<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    SbrCam.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <math.h>
#include "SbrCam.hh"
#include "SbrRenW.hh"
#include "SbrRen.hh"

static float xform[4][4] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};

// typecast if neccessary
void vlSbrCamera::Render(vlRenderer *ren)
{
  this->Render((vlSbrRenderer *)ren);
}

// set the appropriate attributes in Sbr for this camera
//
void vlSbrCamera::Render(vlSbrRenderer *ren)
{
  float aspect[3];
  float *viewport;
  float *background;
  int	width,height;
  long clr;
  int left,right,bottom,top;
  long xmax,ymax,zmax;
  float twist;
  int stereo;
  int fd;
  camera_arg cam;
  int *size;
  int *screen_size;
  vlSbrRenderWindow *rw;

  fd = ren->GetFd();

  // find out if we should stereo render
  stereo = ren->GetStereoRender();

  // set up the view specification
  cam.field_of_view = this->ViewAngle;
  cam.front = this->ClippingRange[0] - this->Distance;
  cam.back = this->ClippingRange[1] - this->Distance;
  cam.camx = this->Position[0];
  cam.camy = this->Position[1];
  cam.camz = this->Position[2];
  cam.refx = this->FocalPoint[0];
  cam.refy = this->FocalPoint[1];
  cam.refz = this->FocalPoint[2];
  cam.upx = this->ViewUp[0];
  cam.upy = this->ViewUp[1];
  cam.upz = this->ViewUp[2];
  cam.projection = CAM_PERSPECTIVE;

  // set this renderer's viewport, must turn off z-buffering when changing
  // viewport
  hidden_surface(fd, FALSE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: False False\n");

  viewport = ren->GetViewport();
  // get the background color
  background = ren->GetBackground();

  // get size info
  rw = (vlSbrRenderWindow*)(ren->GetRenderWindow());
  size = rw->GetSize();
  screen_size = rw->GetScreenSize();

  // make sure the aspect is up to date
  if (size[0] > size[1])
    {
    aspect[0] = size[0]/size[1];
    aspect[1] = 1.0;
    }
  else
    {
    aspect[0] = 1.0;
    aspect[1] = size[1]/size[0];
    }
  ren->SetAspect(aspect);

  vdc_extent(fd,0.0,-screen_size[1]/size[1]+1.0,0.0,
	     screen_size[0]/size[0],1.0,1.0);

  // set viewport to clear entire window
  view_port(fd, viewport[0], viewport[1],
	    viewport[2], viewport[3]);

  hidden_surface(fd, TRUE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: True False\n");

  // Set the background color and clear the display.
  // Since clear control was set to clear z buffer, this is done here
  // also.
  background_color(fd, background[0], background[1], background[2]);

  // clear the view surface so the new background color takes effect
  if (ren->GetErase())
    {
    clear_view_surface(fd);
    vlDebugMacro(<< " SB_clear_view_surface\n");
    }

  hidden_surface(fd, FALSE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: False False\n");

  vdc_extent(fd,0.0,-screen_size[1]/size[1]+1.0,0.0,
	     screen_size[0]/size[0],1.0,1.0);
  view_port(fd, viewport[0], viewport[1],
	    viewport[2], viewport[3]);

  hidden_surface(fd, TRUE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: True False\n");

  // install the camera
  view_camera(fd, &cam);

  // now handle the anisotropy
  xform[0][0] = 1.0/aspect[0];
  xform[1][1] = 1.0/aspect[1];
  xform[3][1] = (1.0 - xform[1][1])/2.0;
  xform[3][0] = (1.0 - xform[0][0])/2.0;
  view_matrix3d(fd, xform, POST_CONCAT_VW);

  // if we have a stereo renderer, draw other eye next time
  if (stereo)
    {
    if (this->LeftEye) this->LeftEye = 0;
    else this->LeftEye = 1;
    }
}
<commit_msg>fixed a tricky camera problem<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    SbrCam.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <math.h>
#include "SbrCam.hh"
#include "SbrRenW.hh"
#include "SbrRen.hh"

static float xform[4][4] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};

// typecast if neccessary
void vlSbrCamera::Render(vlRenderer *ren)
{
  this->Render((vlSbrRenderer *)ren);
}

// set the appropriate attributes in Sbr for this camera
//
void vlSbrCamera::Render(vlSbrRenderer *ren)
{
  float aspect[3];
  float vaspect[2];
  float *viewport;
  float *background;
  int	width,height;
  long clr;
  int left,right,bottom,top;
  long xmax,ymax,zmax;
  float twist;
  int stereo;
  int fd;
  camera_arg cam;
  int *size;
  int *screen_size;
  vlSbrRenderWindow *rw;
  float trans[2];
  float old;

  fd = ren->GetFd();

  // find out if we should stereo render
  stereo = ren->GetStereoRender();

  // set up the view specification
  cam.field_of_view = this->ViewAngle;
  cam.front = this->ClippingRange[0] - this->Distance;
  cam.back = this->ClippingRange[1] - this->Distance;
  cam.camx = this->Position[0];
  cam.camy = this->Position[1];
  cam.camz = - this->Position[2];
  cam.refx = this->FocalPoint[0];
  cam.refy = this->FocalPoint[1];
  cam.refz = - this->FocalPoint[2];
  cam.upx = this->ViewUp[0];
  cam.upy = this->ViewUp[1];
  cam.upz = - this->ViewUp[2];
  cam.projection = CAM_PERSPECTIVE;

  // set this renderer's viewport, must turn off z-buffering when changing
  // viewport
  hidden_surface(fd, FALSE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: False False\n");

  viewport = ren->GetViewport();
  // get the background color
  background = ren->GetBackground();

  // get size info
  rw = (vlSbrRenderWindow*)(ren->GetRenderWindow());
  size = rw->GetSize();
  screen_size = rw->GetScreenSize();

  // make sure the aspect is up to date
  if (size[0] > size[1])
    {
    aspect[0] = size[0]/(float)size[1];
    aspect[1] = 1.0;
    }
  else
    {
    aspect[0] = 1.0;
    aspect[1] = size[1]/(float)size[0];
    }
  ren->SetAspect(aspect);

  vdc_extent(fd,0.0,-screen_size[1]/(float)size[1]+1.0,0.0,
	     screen_size[0]/(float)size[0],1.0,1.0);
  vlDebugMacro(<< " screen_size " << screen_size[0] << " "
  << screen_size[1] << endl);

  vlDebugMacro(<< " size " << size[0] << " " << size[1] << endl);
  vlDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1]
  << " " << viewport[2] << " " << viewport[3] << endl);

  // set viewport to clear entire window
  view_port(fd, viewport[0], viewport[1],
	    viewport[2], viewport[3]);

  hidden_surface(fd, TRUE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: True False\n");

  // Set the background color and clear the display.
  // Since clear control was set to clear z buffer, this is done here
  // also.
  background_color(fd, background[0], background[1], background[2]);

  // clear the view surface so the new background color takes effect
  if (ren->GetErase())
    {
    clear_view_surface(fd);
    vlDebugMacro(<< " SB_clear_view_surface\n");
    }

  hidden_surface(fd, FALSE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: False False\n");

  vdc_extent(fd,0.0,-screen_size[1]/(float)size[1]+1.0,0.0,
	     screen_size[0]/(float)size[0],1.0,1.0);
  view_port(fd, viewport[0], viewport[1],
	    viewport[2], viewport[3]);

  hidden_surface(fd, TRUE, FALSE);
  vlDebugMacro(<< " SB_hidden_surface: True False\n");

  // install the camera
  view_camera(fd, &cam);

  // calculate the viewport aspect
  // we basically compensate for starbases attempt to compensate for
  // non square windows.
  vaspect[0] = viewport[2] - viewport[0];
  vaspect[1] = viewport[3] - viewport[1];
  if ((vaspect[0] >= vaspect[1])&&(aspect[0] <= aspect[1]))
    {
    old = vaspect[0];
    vaspect[0] = aspect[0]*vaspect[1]/old;
    vaspect[1] = aspect[1]*vaspect[1]/old;
    }
  else
    {
    if ((vaspect[0] <= vaspect[1])&&(aspect[0] >= aspect[1]))
      {
      old = vaspect[1];
      vaspect[1] = aspect[1]*vaspect[0]/old;
      vaspect[0] = aspect[0]*vaspect[0]/old;
      }
    }

  // another try
  trans[0] = (viewport[2] + viewport[0])*(1.0 - 1.0/vaspect[0])/2.0;
  trans[1] = (viewport[3] + viewport[1])*(1.0 - 1.0/vaspect[1])/2.0;

  // now handle the anisotropy
  xform[0][0] = 1.0/vaspect[0];
  xform[1][1] = 1.0/vaspect[1];
  xform[3][1] = trans[1];
  xform[3][0] = trans[0];
  view_matrix3d(fd, xform, POST_CONCAT_VW);

  // if we have a stereo renderer, draw other eye next time
  if (stereo)
    {
    if (this->LeftEye) this->LeftEye = 0;
    else this->LeftEye = 1;
    }
}
<|endoftext|>


<commit_before>/*
 * State.cpp
 * Contains all the information of a state
 *
 */

#ifndef PINBALL_BOT_STATE
#define PINBALL_BOT_STATE

#include "Ball.cpp"

class State{

	private:

		//Ball* ball; //Pointer to the ball inside the simulation

	public:

		/**
		 * Gets the expected reward based on a lookup table and the model of the environment
		 * @param	s	State	The State of which the reward is calculated
		 * @return		double	The expected reward
		 */

		double getReward(State s){

			return 0.0;
		}

		/**
		 * Calculates the expected value the given state will in the next turn and in the future => convergence
		 * @param	s	State	The State of which the value is calculated
		 * @return		double	The expected value
		 */

		double getValue(State s){

			return 0.0;
		}

};

#endif /* PINBALL_BOT_STATE */
<commit_msg>Updated State class<commit_after>/*
 * State.cpp
 * Contains all the information of a state
 *
 */

#ifndef PINBALL_BOT_STATE
#define PINBALL_BOT_STATE

#include "Ball.cpp"

#include <iostream>
#include <vector>
#include <random>

class State{

	private:

		//Ball* ball; //Pointer to the ball inside the simulation

		/**
		 * Generates a seed.
		 * @return	void
		 */
		static unsigned int seed(){
			return (unsigned int) rand();//FIXME not a good solution, but works for now.
		}

		/**
		 * Generates a pseudo-random float
		 * @param	min		float		The minimum possible number to generate [included]
		 * @param	max		float		The maximum possible number to generate [included]
		 * @return			float		The pseudo random number
		 */
		static float randomFloatInRange(float min, float max){
			std::default_random_engine					generator(seed());

			std::uniform_real_distribution<float>		distribution
			= std::uniform_real_distribution<float>(min, max);

			return distribution(generator);
		}

		/**
		 * Generates a pseudo-random int
		 * @param	min		int			The minimum possible number to generate [included]
		 * @param	max		int			The maximum possible number to generate [included]
		 * @return			int			The pseudo random number
		 */
		static int randomIntInRange(int min, int max){
			std::default_random_engine					generator(seed());

			std::uniform_int_distribution<int>		distribution
				= std::uniform_int_distribution<int>(min, max);

			return distribution(generator);
		}

	public:

		//inits a state
		State(){

		}

		/**
		 * Gets the expected reward based on a lookup table and the model of the environment
		 * @param	s	State	The State of which the reward is calculated
		 * @return		double	The expected reward
		 */

		float getReward(){

			return 0.0f;
		}

		/**
		 * Calculates the expected value the given state will in the next turn and in the future => convergence
		 * @param	s	State	The State of which the value is calculated
		 * @return		double	The expected value
		 */

		float getValue(){

			return 0.0f;
		}

		/**
		 * Returns one state inside of a vector based on a epsilon greedy algorithm
		 * @param	states		std::vector<State>		A vector containing all the possible states
		 * @param	epsilon		float					Range: [0-1]: The percentage of time, which this function should pick a random state
		 * @return				State					The picked state
		 */
		static State epsilonGreedy(std::vector<State> states, float epsilon){
			if(epsilon < randomFloatInRange(0.0f, 1.0f)){
				//pick a greedy state
				return greedy(states);
			}else{
				//pick a random state
				return random(states);
			}
		}

		/**
		 * Picks the state with the highest value
		 * @param	states		std::vector<State>		A vector containing all the possible states
		 * @return				State					The picked state
		 */
		static State greedy(std::vector<State> states){
			int					maxValue = 0;
			float				tmpValue;
			std::vector<State>	maxStates;
			for(int i=1;i<states.size();i++){
				tmpValue		= states[i].getValue();

				if(tmpValue > maxValue){
					maxValue = tmpValue;

					maxStates.clear();
					maxStates.push_back(states[i]);
				}else if(tmpValue == maxValue){
					maxStates.push_back(states[i]);
				}
			}

			if(maxStates.size() == 1){
				return maxStates[0];
			}else{
				return random(maxStates);
			}
		}

		/**
		 * Picks a random state
		 * @param	states		std::vector<State>		A vector containing all the possible states
		 * @return				State					The picked state
		 */
		static State random(std::vector<State> states){
			return states[randomIntInRange(0, states.size()-1)];
		}

};

#endif /* PINBALL_BOT_STATE */
<|endoftext|>


<commit_before>/*  cbr
 *  Timer.cpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of cbr nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Timer.hpp"

namespace CBR {

Timer::Timer() {
}

Timer::~Timer() {
}
static boost::posix_time::ptime gEpoch(boost::posix_time::time_from_string(std::string("2009-03-12 23:59:59.000")));
Time Timer::getSpecifiedDate(const std::string&dat) {
    boost::posix_time::time_duration since_epoch=boost::posix_time::time_from_string(dat)-gEpoch;
    return Time(since_epoch.total_microseconds());
}
void Timer::start() {
    mStart = boost::posix_time::microsec_clock::local_time();
}
Time Timer::getTimerStarted() const{
    boost::posix_time::time_duration since_start =mStart-gEpoch;
    return Time(since_start.total_microseconds());
}
Duration Timer::sOffset=Duration::seconds(0.0f);
void Timer::setSystemClockOffset(const Duration&skew) {
    sOffset=skew;
}

Time Timer::now() {
    boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time()-gEpoch;
    return Time( since_start.total_microseconds() )+sOffset;
}

Duration Timer::elapsed() const{
    boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time() - mStart;
    return Duration( since_start.total_microseconds() )+sOffset;
}

} // namespace CBR
<commit_msg>Timers elapsed time shouldn't be affected by the offset to the central clock.<commit_after>/*  cbr
 *  Timer.cpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of cbr nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "Timer.hpp"

namespace CBR {

Timer::Timer() {
}

Timer::~Timer() {
}
static boost::posix_time::ptime gEpoch(boost::posix_time::time_from_string(std::string("2009-03-12 23:59:59.000")));
Time Timer::getSpecifiedDate(const std::string&dat) {
    boost::posix_time::time_duration since_epoch=boost::posix_time::time_from_string(dat)-gEpoch;
    return Time(since_epoch.total_microseconds());
}
void Timer::start() {
    mStart = boost::posix_time::microsec_clock::local_time();
}
Time Timer::getTimerStarted() const{
    boost::posix_time::time_duration since_start =mStart-gEpoch;
    return Time(since_start.total_microseconds());
}
Duration Timer::sOffset=Duration::seconds(0.0f);
void Timer::setSystemClockOffset(const Duration&skew) {
    sOffset=skew;
}

Time Timer::now() {
    boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time()-gEpoch;
    return Time( since_start.total_microseconds() )+sOffset;
}

Duration Timer::elapsed() const{
    boost::posix_time::time_duration since_start = boost::posix_time::microsec_clock::local_time() - mStart;
    return Duration( since_start.total_microseconds() );
}

} // namespace CBR
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 3/14/2020, 9:19:13 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

vector<string> concat(string A, string B)
{
  int N{static_cast<int>(A.size())};
  vector<string> ans;
  for (auto i = 0; i <= N; ++i)
  {
    bool ok{true};
    for (auto j = i; j < N; ++j)
    {
      if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?')
      {
        continue;
      }
      else
      {
        ok = false;
        break;
      }
    }
    if (ok)
    {
      stringstream SS;
      for (auto j = 0; j < i; ++j)
      {
        SS << A[j];
      }
      for (auto j = i; j < N; ++j)
      {
        if (A[j] == '?')
        {
          SS << B[j - i];
        }
        else
        {
          SS << A[j];
        }
      }
      for (auto j = N - i; j < static_cast<int>(B.size()); ++j)
      {
        SS << B[j];
      }
      ans.push_back(SS.str());
    }
  }
  return ans;
}

int concat(vector<string> const &V, string B)
{
  int ans{10000};
  for (auto const &A : V)
  {
    int N{static_cast<int>(A.size())};
    for (auto i = 0; i <= N; ++i)
    {
      bool ok{true};
      for (auto j = i; j < N; ++j)
      {
        if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?')
        {
          continue;
        }
        else
        {
          ok = false;
          break;
        }
      }
      if (ok)
      {
        ch_max(ans, N + static_cast<int>(B.size()) - i);
        break;
      }
    }
  }
  return ans;
}

int solve(vector<string> W)
{
  return concat(concat(W[0], W[1]), W[2]);
}

int main()
{
  vector<string> V(3);
  for (auto i = 0; i < 3; ++i)
  {
    cin >> V[i];
  }
  vector<int> O{0, 1, 2};
  int ans{10000};
  do
  {
    vector<string> W(3);
    for (auto i = 0; i < 3; ++i)
    {
      W[i] = V[O[i]];
    }
    ch_min(ans, solve(W));
  } while (next_permutation(O.begin(), O.end()));
  cout << ans << endl;
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 3/14/2020, 9:19:13 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

vector<string> concat(string A, string B)
{
  int N{static_cast<int>(A.size())};
  vector<string> ans;
  for (auto i = 0; i <= N; ++i)
  {
    bool ok{true};
    for (auto j = i; j < N; ++j)
    {
      if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?')
      {
        continue;
      }
      else
      {
        ok = false;
        break;
      }
    }
    if (ok)
    {
      stringstream SS;
      for (auto j = 0; j < i; ++j)
      {
        SS << A[j];
      }
      for (auto j = i; j < N; ++j)
      {
        if (A[j] == '?')
        {
          SS << B[j - i];
        }
        else
        {
          SS << A[j];
        }
      }
      for (auto j = N - i; j < static_cast<int>(B.size()); ++j)
      {
        SS << B[j];
      }
      ans.push_back(SS.str());
    }
  }
  return ans;
}

int concat(vector<string> const &V, string B)
{
  int ans{10000};
  for (auto const &A : V)
  {
    int N{static_cast<int>(A.size())};
    for (auto i = 0; i <= N; ++i)
    {
      bool ok{true};
      for (auto j = i; j < N; ++j)
      {
        if (A[j] == B[j - i] || A[j] == '?' || B[j - i] == '?')
        {
          continue;
        }
        else
        {
          ok = false;
          break;
        }
      }
      if (ok)
      {
        ch_min(ans, N + static_cast<int>(B.size()) - i);
        break;
      }
    }
  }
  return ans;
}

int solve(vector<string> W)
{
  return concat(concat(W[0], W[1]), W[2]);
}

int main()
{
  vector<string> V(3);
  for (auto i = 0; i < 3; ++i)
  {
    cin >> V[i];
  }
  vector<int> O{0, 1, 2};
  int ans{10000};
  do
  {
    vector<string> W(3);
    for (auto i = 0; i < 3; ++i)
    {
      W[i] = V[O[i]];
    }
    ch_min(ans, solve(W));
  } while (next_permutation(O.begin(), O.end()));
  cout << ans << endl;
}
<|endoftext|>


<commit_before>/*
 * UiMgr.cpp
 *
 *  Created on: Apr 12, 2017
 *      Author: chad
 *      Editied: Hadi Rumjahn, Gage Thomas, Jake Shepard
 */

#include <UiMgr.h>
#include <engine.h>

template <typename StorageType>
bool contains(const StorageType item, const StorageType data[], const int len) {

    //Iterates through all values in the array
    for(int index = 0; index < len; index++){

        //If the data was found, return true
        if(data[index] == item) {

            return true;

        }

    }

    //Item was not found
    return false;

}

Token getMyToken(std::ifstream &fin, const char delims[], const int len){

    char character;

    bool leadWS = true, foundDelim = false;;

    Token result;

    //Initialize the token result
    result.data = "";

    //Loops until the file is empty or a deliminator is reached (after leading
    //whitespace is eliminated)
    while(!fin.eof() && !foundDelim) {

        fin.get(character);

        //If the character was not whitespace, set the flag
        if(leadWS && !(character == ' ' || character == '\t' || character == '\n')) {

            leadWS = false;

        }

        //If not processing leading whitespace
        if(!leadWS){

            //If a deliminator is reached after leading whitespace, end loop
            if(contains(character, delims, len)) {

                result.endDelim = character;
                foundDelim = true;

            } else {

                result.data += character;//Else, append the current char

            }
        }

    }

    //If a deliminator was not found, return an empty string
    if(!foundDelim) {

        Token failResult;
        failResult.data = "";
        return failResult;

    } else {//Else return the token

        return result;
    }

}

UiMgr::UiMgr(Engine* eng): Mgr(eng){
	// Initialize the OverlaySystem (changed for Ogre 1.9)
	    mOverlaySystem = new Ogre::OverlaySystem();
	    engine->gfxMgr->ogreSceneManager->addRenderQueueListener(mOverlaySystem);
	    mTrayMgr = 0;
	    timeMonitor = 0;
	    gameOverLabel = 0;
	    highScores = 0;
	    nameLabel = 0;
	    yourName = 0;//Not a rating for the movie, that movie was good
	    creditsButton = 0;
	    credits = 0;
	    playerSurvived = false;

	    //Ogre::WindowEventUtilities::addWindowEventListener(engine->gfxMgr->ogreRenderWindow, this);
}

UiMgr::~UiMgr(){ // before gfxMgr destructor

}

void UiMgr::init(){
	//init sdktrays

    mInputContext.mKeyboard = engine->inputMgr->keyboard;
    mInputContext.mMouse = engine->inputMgr->mouse;
    mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", engine->gfxMgr->ogreRenderWindow, mInputContext, this);
    //mTrayMgr->hideCursor();
}

void UiMgr::stop()
{

}

void UiMgr::loadLevel(){
	mTrayMgr->hideCursor();
	timeMonitor = mTrayMgr->createLabel(OgreBites::TL_TOP, "Timer", timeAsString(engine->gameMgr->gameplayTime));
	//timeMonitor->getOverlayElement()->setMaterialName("TransparentBackground.png");//Not working for some reason
}

void UiMgr::loadGameOver(bool survived)
{
	playerSurvived = survived;
	int width = engine->gfxMgr->ogreRenderWindow->getWidth();
	int height = engine->gfxMgr->ogreRenderWindow->getHeight();

	if(!survived) {
		gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Died!");
	} else
	{
		gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Survived!");
	}
	gameOverLabel->getOverlayElement()->setPosition((width / 2) - (gameOverLabel->getOverlayElement()->getWidth() / 2), 300);
	yourName = mTrayMgr->createLabel(OgreBites::TL_NONE, "YourName", "Your name:");
	yourName->getOverlayElement()->setPosition((width / 2) - (yourName->getOverlayElement()->getWidth() / 2), 340);
	mTrayMgr->showCursor();
	nameLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "NameLabel", "");
	nameLabel->getOverlayElement()->setPosition((width / 2) - (nameLabel->getOverlayElement()->getWidth() / 2), 380);

	//Handle the credits
	creditsButton = mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "CreditsButton", "Credits");
	credits = mTrayMgr->createTextBox(OgreBites::TL_NONE, "Credits", "Credits:", 300, 600);
	credits->getOverlayElement()->setPosition(width - 300, height - 50 - 600);
	credits->setText(getCredits());
	//Do not center it, it alligns the left of the string with the center
	credits->hide(); //For some reason if this call is made now, the text gets cleared
	credits->setText(getCredits());

}

std::string UiMgr::getCredits()
{
	return "Cries\n\nPresented by Code R3d\n\nGage Thomas\n\nJake Shepherd\n\nHadi Rumjahn\n";
}

void UiMgr::loadHighScores(bool survived)
{
	std::string names[10];
	float scores[10];
	std::ifstream fin;
	std::string filename;
	int width = engine->gfxMgr->ogreRenderWindow->getWidth();
	bool playerUsed = false;
	if(survived)
	{
		filename = "HighScoresSurvived.txt";
	} else
	{
		filename = "HighScoresDied.txt";
	}
	fin.open(filename);

	//Enter all the information into the two arrays
	for(int index = 0; index < 10; index++)
	{
		Token nextToken = getMyToken(fin, COLON, 1);//gets the name
		Token scoreToken = getMyToken(fin, WHITESPACE, 3);
		float nextScore = stof(scoreToken.data);

		//If the player beat the score
		if((survived && engine->gameMgr->gameplayTime < nextScore && !playerUsed) ||
				(!survived && engine->gameMgr->gameplayTime > nextScore && !playerUsed))
		{
			playerUsed = true;
			if(nameLabel->getCaption().length() == 0)
			{
				names[index] = "Kira";
			} else
			{
				names[index] = nameLabel->getCaption();
			}
			scores[index] = engine->gameMgr->gameplayTime;
			index++;
		}
		//Now handle the current score, so long as the player's score didn't push
		//index past 10
		if(index < 10)
		{
			names[index] = nextToken.data;
			scores[index] = nextScore;
		}
	}
	fin.close();
	std::ofstream fout;
	fout.open(filename);

	//Now write the new high scores to file
	for(int index = 0; index < 10; index++)
	{
		fout << names[index] << ": " << scores[index] << std::endl;
	}
	fout << std::endl;
	fout.close();

	//Now display the high scores
	yourName->hide();
	nameLabel->hide();
	std::string scoresText = "";
	for(int index = 0; index < 10; index++)
	{
		scoresText += std::to_string(index + 1) + ". " + names[index] + ": " + timeAsString(scores[index]) + "\n\n";
	}
	highScores = mTrayMgr->createTextBox(OgreBites::TL_NONE, "HighScores", "High Scores:", 300, 600);
	highScores->getOverlayElement()->setPosition((width / 2) - (highScores->getOverlayElement()->getWidth() / 2), 340);

	highScores->setText(scoresText);
}

void UiMgr::tick(float dt){
	mTrayMgr->refreshCursor();
	//Update the time since last event if in splash screen
	if(engine->theState == STATE::SPLASH)
	{
		engine->timeSinceLastEvent += dt;
		//If 3 seconds have passed, go into gameplay
		if(engine->timeSinceLastEvent >= 3)
		{
			engine->theState = STATE::MAIN_MENU;
			engine->gfxMgr->loadMenu();

			loadMenu();//Creates the button
		}
	} else if(engine->theState == STATE::GAMEPLAY)
	{
		timeMonitor->setCaption(timeAsString(engine->gameMgr->gameplayTime));
	} else if(engine->theState == STATE::GAMEOVER)
	{

	}
}

void UiMgr::windowResized(Ogre::RenderWindow* rw){
	unsigned int width, height, depth;
	int left, top;
	rw->getMetrics(width, height, depth, left, top);

	const OIS::MouseState &ms = engine->inputMgr->mouse->getMouseState();
	ms.width = width;
	ms.height = height;
}

void UiMgr::windowClosed(Ogre::RenderWindow* rw){

}

bool UiMgr::keyPressed(const OIS::KeyEvent &arg) {
	std::cout << "Key Pressed: " << arg.key << std::endl;
	return true;
}
bool UiMgr::keyReleased(const OIS::KeyEvent &arg){
	return true;
}
bool UiMgr::mouseMoved(const OIS::MouseEvent &arg){
    if (mTrayMgr->injectMouseMove(arg)) return true;
    /* normal mouse processing here... */
	return true;
}
bool UiMgr::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id) {
	std::cout << "mouse clicked" << std::endl;
	if (mTrayMgr->injectMouseDown(arg, id)) return true;
	    /* normal mouse processing here... */
	return true;
}
bool UiMgr::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id){
    if (mTrayMgr->injectMouseUp(arg, id)) return true;
    /* normal mouse processing here... */
	return true;
}

void UiMgr::buttonHit(OgreBites::Button *b){
    if(b->getName()=="NewGame")
    {
        std::cout <<"New Game pressed" << std::endl;
        engine->theState = STATE::GAMEPLAY;
        engine->loadLevel();
        mTrayMgr->destroyWidget(b);
    } else if(b->getName() == "CreditsButton")
    {
    	if(credits->isVisible())
    	{
    		credits->hide();
    	} else
    	{
    		credits->setText(getCredits());
    		credits->show();
    	}
    }

}

void UiMgr::itemSelected(OgreBites::SelectMenu *m){
    if(m->getName()=="MyMenu")
    {
        std::cout <<"Menu!" << std::endl;
    }

}

void UiMgr::loadMenu()
{
	mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "NewGame", "New Game");

	// LOAD MAIN MENU SOUND
	engine->soundMgr->load_song("Menu", "resources/Cries - Theme.ogg");
	//load_sound(std::string soundName, std::string filePath);

	//play_sound(std::string soundName);
	engine->soundMgr->play_song2D("Menu", true);

}

std::string UiMgr::timeAsString(float time)
{
	std::string result = "";
	int resultTime = (int) time;
	int seconds = resultTime % 60;
	int minutes = resultTime / 60;
	if(minutes < 10)
	{
		result += "0";
	}
	result += std::to_string(minutes) + ":";
	if(seconds < 10)
	{
		result += "0";
	}
	result += std::to_string(seconds);

	return result;
}
<commit_msg>Fixing merge conflicts<commit_after>/*
 * UiMgr.cpp
 *
 *  Created on: Apr 12, 2017
 *      Author: chad
 *      Editied: Hadi Rumjahn, Gage Thomas, Jake Shepard
 */

#include <UiMgr.h>
#include <engine.h>

template <typename StorageType>
bool contains(const StorageType item, const StorageType data[], const int len) {

    //Iterates through all values in the array
    for(int index = 0; index < len; index++){

        //If the data was found, return true
        if(data[index] == item) {

            return true;

        }

    }

    //Item was not found
    return false;

}

Token getMyToken(std::ifstream &fin, const char delims[], const int len){

    char character;

    bool leadWS = true, foundDelim = false;;

    Token result;

    //Initialize the token result
    result.data = "";

    //Loops until the file is empty or a deliminator is reached (after leading
    //whitespace is eliminated)
    while(!fin.eof() && !foundDelim) {

        fin.get(character);

        //If the character was not whitespace, set the flag
        if(leadWS && !(character == ' ' || character == '\t' || character == '\n')) {

            leadWS = false;

        }

        //If not processing leading whitespace
        if(!leadWS){

            //If a deliminator is reached after leading whitespace, end loop
            if(contains(character, delims, len)) {

                result.endDelim = character;
                foundDelim = true;

            } else {

                result.data += character;//Else, append the current char

            }
        }

    }

    //If a deliminator was not found, return an empty string
    if(!foundDelim) {

        Token failResult;
        failResult.data = "";
        return failResult;

    } else {//Else return the token

        return result;
    }

}

UiMgr::UiMgr(Engine* eng): Mgr(eng){
	// Initialize the OverlaySystem (changed for Ogre 1.9)
	    mOverlaySystem = new Ogre::OverlaySystem();
	    engine->gfxMgr->ogreSceneManager->addRenderQueueListener(mOverlaySystem);
	    mTrayMgr = 0;
	    timeMonitor = 0;
	    gameOverLabel = 0;
	    highScores = 0;
	    nameLabel = 0;
	    yourName = 0;//Not a rating for the movie, that movie was good
	    creditsButton = 0;
	    credits = 0;
	    playerSurvived = false;

	    //Ogre::WindowEventUtilities::addWindowEventListener(engine->gfxMgr->ogreRenderWindow, this);
}

UiMgr::~UiMgr(){ // before gfxMgr destructor

}

void UiMgr::init(){
	//init sdktrays

    mInputContext.mKeyboard = engine->inputMgr->keyboard;
    mInputContext.mMouse = engine->inputMgr->mouse;
    mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", engine->gfxMgr->ogreRenderWindow, mInputContext, this);
    //mTrayMgr->hideCursor();
}

void UiMgr::stop()
{

}

void UiMgr::loadLevel(){
	mTrayMgr->hideCursor();
	timeMonitor = mTrayMgr->createLabel(OgreBites::TL_TOP, "Timer", timeAsString(engine->gameMgr->gameplayTime));
	//timeMonitor->getOverlayElement()->setMaterialName("TransparentBackground.png");//Not working for some reason
}

void UiMgr::loadGameOver(bool survived)
{
	playerSurvived = survived;
	int width = engine->gfxMgr->ogreRenderWindow->getWidth();
	int height = engine->gfxMgr->ogreRenderWindow->getHeight();

	if(!survived) {
		gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Died!");
	} else
	{
		gameOverLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "GameOverLabel", "You Survived!");
	}
	gameOverLabel->getOverlayElement()->setPosition((width / 2) - (gameOverLabel->getOverlayElement()->getWidth() / 2), 300);
	yourName = mTrayMgr->createLabel(OgreBites::TL_NONE, "YourName", "Your name:");
	yourName->getOverlayElement()->setPosition((width / 2) - (yourName->getOverlayElement()->getWidth() / 2), 340);
	mTrayMgr->showCursor();
	nameLabel = mTrayMgr->createLabel(OgreBites::TL_NONE, "NameLabel", "");
	nameLabel->getOverlayElement()->setPosition((width / 2) - (nameLabel->getOverlayElement()->getWidth() / 2), 380);

	//Handle the credits
	creditsButton = mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "CreditsButton", "Credits");
	credits = mTrayMgr->createTextBox(OgreBites::TL_NONE, "Credits", "Credits:", 300, 600);
	credits->getOverlayElement()->setPosition(width - 300, height - 50 - 600);
	credits->setText(getCredits());
	//Do not center it, it alligns the left of the string with the center
	credits->hide(); //For some reason if this call is made now, the text gets cleared
	credits->setText(getCredits());

}

std::string UiMgr::getCredits()
{
	return "Cries\n\nPresented by Code R3d\n\nGage Thomas\n\nJake Shepherd\n\nHadi Rumjahn\n";
}

void UiMgr::loadHighScores(bool survived)
{
	std::string names[10];
	float scores[10];
	std::ifstream fin;
	std::string filename;
	int width = engine->gfxMgr->ogreRenderWindow->getWidth();
	bool playerUsed = false;
	if(survived)
	{
		filename = "HighScoresSurvived.txt";
	} else
	{
		filename = "HighScoresDied.txt";
	}
	fin.open(filename);

	//Enter all the information into the two arrays
	for(int index = 0; index < 10; index++)
	{
		Token nextToken = getMyToken(fin, COLON, 1);//gets the name
		Token scoreToken = getMyToken(fin, WHITESPACE, 3);
		float nextScore = stof(scoreToken.data);

		//If the player beat the score
		if((survived && engine->gameMgr->gameplayTime < nextScore && !playerUsed) ||
				(!survived && engine->gameMgr->gameplayTime > nextScore && !playerUsed))
		{
			playerUsed = true;
			if(nameLabel->getCaption().length() == 0)
			{
				names[index] = "Kira";
			} else
			{
				names[index] = nameLabel->getCaption();
			}
			scores[index] = engine->gameMgr->gameplayTime;
			index++;
		}
		//Now handle the current score, so long as the player's score didn't push
		//index past 10
		if(index < 10)
		{
			names[index] = nextToken.data;
			scores[index] = nextScore;
		}
	}
	fin.close();
	std::ofstream fout;
	fout.open(filename);

	//Now write the new high scores to file
	for(int index = 0; index < 10; index++)
	{
		fout << names[index] << ": " << scores[index] << std::endl;
	}
	fout << std::endl;
	fout.close();

	//Now display the high scores
	yourName->hide();
	nameLabel->hide();
	std::string scoresText = "";
	for(int index = 0; index < 10; index++)
	{
		scoresText += std::to_string(index + 1) + ". " + names[index] + ": " + timeAsString(scores[index]) + "\n\n";
	}
	highScores = mTrayMgr->createTextBox(OgreBites::TL_NONE, "HighScores", "High Scores:", 300, 600);
	highScores->getOverlayElement()->setPosition((width / 2) - (highScores->getOverlayElement()->getWidth() / 2), 340);

	highScores->setText(scoresText);
}

void UiMgr::tick(float dt){
	mTrayMgr->refreshCursor();
	//Update the time since last event if in splash screen
	if(engine->theState == STATE::SPLASH)
	{
		engine->timeSinceLastEvent += dt;
		//If 3 seconds have passed, go into gameplay
		if(engine->timeSinceLastEvent >= 3)
		{
			engine->theState = STATE::MAIN_MENU;
			engine->gfxMgr->loadMenu();

			loadMenu();//Creates the button
		}
	} else if(engine->theState == STATE::GAMEPLAY)
	{
		timeMonitor->setCaption(timeAsString(engine->gameMgr->gameplayTime));
	} else if(engine->theState == STATE::GAMEOVER)
	{

	}
}

void UiMgr::windowResized(Ogre::RenderWindow* rw){
	unsigned int width, height, depth;
	int left, top;
	rw->getMetrics(width, height, depth, left, top);

	const OIS::MouseState &ms = engine->inputMgr->mouse->getMouseState();
	ms.width = width;
	ms.height = height;
}

void UiMgr::windowClosed(Ogre::RenderWindow* rw){

}

bool UiMgr::keyPressed(const OIS::KeyEvent &arg) {
	std::cout << "Key Pressed: " << arg.key << std::endl;
	return true;
}
bool UiMgr::keyReleased(const OIS::KeyEvent &arg){
	return true;
}
bool UiMgr::mouseMoved(const OIS::MouseEvent &arg){
    if (mTrayMgr->injectMouseMove(arg)) return true;
    /* normal mouse processing here... */
	return true;
}
bool UiMgr::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id) {
	std::cout << "mouse clicked" << std::endl;
	if (mTrayMgr->injectMouseDown(arg, id)) return true;
	    /* normal mouse processing here... */
	return true;
}
bool UiMgr::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id){
    if (mTrayMgr->injectMouseUp(arg, id)) return true;
    /* normal mouse processing here... */
	return true;
}

void UiMgr::buttonHit(OgreBites::Button *b){
    if(b->getName()=="NewGame")
    {
        std::cout <<"New Game pressed" << std::endl;
        engine->theState = STATE::GAMEPLAY;
        engine->loadLevel();
        mTrayMgr->destroyWidget(b);
    } else if(b->getName() == "CreditsButton")
    {
    	if(credits->isVisible())
    	{
    		credits->hide();
    	} else
    	{
    		credits->setText(getCredits());
    		credits->show();
    	}
    }

}

void UiMgr::itemSelected(OgreBites::SelectMenu *m){
    if(m->getName()=="MyMenu")
    {
        std::cout <<"Menu!" << std::endl;
    }
}

void UiMgr::loadMenu()
{
	mTrayMgr->createButton(OgreBites::TL_BOTTOMRIGHT, "NewGame", "New Game");

	// LOAD MAIN MENU SOUND
	//engine->soundMgr->load_song("Menu", "resources/Cries - Theme.ogg");
	engine->soundMgr->load_song("Menu", "resources/theme.wav");
	//load_sound(std::string soundName, std::string filePath);

	//play_sound(std::string soundName);
	engine->soundMgr->play_song2D("Menu", true);

}

std::string UiMgr::timeAsString(float time)
{
	std::string result = "";
	int resultTime = (int) time;
	int seconds = resultTime % 60;
	int minutes = resultTime / 60;
	if(minutes < 10)
	{
		result += "0";
	}
	result += std::to_string(minutes) + ":";
	if(seconds < 10)
	{
		result += "0";
	}
	result += std::to_string(seconds);

	return result;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: numfmtlb.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:53:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWNUMFMTLB_HXX
#define _SWNUMFMTLB_HXX

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _ZFORLIST_HXX //autogen
#include <svtools/zforlist.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwView;

class SW_DLLPUBLIC NumFormatListBox : public ListBox
{
    short               nCurrFormatType;
    USHORT              nStdEntry;
    BOOL                bOneArea;
    ULONG               nDefFormat;
    SwView*             pVw;
    SvNumberFormatter*  pOwnFormatter;
    LanguageType        eCurLanguage;
    BOOL                bShowLanguageControl; //determine whether the language control has
                                              //to be shown in the number format dialog
    BOOL                bUseAutomaticLanguage;//determine whether language is automatically assigned

    SW_DLLPRIVATE DECL_LINK( SelectHdl, ListBox * );

    SW_DLLPRIVATE double          GetDefValue(const short nFormatType) const;
    SW_DLLPRIVATE void            Init(short nFormatType, BOOL bUsrFmts);
    SW_DLLPRIVATE SwView*           GetView();

public:
    NumFormatListBox( Window* pWin, const ResId& rResId,
        short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0,
        BOOL bUsrFmts = TRUE );

    NumFormatListBox( Window* pWin, SwView* pView, const ResId& rResId,
        short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0,
        BOOL bUsrFmts = TRUE );

    ~NumFormatListBox();

    void            Clear();

    inline void     SetOneArea(BOOL bOnlyOne = TRUE) { bOneArea = bOnlyOne; }

    void            SetFormatType(const short nFormatType);
    inline short    GetFormatType() const { return nCurrFormatType; }
    void            SetDefFormat(const ULONG nDefFmt);
    ULONG           GetFormat() const;

    inline LanguageType GetCurLanguage() const { return eCurLanguage;}
    void                SetLanguage(LanguageType eSet)  { eCurLanguage = eSet;}

    void            SetAutomaticLanguage(BOOL bSet){bUseAutomaticLanguage = bSet;}
    BOOL            IsAutomaticLanguage()const {return bUseAutomaticLanguage;}

    void            SetShowLanguageControl(BOOL bSet){bShowLanguageControl = bSet;}

};

#endif

<commit_msg>INTEGRATION: CWS swwarnings (1.6.710); FILE MERGED 2007/03/26 12:09:08 tl 1.6.710.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: numfmtlb.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:05:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWNUMFMTLB_HXX
#define _SWNUMFMTLB_HXX

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _ZFORLIST_HXX //autogen
#include <svtools/zforlist.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwView;

class SW_DLLPUBLIC NumFormatListBox : public ListBox
{
    short               nCurrFormatType;
    USHORT              nStdEntry;
    BOOL                bOneArea;
    ULONG               nDefFormat;
    SwView*             pVw;
    SvNumberFormatter*  pOwnFormatter;
    LanguageType        eCurLanguage;
    BOOL                bShowLanguageControl; //determine whether the language control has
                                              //to be shown in the number format dialog
    BOOL                bUseAutomaticLanguage;//determine whether language is automatically assigned

    SW_DLLPRIVATE DECL_LINK( SelectHdl, ListBox * );

    SW_DLLPRIVATE double          GetDefValue(const short nFormatType) const;
    SW_DLLPRIVATE void            Init(short nFormatType, BOOL bUsrFmts);
    SW_DLLPRIVATE SwView*           GetView();

public:
    NumFormatListBox( Window* pWin, const ResId& rResId,
        short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0,
        BOOL bUsrFmts = TRUE );

    NumFormatListBox( Window* pWin, SwView* pView, const ResId& rResId,
        short nFormatType = NUMBERFORMAT_NUMBER, ULONG nDefFmt = 0,
        BOOL bUsrFmts = TRUE );

    ~NumFormatListBox();

    void            Clear();

    inline void     SetOneArea(BOOL bOnlyOne = TRUE) { bOneArea = bOnlyOne; }

    void            SetFormatType(const short nFormatType);
    inline short    GetFormatType() const { return nCurrFormatType; }
    void            SetDefFormat(const ULONG nDefFmt);
    ULONG           GetFormat() const;

    inline LanguageType GetCurLanguage() const { return eCurLanguage;}
    void                SetLanguage(LanguageType eSet)  { eCurLanguage = eSet;}

    void            SetAutomaticLanguage(BOOL bSet){bUseAutomaticLanguage = bSet;}
    BOOL            IsAutomaticLanguage()const {return bUseAutomaticLanguage;}

    void            SetShowLanguageControl(BOOL bSet){bShowLanguageControl = bSet;}

};

#endif

<|endoftext|>


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

#include "ActiveMQConnectionSupport.h"

#include <activemq/exceptions/ActiveMQException.h>
#include <activemq/core/ActiveMQConstants.h>

#include <decaf/lang/Boolean.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/exceptions/IllegalArgumentException.h>

using namespace std;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;

////////////////////////////////////////////////////////////////////////////////
ActiveMQConnectionSupport::ActiveMQConnectionSupport(
    const Pointer<transport::Transport>& transport,
    const Pointer<decaf::util::Properties>& properties ) {

    if( transport  == NULL ) {
        throw decaf::lang::exceptions::IllegalArgumentException(
            __FILE__, __LINE__,
            "ActiveMQConnectionSupport::ActiveMQConnectionSupport - "
            "Required Parameter 'transport' was NULL.");
    }

    this->properties = properties;
    this->transport = transport;

    // Check the connection options
    this->setAlwaysSyncSend( Boolean::parseBoolean(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_ALWAYSSYNCSEND ), "false" ) ) );

    this->setUseAsyncSend( Boolean::parseBoolean(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_USEASYNCSEND ), "false" ) ) );

    this->setProducerWindowSize( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_PRODUCERWINDOWSIZE ), "0" ) ) );

    this->setSendTimeout( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_SENDTIMEOUT ), "0" ) ) );

    this->setCloseTimeout( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_CLOSETIMEOUT ), "15000" ) ) );

    this->setClientId( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_CLIENTID ), "" ) );

    this->setUsername( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_USERNAME ), "" ) );

    this->setPassword( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_PASSWORD ), "" ) );
}

////////////////////////////////////////////////////////////////////////////////
ActiveMQConnectionSupport::~ActiveMQConnectionSupport() {
    try{
        this->shutdownTransport();
    }
    AMQ_CATCH_NOTHROW( ActiveMQException )
    AMQ_CATCHALL_NOTHROW()
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQConnectionSupport::startupTransport() throw( decaf::lang::Exception ) {
    try {

        if( this->transport.get()  == NULL ) {
            throw decaf::lang::exceptions::IllegalArgumentException(
                __FILE__, __LINE__,
                "ActiveMQConnectionSupport::startupTransport - "
                "Required Object 'transport' was NULL.");
        }

        this->transport->start();
    }
    AMQ_CATCH_RETHROW( decaf::lang::Exception )
    AMQ_CATCHALL_THROW( decaf::lang::Exception )
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQConnectionSupport::shutdownTransport() throw( decaf::lang::Exception ) {

    bool hasException = false;
    exceptions::ActiveMQException e;

    try {

        if( transport.get() != NULL ){

            try{
                transport->close();
            }catch( exceptions::ActiveMQException& ex ){
                if( !hasException ){
                    hasException = true;
                    ex.setMark(__FILE__, __LINE__ );
                    e = ex;
                }
            }

            try{
                transport.reset( NULL );
            }catch( exceptions::ActiveMQException& ex ){
                if( !hasException ){
                    hasException = true;
                    ex.setMark(__FILE__, __LINE__ );
                    e = ex;
                }
            }
        }

        // If we encountered an exception - throw the first one we encountered.
        // This will preserve the stack trace for logging purposes.
        if( hasException ){
            throw e;
        }
    }
    AMQ_CATCH_RETHROW( decaf::lang::Exception )
    AMQ_CATCHALL_THROW( decaf::lang::Exception )
}
<commit_msg>fix for: http://issues.apache.org/activemq/browse/AMQCPP-290<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ActiveMQConnectionSupport.h"

#include <activemq/exceptions/ActiveMQException.h>
#include <activemq/core/ActiveMQConstants.h>

#include <decaf/lang/Boolean.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/exceptions/IllegalArgumentException.h>

using namespace std;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;

////////////////////////////////////////////////////////////////////////////////
ActiveMQConnectionSupport::ActiveMQConnectionSupport(
    const Pointer<transport::Transport>& transport,
    const Pointer<decaf::util::Properties>& properties ) {

    if( transport  == NULL ) {
        throw decaf::lang::exceptions::IllegalArgumentException(
            __FILE__, __LINE__,
            "ActiveMQConnectionSupport::ActiveMQConnectionSupport - "
            "Required Parameter 'transport' was NULL.");
    }

    this->properties = properties;
    this->transport = transport;

    // Check the connection options
    this->setAlwaysSyncSend( Boolean::parseBoolean(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_ALWAYSSYNCSEND ), "false" ) ) );

    this->setUseAsyncSend( Boolean::parseBoolean(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_USEASYNCSEND ), "false" ) ) );

    this->setProducerWindowSize( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_PRODUCERWINDOWSIZE ), "0" ) ) );

    this->setSendTimeout( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_SENDTIMEOUT ), "0" ) ) );

    this->setCloseTimeout( decaf::lang::Integer::parseInt(
        properties->getProperty(
            core::ActiveMQConstants::toString(
                core::ActiveMQConstants::CONNECTION_CLOSETIMEOUT ), "15000" ) ) );

    this->setClientId( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_CLIENTID ), "" ) );

    this->setUsername( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_USERNAME ), "" ) );

    this->setPassword( properties->getProperty(
        core::ActiveMQConstants::toString(
            core::ActiveMQConstants::PARAM_PASSWORD ), "" ) );
}

////////////////////////////////////////////////////////////////////////////////
ActiveMQConnectionSupport::~ActiveMQConnectionSupport() {
    try{
        this->shutdownTransport();
    }
    AMQ_CATCH_NOTHROW( ActiveMQException )
    AMQ_CATCHALL_NOTHROW()
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQConnectionSupport::startupTransport() throw( decaf::lang::Exception ) {
    try {

        if( this->transport.get()  == NULL ) {
            throw decaf::lang::exceptions::IllegalArgumentException(
                __FILE__, __LINE__,
                "ActiveMQConnectionSupport::startupTransport - "
                "Required Object 'transport' was NULL.");
        }

        this->transport->start();
    }
    AMQ_CATCH_RETHROW( decaf::lang::Exception )
    AMQ_CATCHALL_THROW( decaf::lang::Exception )
}

////////////////////////////////////////////////////////////////////////////////
void ActiveMQConnectionSupport::shutdownTransport() throw( decaf::lang::Exception ) {

    bool hasException = false;
    exceptions::ActiveMQException e;

    try {

        if( transport.get() != NULL ){

            // Clear the listener, we don't care about errors at this point.
            transport->setTransportListener( NULL );

            try{
                transport->close();
            }catch( exceptions::ActiveMQException& ex ){
                if( !hasException ){
                    hasException = true;
                    ex.setMark(__FILE__, __LINE__ );
                    e = ex;
                }
            }

            try{
                transport.reset( NULL );
            }catch( exceptions::ActiveMQException& ex ){
                if( !hasException ){
                    hasException = true;
                    ex.setMark(__FILE__, __LINE__ );
                    e = ex;
                }
            }
        }

        // If we encountered an exception - throw the first one we encountered.
        // This will preserve the stack trace for logging purposes.
        if( hasException ){
            throw e;
        }
    }
    AMQ_CATCH_RETHROW( decaf::lang::Exception )
    AMQ_CATCHALL_THROW( decaf::lang::Exception )
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: delete.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:39:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _CRSSKIP_HXX
#include <crsskip.hxx>
#endif
#ifndef _SWCRSR_HXX
#include <swcrsr.hxx>
#endif
#include <svx/lrspitem.hxx> // #i23725#
// --> OD 2006-07-10 #134369#
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DRAWBASE_HXX
#include <drawbase.hxx>
#endif
// <--

inline void SwWrtShell::OpenMark()
{
    StartAllAction();
    ResetCursorStack();
    KillPams();
    SetMark();
}

inline void SwWrtShell::CloseMark( BOOL bOkFlag )
{
    if( bOkFlag )
        UpdateAttr();
    else
        SwapPam();

    ClearMark();
    EndAllAction();
}

// #i23725#
BOOL SwWrtShell::TryRemoveIndent()
{
    BOOL bResult = FALSE;

    SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE);
    GetAttr(aAttrSet);

    SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE);
    short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst();

    if (aOldFirstLineOfst > 0)
    {
        aItem.SetTxtFirstLineOfst(0);
        bResult = TRUE;
    }
    else if (aOldFirstLineOfst < 0)
    {
        aItem.SetTxtFirstLineOfst(0);
        aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst);

        bResult = TRUE;
    }
    else if (aItem.GetLeft() != 0)
    {
        aItem.SetLeft(0);
        bResult = TRUE;
    }

    if (bResult)
    {
        aAttrSet.Put(aItem);
        SetAttr(aAttrSet);
    }

    return bResult;
}

/*------------------------------------------------------------------------
 Beschreibung:  Zeile loeschen
------------------------------------------------------------------------*/

long SwWrtShell::DelLine()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
        // alten Cursor merken
    Push();
    ClearMark();
    SwCrsrShell::LeftMargin();
    SetMark();
    SwCrsrShell::RightMargin();
//Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden?
//  if(!IsEndOfPara())
//      SwCrsrShell::Right();
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}

long SwWrtShell::DelToStartOfLine()
{
    OpenMark();
    SwCrsrShell::LeftMargin();
    long nRet = Delete();
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelToEndOfLine()
{
    OpenMark();
    SwCrsrShell::RightMargin();
    long nRet = Delete();
    CloseMark( 0 != nRet );
    return 1;
}

long SwWrtShell::DelLeft()
{
    // wenns denn ein Fly ist, wech damit
    int nSelType = GetSelectionType();
    const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW;
    if( nCmp & nSelType )
    {
        /*  #108205# Remember object's position. */
        Point aTmpPt = GetObjRect().TopLeft();

        DelSelectedObj();

        /*  #108205# Set cursor to remembered position. */
        SetCrsr(&aTmpPt);

        LeaveSelFrmMode();
        UnSelectFrm();

        nSelType = GetSelectionType();
        if ( nCmp & nSelType )
        {
            EnterSelFrmMode();
            GotoNextFly();
        }

        return 1L;
    }

    // wenn eine Selektion existiert, diese loeschen.
    if ( IsSelection() )
    {
         //OS: wieder einmal Basic: ACT_KONTEXT muss vor
        //EnterStdMode verlassen werden!
        {
            ACT_KONTEXT(this);
            ResetCursorStack();
            Delete();
            UpdateAttr();
        }
        EnterStdMode();
        return 1L;
    }

    // JP 29.06.95: nie eine davor stehende Tabelle loeschen.
    BOOL bSwap = FALSE;
    const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl();
    if( SwCrsrShell::IsSttPara())
    {
        /* If the cursor is at the beginning of a paragraph, try to step
           backwards. On failure we are done. */
        if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) )
            return 0;

        /* If the cursor entered or left a table (or both) we are done. No step
           back. */
        if( SwCrsrShell::IsCrsrInTbl() != pWasInTblNd )
            return 0;

        OpenMark();
        SwCrsrShell::Right(1,CRSR_SKIP_CHARS);
        SwCrsrShell::SwapPam();
        bSwap = TRUE;
    }
    else
    {
        OpenMark();
        SwCrsrShell::Left(1,CRSR_SKIP_CHARS);
    }
    long nRet = Delete();
    if( !nRet && bSwap )
        SwCrsrShell::SwapPam();
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelRight(BOOL bDelFrm)
{
        // werden verodert, wenn Tabellenselektion vorliegt;
        // wird hier auf SEL_TBL umgesetzt.
    long nRet = 0;
    int nSelection = GetSelectionType();
    if(nSelection & SwWrtShell::SEL_TBL_CELLS)
        nSelection = SwWrtShell::SEL_TBL;
    if(nSelection & SwWrtShell::SEL_TXT)
        nSelection = SwWrtShell::SEL_TXT;

    const SwTableNode * pWasInTblNd = NULL;

    switch( nSelection & ~(SEL_BEZ) )
    {
    case SEL_TXT:
    case SEL_TBL:
    case SEL_NUM:
            //  wenn eine Selektion existiert, diese loeschen.
        if( IsSelection() )
        {
            //OS: wieder einmal Basic: ACT_KONTEXT muss vor
            //EnterStdMode verlassen werden!
            {
                ACT_KONTEXT(this);
                ResetCursorStack();
                Delete();
                UpdateAttr();
            }
            EnterStdMode();
            nRet = 1L;
            break;
        }

        pWasInTblNd = IsCrsrInTbl();

        if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() &&
            SwCrsrShell::IsEndPara() )
        {
            // save cursor
            SwCrsrShell::Push();

            bool bDelFull = false;
            if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) )
            {
                const SwTableNode * pCurrTblNd = IsCrsrInTbl();
                bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd;
            }

            // restore cursor
            SwCrsrShell::Pop( FALSE );

            if( bDelFull )
            {
                DelFullPara();
                UpdateAttr();
                break;
            }
        }

        {
            /* #108049# Save the startnode of the current cell */
            const SwStartNode * pSNdOld;
            pSNdOld = GetSwCrsr()->GetNode()->
                FindTableBoxStartNode();

            if ( SwCrsrShell::IsEndPara() )
            {
                // --> FME 2005-01-28 #i41424# Introduced a couple of
                // Push()-Pop() pairs here. The reason for this is thet a
                // Right()-Left() combination does not make sure, that
                // the cursor will be in its initial state, because there
                // may be a numbering in front of the next paragraph.
                SwCrsrShell::Push();
                // <--

                if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) )
                {
                    if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl()))
                    {
                        /* #108049# Save the startnode of the current
                            cell. May be different to pSNdOld as we have
                            moved. */
                        const SwStartNode * pSNdNew = GetSwCrsr()
                            ->GetNode()->FindTableBoxStartNode();

                        /* #108049# Only move instead of deleting if we
                            have moved to a different cell */
                        if (pSNdOld != pSNdNew)
                        {
                            SwCrsrShell::Pop( TRUE );
                            break;
                        }
                    }
                }

                // restore cursor
                SwCrsrShell::Pop( FALSE );
            }
        }

        OpenMark();
        SwCrsrShell::Right(1,CRSR_SKIP_CELLS);
        nRet = Delete();
        CloseMark( 0 != nRet );
        break;

    case SEL_FRM:
    case SEL_GRF:
    case SEL_OLE:
    case SEL_DRW:
    case SEL_DRW_TXT:
    case SEL_DRW_FORM:
        {
            /*  #108205# Remember object's position. */
            Point aTmpPt = GetObjRect().TopLeft();

            DelSelectedObj();

            /*  #108205# Set cursor to remembered position. */
            SetCrsr(&aTmpPt);

            LeaveSelFrmMode();
            UnSelectFrm();
            // --> OD 2006-07-06 #134369#
            ASSERT( !IsFrmSelected(),
                    "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" )
            // <--
            // --> OD 2006-07-10 #134369#
            // leave draw mode, if necessary.
            {
                if (GetView().GetDrawFuncPtr())
                {
                    GetView().GetDrawFuncPtr()->Deactivate();
                    GetView().SetDrawFuncPtr(NULL);
                }
                if ( GetView().IsDrawMode() )
                {
                    GetView().LeaveDrawCreate();
                }
            }
            // <--
        }

        // --> OD 2006-07-07 #134369#
        // <IsFrmSelected()> can't be true - see above.
        // <--
        {
            nSelection = GetSelectionType();
            if ( SEL_FRM & nSelection ||
                 SEL_GRF & nSelection ||
                 SEL_OLE & nSelection ||
                 SEL_DRW & nSelection )
            {
                EnterSelFrmMode();
                GotoNextFly();
            }
        }
        nRet = 1;
        break;
    }
    return nRet;
}

long SwWrtShell::DelToEndOfPara()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
    Push();
    SetMark();
    if( !MovePara(fnParaCurr,fnParaEnd))
    {
        Pop(FALSE);
        return 0;
    }
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}

long SwWrtShell::DelToStartOfPara()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
    Push();
    SetMark();
    if( !MovePara(fnParaCurr,fnParaStart))
    {
        Pop(FALSE);
        return 0;
    }
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}
/*
 * alle Loeschoperationen sollten mit Find statt mit
 * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten
 * -- das ist wohl nicht gewuenscht.
 */

long SwWrtShell::DelToStartOfSentence()
{
    if(IsStartOfDoc())
        return 0;
    OpenMark();
    long nRet = _BwdSentence() ? Delete() : 0;
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelToEndOfSentence()
{
    if(IsEndOfDoc())
        return 0;
    OpenMark();
    long nRet = _FwdSentence() ? Delete() : 0;
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelNxtWord()
{
    if(IsEndOfDoc())
        return 0;
    ACT_KONTEXT(this);
    ResetCursorStack();
    EnterStdMode();
    SetMark();
    if(IsEndWrd() && !IsSttWrd())
        _NxtWrd();
    if(IsSttWrd() || IsEndPara())
        _NxtWrd();
    else
        _EndWrd();

    long nRet = Delete();
    if( nRet )
        UpdateAttr();
    else
        SwapPam();
    ClearMark();
    return nRet;
}

long SwWrtShell::DelPrvWord()
{
    if(IsStartOfDoc())
        return 0;
    ACT_KONTEXT(this);
    ResetCursorStack();
    EnterStdMode();
    SetMark();
    if( !IsSttWrd() || !_PrvWrd() )
    {
        if( IsEndWrd() )
        {
            if( _PrvWrd() )
            {
                // skip over all-1 spaces
                short n = -1;
                while( ' ' == GetChar( FALSE, n ))
                    --n;

                if( ++n )
                    ExtendSelection( FALSE, -n );
            }
        }
        else if( IsSttPara())
            _PrvWrd();
        else
            _SttWrd();
    }
    long nRet = Delete();
    if( nRet )
        UpdateAttr();
    else
        SwapPam();
    ClearMark();
    return nRet;
}

<commit_msg>INTEGRATION: CWS swnewtable (1.15.14); FILE MERGED 2007/02/15 13:36:48 fme 1.15.14.1: #i4032# New table concept - Don't delete content if backspace forces a cell change<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: delete.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-28 15:56:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _CRSSKIP_HXX
#include <crsskip.hxx>
#endif
#ifndef _SWCRSR_HXX
#include <swcrsr.hxx>
#endif
#include <svx/lrspitem.hxx> // #i23725#
// --> OD 2006-07-10 #134369#
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DRAWBASE_HXX
#include <drawbase.hxx>
#endif
// <--

inline void SwWrtShell::OpenMark()
{
    StartAllAction();
    ResetCursorStack();
    KillPams();
    SetMark();
}

inline void SwWrtShell::CloseMark( BOOL bOkFlag )
{
    if( bOkFlag )
        UpdateAttr();
    else
        SwapPam();

    ClearMark();
    EndAllAction();
}

// #i23725#
BOOL SwWrtShell::TryRemoveIndent()
{
    BOOL bResult = FALSE;

    SfxItemSet aAttrSet(GetAttrPool(), RES_LR_SPACE, RES_LR_SPACE);
    GetAttr(aAttrSet);

    SvxLRSpaceItem aItem = (const SvxLRSpaceItem &)aAttrSet.Get(RES_LR_SPACE);
    short aOldFirstLineOfst = aItem.GetTxtFirstLineOfst();

    if (aOldFirstLineOfst > 0)
    {
        aItem.SetTxtFirstLineOfst(0);
        bResult = TRUE;
    }
    else if (aOldFirstLineOfst < 0)
    {
        aItem.SetTxtFirstLineOfst(0);
        aItem.SetLeft(aItem.GetLeft() + aOldFirstLineOfst);

        bResult = TRUE;
    }
    else if (aItem.GetLeft() != 0)
    {
        aItem.SetLeft(0);
        bResult = TRUE;
    }

    if (bResult)
    {
        aAttrSet.Put(aItem);
        SetAttr(aAttrSet);
    }

    return bResult;
}

/*------------------------------------------------------------------------
 Beschreibung:  Zeile loeschen
------------------------------------------------------------------------*/

long SwWrtShell::DelLine()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
        // alten Cursor merken
    Push();
    ClearMark();
    SwCrsrShell::LeftMargin();
    SetMark();
    SwCrsrShell::RightMargin();
//Warum soll hier noch ein Zeichen in der naechsten Zeile geloescht werden?
//  if(!IsEndOfPara())
//      SwCrsrShell::Right();
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}

long SwWrtShell::DelToStartOfLine()
{
    OpenMark();
    SwCrsrShell::LeftMargin();
    long nRet = Delete();
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelToEndOfLine()
{
    OpenMark();
    SwCrsrShell::RightMargin();
    long nRet = Delete();
    CloseMark( 0 != nRet );
    return 1;
}

long SwWrtShell::DelLeft()
{
    // wenns denn ein Fly ist, wech damit
    int nSelType = GetSelectionType();
    const int nCmp = SEL_FRM | SEL_GRF | SEL_OLE | SEL_DRW;
    if( nCmp & nSelType )
    {
        /*  #108205# Remember object's position. */
        Point aTmpPt = GetObjRect().TopLeft();

        DelSelectedObj();

        /*  #108205# Set cursor to remembered position. */
        SetCrsr(&aTmpPt);

        LeaveSelFrmMode();
        UnSelectFrm();

        nSelType = GetSelectionType();
        if ( nCmp & nSelType )
        {
            EnterSelFrmMode();
            GotoNextFly();
        }

        return 1L;
    }

    // wenn eine Selektion existiert, diese loeschen.
    if ( IsSelection() )
    {
         //OS: wieder einmal Basic: ACT_KONTEXT muss vor
        //EnterStdMode verlassen werden!
        {
            ACT_KONTEXT(this);
            ResetCursorStack();
            Delete();
            UpdateAttr();
        }
        EnterStdMode();
        return 1L;
    }

    // JP 29.06.95: nie eine davor stehende Tabelle loeschen.
    BOOL bSwap = FALSE;
    const SwTableNode * pWasInTblNd = SwCrsrShell::IsCrsrInTbl();

    if( SwCrsrShell::IsSttPara())
    {
        // --> FME 2007-02-15 #i4032# Don't actually call a 'delete' if we
        // changed the table cell, compare DelRight().
        const SwStartNode * pSNdOld = pWasInTblNd ?
                                      GetSwCrsr()->GetNode()->FindTableBoxStartNode() :
                                      0;
        // <--

        /* If the cursor is at the beginning of a paragraph, try to step
           backwards. On failure we are done. */
        if( !SwCrsrShell::Left(1,CRSR_SKIP_CHARS) )
            return 0;

        /* If the cursor entered or left a table (or both) we are done. No step
           back. */
        const SwTableNode* pIsInTblNd = SwCrsrShell::IsCrsrInTbl();
        if( pIsInTblNd != pWasInTblNd )
            return 0;

        const SwStartNode* pSNdNew = pIsInTblNd ?
                                     GetSwCrsr()->GetNode()->FindTableBoxStartNode() :
                                     0;

        // --> FME 2007-02-15 #i4032# Don't actually call a 'delete' if we
        // changed the table cell, compare DelRight().
        if ( pSNdOld != pSNdNew )
            return 0;
        // <--

        OpenMark();
        SwCrsrShell::Right(1,CRSR_SKIP_CHARS);
        SwCrsrShell::SwapPam();
        bSwap = TRUE;
    }
    else
    {
        OpenMark();
        SwCrsrShell::Left(1,CRSR_SKIP_CHARS);
    }
    long nRet = Delete();
    if( !nRet && bSwap )
        SwCrsrShell::SwapPam();
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelRight(BOOL bDelFrm)
{
        // werden verodert, wenn Tabellenselektion vorliegt;
        // wird hier auf SEL_TBL umgesetzt.
    long nRet = 0;
    int nSelection = GetSelectionType();
    if(nSelection & SwWrtShell::SEL_TBL_CELLS)
        nSelection = SwWrtShell::SEL_TBL;
    if(nSelection & SwWrtShell::SEL_TXT)
        nSelection = SwWrtShell::SEL_TXT;

    const SwTableNode * pWasInTblNd = NULL;

    switch( nSelection & ~(SEL_BEZ) )
    {
    case SEL_TXT:
    case SEL_TBL:
    case SEL_NUM:
            //  wenn eine Selektion existiert, diese loeschen.
        if( IsSelection() )
        {
            //OS: wieder einmal Basic: ACT_KONTEXT muss vor
            //EnterStdMode verlassen werden!
            {
                ACT_KONTEXT(this);
                ResetCursorStack();
                Delete();
                UpdateAttr();
            }
            EnterStdMode();
            nRet = 1L;
            break;
        }

        pWasInTblNd = IsCrsrInTbl();

        if( SEL_TXT & nSelection && SwCrsrShell::IsSttPara() &&
            SwCrsrShell::IsEndPara() )
        {
            // save cursor
            SwCrsrShell::Push();

            bool bDelFull = false;
            if ( SwCrsrShell::Right(1,CRSR_SKIP_CHARS) )
            {
                const SwTableNode * pCurrTblNd = IsCrsrInTbl();
                bDelFull = pCurrTblNd && pCurrTblNd != pWasInTblNd;
            }

            // restore cursor
            SwCrsrShell::Pop( FALSE );

            if( bDelFull )
            {
                DelFullPara();
                UpdateAttr();
                break;
            }
        }

        {
            /* #108049# Save the startnode of the current cell */
            const SwStartNode * pSNdOld;
            pSNdOld = GetSwCrsr()->GetNode()->
                FindTableBoxStartNode();

            if ( SwCrsrShell::IsEndPara() )
            {
                // --> FME 2005-01-28 #i41424# Introduced a couple of
                // Push()-Pop() pairs here. The reason for this is that a
                // Right()-Left() combination does not make sure, that
                // the cursor will be in its initial state, because there
                // may be a numbering in front of the next paragraph.
                SwCrsrShell::Push();
                // <--

                if ( SwCrsrShell::Right(1, CRSR_SKIP_CHARS) )
                {
                    if (IsCrsrInTbl() || (pWasInTblNd != IsCrsrInTbl()))
                    {
                        /* #108049# Save the startnode of the current
                            cell. May be different to pSNdOld as we have
                            moved. */
                        const SwStartNode * pSNdNew = GetSwCrsr()
                            ->GetNode()->FindTableBoxStartNode();

                        /* #108049# Only move instead of deleting if we
                            have moved to a different cell */
                        if (pSNdOld != pSNdNew)
                        {
                            SwCrsrShell::Pop( TRUE );
                            break;
                        }
                    }
                }

                // restore cursor
                SwCrsrShell::Pop( FALSE );
            }
        }

        OpenMark();
        SwCrsrShell::Right(1,CRSR_SKIP_CELLS);
        nRet = Delete();
        CloseMark( 0 != nRet );
        break;

    case SEL_FRM:
    case SEL_GRF:
    case SEL_OLE:
    case SEL_DRW:
    case SEL_DRW_TXT:
    case SEL_DRW_FORM:
        {
            /*  #108205# Remember object's position. */
            Point aTmpPt = GetObjRect().TopLeft();

            DelSelectedObj();

            /*  #108205# Set cursor to remembered position. */
            SetCrsr(&aTmpPt);

            LeaveSelFrmMode();
            UnSelectFrm();
            // --> OD 2006-07-06 #134369#
            ASSERT( !IsFrmSelected(),
                    "<SwWrtShell::DelRight(..)> - <SwWrtShell::UnSelectFrm()> should unmark all objects" )
            // <--
            // --> OD 2006-07-10 #134369#
            // leave draw mode, if necessary.
            {
                if (GetView().GetDrawFuncPtr())
                {
                    GetView().GetDrawFuncPtr()->Deactivate();
                    GetView().SetDrawFuncPtr(NULL);
                }
                if ( GetView().IsDrawMode() )
                {
                    GetView().LeaveDrawCreate();
                }
            }
            // <--
        }

        // --> OD 2006-07-07 #134369#
        // <IsFrmSelected()> can't be true - see above.
        // <--
        {
            nSelection = GetSelectionType();
            if ( SEL_FRM & nSelection ||
                 SEL_GRF & nSelection ||
                 SEL_OLE & nSelection ||
                 SEL_DRW & nSelection )
            {
                EnterSelFrmMode();
                GotoNextFly();
            }
        }
        nRet = 1;
        break;
    }
    return nRet;
}

long SwWrtShell::DelToEndOfPara()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
    Push();
    SetMark();
    if( !MovePara(fnParaCurr,fnParaEnd))
    {
        Pop(FALSE);
        return 0;
    }
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}

long SwWrtShell::DelToStartOfPara()
{
    ACT_KONTEXT(this);
    ResetCursorStack();
    Push();
    SetMark();
    if( !MovePara(fnParaCurr,fnParaStart))
    {
        Pop(FALSE);
        return 0;
    }
    long nRet = Delete();
    Pop(FALSE);
    if( nRet )
        UpdateAttr();
    return nRet;
}
/*
 * alle Loeschoperationen sollten mit Find statt mit
 * Nxt-/PrvDelim arbeiten, da letzteren mit Wrap Around arbeiten
 * -- das ist wohl nicht gewuenscht.
 */

long SwWrtShell::DelToStartOfSentence()
{
    if(IsStartOfDoc())
        return 0;
    OpenMark();
    long nRet = _BwdSentence() ? Delete() : 0;
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelToEndOfSentence()
{
    if(IsEndOfDoc())
        return 0;
    OpenMark();
    long nRet = _FwdSentence() ? Delete() : 0;
    CloseMark( 0 != nRet );
    return nRet;
}

long SwWrtShell::DelNxtWord()
{
    if(IsEndOfDoc())
        return 0;
    ACT_KONTEXT(this);
    ResetCursorStack();
    EnterStdMode();
    SetMark();
    if(IsEndWrd() && !IsSttWrd())
        _NxtWrd();
    if(IsSttWrd() || IsEndPara())
        _NxtWrd();
    else
        _EndWrd();

    long nRet = Delete();
    if( nRet )
        UpdateAttr();
    else
        SwapPam();
    ClearMark();
    return nRet;
}

long SwWrtShell::DelPrvWord()
{
    if(IsStartOfDoc())
        return 0;
    ACT_KONTEXT(this);
    ResetCursorStack();
    EnterStdMode();
    SetMark();
    if( !IsSttWrd() || !_PrvWrd() )
    {
        if( IsEndWrd() )
        {
            if( _PrvWrd() )
            {
                // skip over all-1 spaces
                short n = -1;
                while( ' ' == GetChar( FALSE, n ))
                    --n;

                if( ++n )
                    ExtendSelection( FALSE, -n );
            }
        }
        else if( IsSttPara())
            _PrvWrd();
        else
            _SttWrd();
    }
    long nRet = Delete();
    if( nRet )
        UpdateAttr();
    else
        SwapPam();
    ClearMark();
    return nRet;
}

<|endoftext|>