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

#include <gtest/gtest.h>
#include <memory>

#include "SurgSim/Collision/BoxCapsuleDcdContact.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Collision/ShapeCollisionRepresentation.h"
#include "SurgSim/Math/BoxShape.h"
#include "SurgSim/Math/CapsuleShape.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"

using SurgSim::Math::BoxShape;
using SurgSim::Math::CapsuleShape;

namespace SurgSim
{
namespace Collision
{

void doBoxCapsuleTest(std::shared_ptr<BoxShape> box,
					  const SurgSim::Math::Quaterniond& boxQuat,
					  const SurgSim::Math::Vector3d& boxTrans,
					  std::shared_ptr<CapsuleShape> capsule,
					  const SurgSim::Math::Quaterniond& capsuleQuat,
					  const SurgSim::Math::Vector3d& capsuleTrans,
					  const bool expectedInContact)
{
	std::shared_ptr<ShapeCollisionRepresentation> boxRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Box 0");
	boxRep->setShape(box);
	boxRep->setLocalPose(SurgSim::Math::makeRigidTransform(boxQuat, boxTrans));

	std::shared_ptr<ShapeCollisionRepresentation> capsuleRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Capsule 0");
	capsuleRep->setShape(capsule);
	capsuleRep->setLocalPose(SurgSim::Math::makeRigidTransform(capsuleQuat, capsuleTrans));

	// Perform collision detection.
	BoxCapsuleDcdContact calcContact;
	std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(boxRep, capsuleRep);
	calcContact.calculateContact(pair);

	EXPECT_EQ(expectedInContact, pair->hasContacts());

	if (expectedInContact)
	{
		SurgSim::Math::Vector3d capsuleToBox;
		capsuleToBox = boxTrans - capsuleTrans;

		double depthMax = box->getSize().norm();
		depthMax += capsule->getLength() / 2.0 + capsule->getRadius();

		auto contacts = pair->getContacts();
		for (auto contact=contacts.cbegin(); contact!=contacts.cend(); ++contact)
		{
			if (! capsuleToBox.isZero())
			{
				// Check that each normal is pointing into the box
				EXPECT_LT(0.0, (*contact)->normal.dot(capsuleToBox));
			}

			// Check that the depth is sane
			EXPECT_LT(0.0, (*contact)->depth);
			EXPECT_GT(depthMax, (*contact)->depth);
		}
	}
}

TEST(BoxCapsuleContactCalculationTests, UnitTests)
{
	std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(1.0, 1.0, 1.0);
	std::shared_ptr<CapsuleShape> capsule = std::make_shared<CapsuleShape>(4.0, 1.0);
	SurgSim::Math::Quaterniond boxQuat;
	SurgSim::Math::Vector3d boxTrans;
	SurgSim::Math::Quaterniond capsuleQuat;
	SurgSim::Math::Vector3d capsuleTrans;

	{
		SCOPED_TRACE("No intersection, box in front of capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(10.6, 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, capsule beyond corner of box");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d::Zero();
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		bool expectedInContact = false;
		capsuleTrans = SurgSim::Math::Vector3d(1.5, 0.0, 1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = SurgSim::Math::Vector3d(1.5, 0.0, -1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = SurgSim::Math::Vector3d(-1.5, 0.0, 1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = SurgSim::Math::Vector3d(-1.5, 0.0, -1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, box below capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(0.0, -3.6, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with capsule side");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with upside down capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with z-axis capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with x-axis capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with capsule cap");
		boxQuat = SurgSim::Math::makeRotationQuaternion(M_PI_2, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(0.1 , 0.0, 0.1);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d(0.0 , 2.6, 0.0);
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, capsule near box corner, but not intersecting");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(0.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d(1.3 , 0.0, 1.3);
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, capsule intersecting with box corner");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d(0.0 , 0.0, 0.0);
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d(1.2 , 0.0, 1.2);
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box inside capsule");
		boxQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		boxTrans = SurgSim::Math::Vector3d::Zero();
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(0.0, SurgSim::Math::Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = SurgSim::Math::Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, capsule inside box");
		std::shared_ptr<BoxShape> bigBox = std::make_shared<BoxShape>(10.0, 10.0, 10.0);
		boxQuat = SurgSim::Math::makeRotationQuaternion(-M_PI_4, SurgSim::Math::Vector3d(0.0, 1.0, 0.0));
		boxTrans = SurgSim::Math::Vector3d::Zero();
		capsuleQuat = SurgSim::Math::makeRotationQuaternion(M_PI, SurgSim::Math::Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = SurgSim::Math::Vector3d(0.0, 0.0, 0.0);
		bool expectedInContact = true;
		doBoxCapsuleTest(bigBox, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}
}

}; // namespace Collision
}; // namespace SurgSim
<commit_msg>Add Unit Test to Box Capsule Dcd Contact<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <gtest/gtest.h>
#include <memory>

#include "SurgSim/Collision/BoxCapsuleDcdContact.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Collision/ShapeCollisionRepresentation.h"
#include "SurgSim/Math/BoxShape.h"
#include "SurgSim/Math/CapsuleShape.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"

using SurgSim::Math::BoxShape;
using SurgSim::Math::CapsuleShape;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::makeRotationQuaternion;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace Collision
{

void doBoxCapsuleTest(std::shared_ptr<BoxShape> box,
					  const Quaterniond& boxQuat,
					  const Vector3d& boxTrans,
					  std::shared_ptr<CapsuleShape> capsule,
					  const Quaterniond& capsuleQuat,
					  const Vector3d& capsuleTrans,
					  const bool expectedInContact)
{
	std::shared_ptr<ShapeCollisionRepresentation> boxRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Box 0");
	boxRep->setShape(box);
	boxRep->setLocalPose(makeRigidTransform(boxQuat, boxTrans));

	std::shared_ptr<ShapeCollisionRepresentation> capsuleRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Capsule 0");
	capsuleRep->setShape(capsule);
	capsuleRep->setLocalPose(makeRigidTransform(capsuleQuat, capsuleTrans));

	// Perform collision detection.
	BoxCapsuleDcdContact calcContact;
	std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(boxRep, capsuleRep);
	calcContact.calculateContact(pair);

	EXPECT_EQ(expectedInContact, pair->hasContacts());

	if (expectedInContact)
	{
		Vector3d capsuleToBox = boxTrans - capsuleTrans;

		double depthMax = box->getSize().norm();
		depthMax += capsule->getLength() / 2.0 + capsule->getRadius();

		auto contacts = pair->getContacts();
		for (auto contact=contacts.cbegin(); contact!=contacts.cend(); ++contact)
		{
			if (! capsuleToBox.isZero())
			{
				// Check that each normal is pointing into the box
				EXPECT_LT(0.0, (*contact)->normal.dot(capsuleToBox));
			}

			// Check that the depth is sane
			EXPECT_LT(0.0, (*contact)->depth);
			EXPECT_GT(depthMax, (*contact)->depth);

			// Check that the locations are sane
			Vector3d boxPenetrationPoint = (*contact)->penetrationPoints.first.globalPosition.getValue();
			Vector3d capsulePenetrationPoint = (*contact)->penetrationPoints.second.globalPosition.getValue();
			EXPECT_GT(0.0, (*contact)->normal.dot(boxPenetrationPoint - boxTrans));
			EXPECT_LT(0.0, (*contact)->normal.dot(capsulePenetrationPoint - capsuleTrans));
		}
	}
}

TEST(BoxCapsuleContactCalculationTests, UnitTests)
{
	std::shared_ptr<BoxShape> box = std::make_shared<BoxShape>(1.0, 1.0, 1.0);
	std::shared_ptr<CapsuleShape> capsule = std::make_shared<CapsuleShape>(4.0, 1.0);
	Quaterniond boxQuat;
	Vector3d boxTrans;
	Quaterniond capsuleQuat;
	Vector3d capsuleTrans;

	{
		SCOPED_TRACE("No intersection, box in front of capsule");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(10.6, 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, capsule beyond corner of box");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d::Zero();
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		bool expectedInContact = false;
		capsuleTrans = Vector3d(1.5, 0.0, 1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = Vector3d(1.5, 0.0, -1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = Vector3d(-1.5, 0.0, 1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
		capsuleTrans = Vector3d(-1.5, 0.0, -1.5);
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, box below capsule");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(0.0, -3.6, 0.0);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with capsule side");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with upside down capsule");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(M_PI, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with z-axis capsule");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(M_PI_2, Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with x-axis capsule");
		boxQuat = makeRotationQuaternion(M_PI, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(1.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(M_PI_2, Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box intersection with capsule cap");
		boxQuat = makeRotationQuaternion(M_PI_2, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(0.1 , 0.0, 0.1);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d(0.0 , 2.6, 0.0);
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("No intersection, capsule near box corner, but not intersecting");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(0.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d(1.3 , 0.0, 1.3);
		bool expectedInContact = false;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, capsule intersecting with box corner");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d(0.0 , 0.0, 0.0);
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d(1.2 , 0.0, 1.2);
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, box inside capsule");
		boxQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		boxTrans = Vector3d::Zero();
		capsuleQuat = makeRotationQuaternion(0.0, Vector3d(0.0, 0.0, 1.0));
		capsuleTrans = Vector3d::Zero();
		bool expectedInContact = true;
		doBoxCapsuleTest(box, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}

	{
		SCOPED_TRACE("Intersection, capsule inside box");
		std::shared_ptr<BoxShape> bigBox = std::make_shared<BoxShape>(10.0, 10.0, 10.0);
		boxQuat = makeRotationQuaternion(-M_PI_4, Vector3d(0.0, 1.0, 0.0));
		boxTrans = Vector3d::Zero();
		capsuleQuat = makeRotationQuaternion(M_PI, Vector3d(1.0, 0.0, 0.0));
		capsuleTrans = Vector3d(0.0, 0.0, 0.0);
		bool expectedInContact = true;
		doBoxCapsuleTest(bigBox, boxQuat, boxTrans, capsule, capsuleQuat, capsuleTrans, expectedInContact);
	}
}

}; // namespace Collision
}; // namespace SurgSim
<|endoftext|>


<commit_before>#include <csignal>
#include <fcntl.h>
#include <sys/stat.h>
#include "driver.h"
#include "../main/version.h"
#include "files.h"
#include "chpl.h"
#include "baseAST.h"
#include "symbol.h"
#include "expr.h"
#include "stmt.h"
#include "stringutil.h"
#include "misc.h"
#include "yy.h"

static void cleanup_for_exit(void) {
  deleteTmpDir();
  stopCatchingSignals();
}

// must be non-static to avoid dead-code elim. when compiling -O3
void gdbShouldBreakHere(void) {
}

// Support for internal errors, adopted from ZPL compiler

static bool exit_immediately = true;
static bool exit_eventually = false;

static const char* err_filename;
static int err_lineno;
static int err_fatal;
static int err_user;
static int err_print;
static int err_ignore;
static FnSymbol* err_fn = NULL;

const char* cleanFilename(const char* name) {
  static int chplHomeLen = strlen(CHPL_HOME);

  if (!strncmp(name, CHPL_HOME, chplHomeLen)) {
    return astr("$CHPL_HOME", name + chplHomeLen);
  } else {
    return name;
  }
}

static const char* cleanFilename(BaseAST* ast) {
  ModuleSymbol* mod = ast->getModule();
  if (mod) {
    return cleanFilename(ast->getModule()->filename);
  } else {
    return cleanFilename(yyfilename);
  }
}

static void
print_user_internal_error() {
  static char error[8];

  const char* filename_start = strrchr(err_filename, '/');
  if (filename_start)
    filename_start++;
  else
    filename_start = err_filename;
  strncpy(error, filename_start, 3);
  sprintf(error+3, "%04d", err_lineno);
  for (int i = 0; i < 7; i++) {
    if (error[i] >= 'a' && error[i] <= 'z') {
      error[i] += 'A' - 'a';
    }
  }

  fprintf(stderr, "internal failure %s ", error);
  char version[128];
  get_version(version);
  fprintf(stderr, "chpl Version %s\n", version);
  if (err_fatal)
    clean_exit(1);
}

void
setupError(const char *filename, int lineno, int tag) {
  err_filename = filename;
  err_lineno = lineno;
  err_fatal = tag == 1 || tag == 2 || tag == 3;
  err_user = tag != 1;
  err_print = tag == 5;
  err_ignore = ignore_warnings && tag == 4;
  exit_immediately = tag == 1 || tag == 2;
  exit_eventually |= tag == 3;
}

static void
printDevelErrorHeader(BaseAST* ast) {
  if (!err_print) {
    if (Expr* expr = toExpr(ast)) {
      Symbol* parent = expr->parentSymbol;
      if (isArgSymbol(parent))
        parent = parent->defPoint->parentSymbol;
      FnSymbol* fn = toFnSymbol(parent);
      if (fn && fn != err_fn) {
        err_fn = fn;
        while ((fn = toFnSymbol(err_fn->defPoint->parentSymbol))) {
          if (fn == fn->getModule()->initFn)
            break;
          err_fn = fn;
        }
        if (err_fn->getModule()->initFn != err_fn &&
            !err_fn->hasFlag(FLAG_TEMP) &&
            !err_fn->hasFlag(FLAG_INLINE) &&
            err_fn->lineno) {
          fprintf(stderr, "%s:%d: In ",
                  cleanFilename(err_fn), err_fn->lineno);
          if (!strncmp(err_fn->name, "_construct_", 11)) {
            fprintf(stderr, "constructor '%s':\n", err_fn->name+11);
          } else {
            fprintf(stderr, "%s '%s':\n",
                    (err_fn->hasFlag(FLAG_ITERATOR_FN) ? "iterator" : "function"),
                    err_fn->name);
          }
        }
      }
    }
  }

  if (ast && ast->lineno)
    fprintf(stderr, "%s:%d: ", cleanFilename(ast), ast->lineno);

  fprintf(stderr, err_print ? "note: " : err_fatal ? "error: " : "warning: ");

  if (!err_user && !developer) {
    print_user_internal_error();
  }

}

static void printDevelErrorFooter(void) {
  if (developer)
    fprintf(stderr, " [%s:%d]", err_filename, err_lineno);
}

void handleError(const char *fmt, ...) {
  fflush(stdout);
  fflush(stderr);
  if (err_ignore)
    return;

  printDevelErrorHeader(NULL);

  if (!err_user && !developer)
    return;

  va_list args;

  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);

  printDevelErrorFooter();

  fprintf(stderr, "\n");

  if (exit_immediately && !ignore_errors) {
    clean_exit(1);
  }
}

void handleError(BaseAST* ast, const char *fmt, ...) {
  if (err_ignore)
    return;

  printDevelErrorHeader(ast);

  if (!err_user && !developer)
    return;

  va_list args;

  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);

  printDevelErrorFooter();

  fprintf(stderr, "\n");

  if (exit_immediately && !ignore_errors) {
    clean_exit(1);
  }
}

void exitIfFatalErrorsEncountered() {
  if (exit_eventually && !ignore_errors) {
    clean_exit(1);
  }
}

static void handleInterrupt(int sig) {
  INT_FATAL("received interrupt");
}

static void handleSegFault(int sig) {
  INT_FATAL("seg fault");
}

void startCatchingSignals(void) {
  signal(SIGINT, handleInterrupt);
  signal(SIGSEGV, handleSegFault);
}

void stopCatchingSignals(void) {
  signal(SIGINT, SIG_DFL);
  signal(SIGSEGV, SIG_DFL);
}

//
// Put this last to minimize the amount of code affected by this #undef
//
#ifdef exit
#undef exit
#endif
void clean_exit(int status) {
  if (status != 0) {
    gdbShouldBreakHere();
  }
  cleanup_for_exit();
  deleteStrings();
  exit(status);
}
<commit_msg>Installed handlers for SIGTERM and SIGHUP that will clean up the /tmp directories and exit cleanly.<commit_after>#include <csignal>
#include <fcntl.h>
#include <sys/stat.h>
#include "driver.h"
#include "../main/version.h"
#include "files.h"
#include "chpl.h"
#include "baseAST.h"
#include "symbol.h"
#include "expr.h"
#include "stmt.h"
#include "stringutil.h"
#include "misc.h"
#include "yy.h"

static void cleanup_for_exit(void) {
  deleteTmpDir();
  stopCatchingSignals();
}

// must be non-static to avoid dead-code elim. when compiling -O3
void gdbShouldBreakHere(void) {
}

// Support for internal errors, adopted from ZPL compiler

static bool exit_immediately = true;
static bool exit_eventually = false;

static const char* err_filename;
static int err_lineno;
static int err_fatal;
static int err_user;
static int err_print;
static int err_ignore;
static FnSymbol* err_fn = NULL;

const char* cleanFilename(const char* name) {
  static int chplHomeLen = strlen(CHPL_HOME);

  if (!strncmp(name, CHPL_HOME, chplHomeLen)) {
    return astr("$CHPL_HOME", name + chplHomeLen);
  } else {
    return name;
  }
}

static const char* cleanFilename(BaseAST* ast) {
  ModuleSymbol* mod = ast->getModule();
  if (mod) {
    return cleanFilename(ast->getModule()->filename);
  } else {
    return cleanFilename(yyfilename);
  }
}

static void
print_user_internal_error() {
  static char error[8];

  const char* filename_start = strrchr(err_filename, '/');
  if (filename_start)
    filename_start++;
  else
    filename_start = err_filename;
  strncpy(error, filename_start, 3);
  sprintf(error+3, "%04d", err_lineno);
  for (int i = 0; i < 7; i++) {
    if (error[i] >= 'a' && error[i] <= 'z') {
      error[i] += 'A' - 'a';
    }
  }

  fprintf(stderr, "internal failure %s ", error);
  char version[128];
  get_version(version);
  fprintf(stderr, "chpl Version %s\n", version);
  if (err_fatal)
    clean_exit(1);
}

void
setupError(const char *filename, int lineno, int tag) {
  err_filename = filename;
  err_lineno = lineno;
  err_fatal = tag == 1 || tag == 2 || tag == 3;
  err_user = tag != 1;
  err_print = tag == 5;
  err_ignore = ignore_warnings && tag == 4;
  exit_immediately = tag == 1 || tag == 2;
  exit_eventually |= tag == 3;
}

static void
printDevelErrorHeader(BaseAST* ast) {
  if (!err_print) {
    if (Expr* expr = toExpr(ast)) {
      Symbol* parent = expr->parentSymbol;
      if (isArgSymbol(parent))
        parent = parent->defPoint->parentSymbol;
      FnSymbol* fn = toFnSymbol(parent);
      if (fn && fn != err_fn) {
        err_fn = fn;
        while ((fn = toFnSymbol(err_fn->defPoint->parentSymbol))) {
          if (fn == fn->getModule()->initFn)
            break;
          err_fn = fn;
        }
        if (err_fn->getModule()->initFn != err_fn &&
            !err_fn->hasFlag(FLAG_TEMP) &&
            !err_fn->hasFlag(FLAG_INLINE) &&
            err_fn->lineno) {
          fprintf(stderr, "%s:%d: In ",
                  cleanFilename(err_fn), err_fn->lineno);
          if (!strncmp(err_fn->name, "_construct_", 11)) {
            fprintf(stderr, "constructor '%s':\n", err_fn->name+11);
          } else {
            fprintf(stderr, "%s '%s':\n",
                    (err_fn->hasFlag(FLAG_ITERATOR_FN) ? "iterator" : "function"),
                    err_fn->name);
          }
        }
      }
    }
  }

  if (ast && ast->lineno)
    fprintf(stderr, "%s:%d: ", cleanFilename(ast), ast->lineno);

  fprintf(stderr, err_print ? "note: " : err_fatal ? "error: " : "warning: ");

  if (!err_user && !developer) {
    print_user_internal_error();
  }

}

static void printDevelErrorFooter(void) {
  if (developer)
    fprintf(stderr, " [%s:%d]", err_filename, err_lineno);
}

void handleError(const char *fmt, ...) {
  fflush(stdout);
  fflush(stderr);
  if (err_ignore)
    return;

  printDevelErrorHeader(NULL);

  if (!err_user && !developer)
    return;

  va_list args;

  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);

  printDevelErrorFooter();

  fprintf(stderr, "\n");

  if (exit_immediately && !ignore_errors) {
    clean_exit(1);
  }
}

void handleError(BaseAST* ast, const char *fmt, ...) {
  if (err_ignore)
    return;

  printDevelErrorHeader(ast);

  if (!err_user && !developer)
    return;

  va_list args;

  va_start(args, fmt);
  vfprintf(stderr, fmt, args);
  va_end(args);

  printDevelErrorFooter();

  fprintf(stderr, "\n");

  if (exit_immediately && !ignore_errors) {
    clean_exit(1);
  }
}

void exitIfFatalErrorsEncountered() {
  if (exit_eventually && !ignore_errors) {
    clean_exit(1);
  }
}

static void handleInterrupt(int sig) {
  INT_FATAL("received interrupt");
}

static void handleSegFault(int sig) {
  INT_FATAL("seg fault");
}

void startCatchingSignals(void) {
  signal(SIGINT, handleInterrupt);
  signal(SIGTERM, handleInterrupt);
  signal(SIGHUP, handleInterrupt);
  signal(SIGSEGV, handleSegFault);
}

void stopCatchingSignals(void) {
  signal(SIGINT, SIG_DFL);
  signal(SIGSEGV, SIG_DFL);
}

//
// Put this last to minimize the amount of code affected by this #undef
//
#ifdef exit
#undef exit
#endif
void clean_exit(int status) {
  if (status != 0) {
    gdbShouldBreakHere();
  }
  cleanup_for_exit();
  deleteStrings();
  exit(status);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <string.h>

#include <memory>

#include "webrtc/media/base/videoframe_unittest.h"
#include "webrtc/media/engine/webrtcvideoframe.h"
#include "webrtc/media/engine/webrtcvideoframefactory.h"

class WebRtcVideoFrameFactoryTest
    : public VideoFrameTest<cricket::WebRtcVideoFrameFactory> {
 public:
  WebRtcVideoFrameFactoryTest() {}

  void InitFrame(webrtc::VideoRotation frame_rotation) {
    const int frame_width = 1920;
    const int frame_height = 1080;

    // Build the CapturedFrame.
    captured_frame_.fourcc = cricket::FOURCC_I420;
    captured_frame_.pixel_width = 1;
    captured_frame_.pixel_height = 1;
    captured_frame_.time_stamp = rtc::TimeNanos();
    captured_frame_.rotation = frame_rotation;
    captured_frame_.width = frame_width;
    captured_frame_.height = frame_height;
    captured_frame_.data_size =
        (frame_width * frame_height) +
        ((frame_width + 1) / 2) * ((frame_height + 1) / 2) * 2;
    captured_frame_buffer_.reset(new uint8_t[captured_frame_.data_size]);
    // Initialize memory to satisfy DrMemory tests.
    memset(captured_frame_buffer_.get(), 0, captured_frame_.data_size);
    captured_frame_.data = captured_frame_buffer_.get();
  }

  void VerifyFrame(cricket::VideoFrame* dest_frame,
                   webrtc::VideoRotation src_rotation,
                   int src_width,
                   int src_height,
                   bool apply_rotation) {
    if (!apply_rotation) {
      EXPECT_EQ(dest_frame->rotation(), src_rotation);
      EXPECT_EQ(dest_frame->width(), src_width);
      EXPECT_EQ(dest_frame->height(), src_height);
    } else {
      EXPECT_EQ(dest_frame->rotation(), webrtc::kVideoRotation_0);
      if (src_rotation == webrtc::kVideoRotation_90 ||
          src_rotation == webrtc::kVideoRotation_270) {
        EXPECT_EQ(dest_frame->width(), src_height);
        EXPECT_EQ(dest_frame->height(), src_width);
      } else {
        EXPECT_EQ(dest_frame->width(), src_width);
        EXPECT_EQ(dest_frame->height(), src_height);
      }
    }
  }

  void TestCreateAliasedFrame(bool apply_rotation) {
    cricket::VideoFrameFactory& factory = factory_;
    factory.SetApplyRotation(apply_rotation);
    InitFrame(webrtc::kVideoRotation_270);
    const cricket::CapturedFrame& captured_frame = get_captured_frame();
    // Create the new frame from the CapturedFrame.
    std::unique_ptr<cricket::VideoFrame> frame;
    int new_width = captured_frame.width / 2;
    int new_height = captured_frame.height / 2;
    frame.reset(factory.CreateAliasedFrame(&captured_frame, new_width,
                                           new_height, new_width, new_height));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width, new_height,
                apply_rotation);

    frame.reset(factory.CreateAliasedFrame(
        &captured_frame, new_width, new_height, new_width / 2, new_height / 2));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2,
                new_height / 2, apply_rotation);

    // Reset the frame first so it's exclusive hence we could go through the
    // StretchToFrame code path in CreateAliasedFrame.
    frame.reset();
    frame.reset(factory.CreateAliasedFrame(
        &captured_frame, new_width, new_height, new_width / 2, new_height / 2));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2,
                new_height / 2, apply_rotation);
  }

  const cricket::CapturedFrame& get_captured_frame() { return captured_frame_; }

 private:
  cricket::CapturedFrame captured_frame_;
  std::unique_ptr<uint8_t[]> captured_frame_buffer_;
  cricket::WebRtcVideoFrameFactory factory_;
};

TEST_F(WebRtcVideoFrameFactoryTest, NoApplyRotation) {
  TestCreateAliasedFrame(false);
}

TEST_F(WebRtcVideoFrameFactoryTest, ApplyRotation) {
  TestCreateAliasedFrame(true);
}
<commit_msg>WebRtcVideoFrameFactoryTest shouldn't inherit VideoFrameTest.<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <string.h>

#include <memory>

#include "webrtc/base/gunit.h"
#include "webrtc/media/base/videocapturer.h"
#include "webrtc/media/engine/webrtcvideoframe.h"
#include "webrtc/media/engine/webrtcvideoframefactory.h"

class WebRtcVideoFrameFactoryTest : public testing::Test {
 public:
  WebRtcVideoFrameFactoryTest() {}

  void InitFrame(webrtc::VideoRotation frame_rotation) {
    const int frame_width = 1920;
    const int frame_height = 1080;

    // Build the CapturedFrame.
    captured_frame_.fourcc = cricket::FOURCC_I420;
    captured_frame_.pixel_width = 1;
    captured_frame_.pixel_height = 1;
    captured_frame_.time_stamp = rtc::TimeNanos();
    captured_frame_.rotation = frame_rotation;
    captured_frame_.width = frame_width;
    captured_frame_.height = frame_height;
    captured_frame_.data_size =
        (frame_width * frame_height) +
        ((frame_width + 1) / 2) * ((frame_height + 1) / 2) * 2;
    captured_frame_buffer_.reset(new uint8_t[captured_frame_.data_size]);
    // Initialize memory to satisfy DrMemory tests.
    memset(captured_frame_buffer_.get(), 0, captured_frame_.data_size);
    captured_frame_.data = captured_frame_buffer_.get();
  }

  void VerifyFrame(cricket::VideoFrame* dest_frame,
                   webrtc::VideoRotation src_rotation,
                   int src_width,
                   int src_height,
                   bool apply_rotation) {
    if (!apply_rotation) {
      EXPECT_EQ(dest_frame->rotation(), src_rotation);
      EXPECT_EQ(dest_frame->width(), src_width);
      EXPECT_EQ(dest_frame->height(), src_height);
    } else {
      EXPECT_EQ(dest_frame->rotation(), webrtc::kVideoRotation_0);
      if (src_rotation == webrtc::kVideoRotation_90 ||
          src_rotation == webrtc::kVideoRotation_270) {
        EXPECT_EQ(dest_frame->width(), src_height);
        EXPECT_EQ(dest_frame->height(), src_width);
      } else {
        EXPECT_EQ(dest_frame->width(), src_width);
        EXPECT_EQ(dest_frame->height(), src_height);
      }
    }
  }

  void TestCreateAliasedFrame(bool apply_rotation) {
    cricket::VideoFrameFactory& factory = factory_;
    factory.SetApplyRotation(apply_rotation);
    InitFrame(webrtc::kVideoRotation_270);
    const cricket::CapturedFrame& captured_frame = get_captured_frame();
    // Create the new frame from the CapturedFrame.
    std::unique_ptr<cricket::VideoFrame> frame;
    int new_width = captured_frame.width / 2;
    int new_height = captured_frame.height / 2;
    frame.reset(factory.CreateAliasedFrame(&captured_frame, new_width,
                                           new_height, new_width, new_height));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width, new_height,
                apply_rotation);

    frame.reset(factory.CreateAliasedFrame(
        &captured_frame, new_width, new_height, new_width / 2, new_height / 2));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2,
                new_height / 2, apply_rotation);

    // Reset the frame first so it's exclusive hence we could go through the
    // StretchToFrame code path in CreateAliasedFrame.
    frame.reset();
    frame.reset(factory.CreateAliasedFrame(
        &captured_frame, new_width, new_height, new_width / 2, new_height / 2));
    VerifyFrame(frame.get(), webrtc::kVideoRotation_270, new_width / 2,
                new_height / 2, apply_rotation);
  }

  const cricket::CapturedFrame& get_captured_frame() { return captured_frame_; }

 private:
  cricket::CapturedFrame captured_frame_;
  std::unique_ptr<uint8_t[]> captured_frame_buffer_;
  cricket::WebRtcVideoFrameFactory factory_;
};

TEST_F(WebRtcVideoFrameFactoryTest, NoApplyRotation) {
  TestCreateAliasedFrame(false);
}

TEST_F(WebRtcVideoFrameFactoryTest, ApplyRotation) {
  TestCreateAliasedFrame(true);
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <sal/config.h>
#include <rtl/uuid.h>
#include "xmlencryption_nssimpl.hxx"

#include "xmldocumentwrapper_xmlsecimpl.hxx"

#include "xmlelementwrapper_xmlsecimpl.hxx"

#include "securityenvironment_nssimpl.hxx"
#include "errorcallback.hxx"

#include <sal/types.h>
//For reasons that escape me, this is what xmlsec does when size_t is not 4
#if SAL_TYPES_SIZEOFPOINTER != 4
#    define XMLSEC_NO_SIZE_T
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/xmltree.h"
#include "xmlsec/xmlenc.h"
#include "xmlsec/crypto.h"

#ifdef UNX
#define stricmp strcasecmp
#endif

using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;

using ::com::sun::star::xml::wrapper::XXMLElementWrapper ;
using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLEncryption ;
using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
using ::com::sun::star::xml::crypto::XMLEncryptionException ;

XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) {
}

XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() {
}

/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: encrypt(
    const Reference< XXMLEncryptionTemplate >& aTemplate ,
    const Reference< XSecurityEnvironment >& aEnvironment
) throw( com::sun::star::xml::crypto::XMLEncryptionException,
         com::sun::star::uno::SecurityException )
{
    xmlSecKeysMngrPtr pMngr = NULL ;
    xmlSecEncCtxPtr pEncCtx = NULL ;
    xmlNodePtr pEncryptedData = NULL ;
    xmlNodePtr pContent = NULL ;

    if( !aTemplate.is() )
        throw RuntimeException() ;

    if( !aEnvironment.is() )
        throw RuntimeException() ;

    //Get Keys Manager
    Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
    if( !xSecTunnel.is() ) {
         throw RuntimeException() ;
    }

    SecurityEnvironment_NssImpl* pSecEnv =
        reinterpret_cast<SecurityEnvironment_NssImpl*>(
            sal::static_int_cast<sal_uIntPtr>(xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ;
    if( pSecEnv == NULL )
        throw RuntimeException() ;

    //Get the encryption template
    Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
    if( !xTemplate.is() ) {
        throw RuntimeException() ;
    }

    Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
    if( !xTplTunnel.is() ) {
        throw RuntimeException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTemplate =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTemplate == NULL ) {
        throw RuntimeException() ;
    }

    // Get the element to be encrypted
    Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ;
    if( !xTarget.is() ) {
        throw XMLEncryptionException() ;
    }

    Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ;
    if( !xTgtTunnel.is() ) {
        throw XMLEncryptionException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTarget =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTarget == NULL ) {
        throw RuntimeException() ;
    }

    pContent = pTarget->getNativeElement() ;

    if( pContent == NULL ) {
        throw XMLEncryptionException() ;
    }

    //remember the position of the element to be signed
    sal_Bool isParentRef = sal_True;
    pEncryptedData = pTemplate->getNativeElement();

    xmlNodePtr pParent = pEncryptedData->parent;
    xmlNodePtr referenceNode;

    if (pEncryptedData == pParent->children)
    {
        referenceNode = pParent;
    }
    else
    {
        referenceNode = pEncryptedData->prev;
        isParentRef = sal_False;
    }

     setErrorRecorder( );

    pMngr = pSecEnv->createKeysManager() ; //i39448
    if( !pMngr ) {
        throw RuntimeException() ;
    }

    //Create Encryption context
    pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
    if( pEncCtx == NULL )
    {
        pSecEnv->destroyKeysManager( pMngr ) ; //i39448
        //throw XMLEncryptionException() ;
        clearErrorRecorder();
        return aTemplate;
    }

    //Find the element to be encrypted.

    //Encrypt the template
    if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 )
    {
        xmlSecEncCtxDestroy( pEncCtx ) ;
        pSecEnv->destroyKeysManager( pMngr ) ; //i39448

        //throw XMLEncryptionException() ;
        clearErrorRecorder();
        return aTemplate;
    }

    xmlSecEncCtxDestroy( pEncCtx ) ;
    pSecEnv->destroyKeysManager( pMngr ) ; //i39448

    //get the new EncryptedData element
    if (isParentRef)
    {
        pTemplate->setNativeElement(referenceNode->children) ;
    }
    else
    {
        pTemplate->setNativeElement(referenceNode->next);
    }

    return aTemplate ;
}

/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: decrypt(
    const Reference< XXMLEncryptionTemplate >& aTemplate ,
    const Reference< XXMLSecurityContext >& aSecurityCtx
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
         com::sun::star::uno::SecurityException) {
    xmlSecKeysMngrPtr pMngr = NULL ;
    xmlSecEncCtxPtr pEncCtx = NULL ;
    xmlNodePtr pEncryptedData = NULL ;

    if( !aTemplate.is() )
        throw RuntimeException() ;

    if( !aSecurityCtx.is() )
        throw RuntimeException() ;

    //Get the encryption template
    Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
    if( !xTemplate.is() ) {
        throw RuntimeException() ;
    }

    Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
    if( !xTplTunnel.is() ) {
        throw RuntimeException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTemplate =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTemplate == NULL ) {
        throw RuntimeException() ;
    }

    pEncryptedData = pTemplate->getNativeElement() ;

    //remember the position of the element to be signed
    sal_Bool isParentRef = sal_True;
    xmlNodePtr pParent = pEncryptedData->parent;
    xmlNodePtr referenceNode;

    if (pEncryptedData == pParent->children)
    {
        referenceNode = pParent;
    }
    else
    {
        referenceNode = pEncryptedData->prev;
        isParentRef = sal_False;
    }

     setErrorRecorder( );

    sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber();
    sal_Int32 i;

    for (i=0; i<nSecurityEnvironment; ++i)
    {
        Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i);

        //Get Keys Manager
        Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
        if( !aEnvironment.is() ) {
             throw RuntimeException() ;
        }

        SecurityEnvironment_NssImpl* pSecEnv =
            reinterpret_cast<SecurityEnvironment_NssImpl*>(
                sal::static_int_cast<sal_uIntPtr>(
                    xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() )));
        if( pSecEnv == NULL )
            throw RuntimeException() ;

        pMngr = pSecEnv->createKeysManager() ; //i39448
        if( !pMngr ) {
            throw RuntimeException() ;
        }

        //Create Encryption context
        pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
        if( pEncCtx == NULL )
        {
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448
            //throw XMLEncryptionException() ;
            clearErrorRecorder();
            return aTemplate;
        }

        //Decrypt the template
        if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL ))
        {
            //The decryption succeeds

            //Destroy the encryption context
            xmlSecEncCtxDestroy( pEncCtx ) ;
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448

            //get the decrypted element
            XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef?
                (referenceNode->children):(referenceNode->next));

            //return ret;
            aTemplate->setTemplate(ret);
            break;
        }
        else
        {
            //The decryption fails, continue with the next security environment
            xmlSecEncCtxDestroy( pEncCtx ) ;
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448
        }
    }

    clearErrorRecorder();
    return aTemplate;
}

/* XInitialization */
void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& /*aArguments*/ ) throw( Exception, RuntimeException ) {
    // TBD
} ;

/* XServiceInfo */
OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) {
    return impl_getImplementationName() ;
}

/* XServiceInfo */
sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
    Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
    const OUString* pArray = seqServiceNames.getConstArray() ;
    for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
        if( *( pArray + i ) == serviceName )
            return sal_True ;
    }
    return sal_False ;
}

/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) {
    return impl_getSupportedServiceNames() ;
}

//Helper for XServiceInfo
Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() {
    ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
    Sequence< OUString > seqServiceNames( 1 ) ;
    seqServiceNames.getArray()[0] = OUString("com.sun.star.xml.crypto.XMLEncryption") ;
    return seqServiceNames ;
}

OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) {
    return OUString("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl") ;
}

//Helper for registry
Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
    return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ;
}

Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
    //Reference< XSingleServiceFactory > xFactory ;
    //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
    //return xFactory ;
    return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>stricmp macro is unused<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <sal/config.h>
#include <rtl/uuid.h>
#include "xmlencryption_nssimpl.hxx"

#include "xmldocumentwrapper_xmlsecimpl.hxx"

#include "xmlelementwrapper_xmlsecimpl.hxx"

#include "securityenvironment_nssimpl.hxx"
#include "errorcallback.hxx"

#include <sal/types.h>
//For reasons that escape me, this is what xmlsec does when size_t is not 4
#if SAL_TYPES_SIZEOFPOINTER != 4
#    define XMLSEC_NO_SIZE_T
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/xmltree.h"
#include "xmlsec/xmlenc.h"
#include "xmlsec/crypto.h"

using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;

using ::com::sun::star::xml::wrapper::XXMLElementWrapper ;
using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLEncryption ;
using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
using ::com::sun::star::xml::crypto::XMLEncryptionException ;

XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) {
}

XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() {
}

/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: encrypt(
    const Reference< XXMLEncryptionTemplate >& aTemplate ,
    const Reference< XSecurityEnvironment >& aEnvironment
) throw( com::sun::star::xml::crypto::XMLEncryptionException,
         com::sun::star::uno::SecurityException )
{
    xmlSecKeysMngrPtr pMngr = NULL ;
    xmlSecEncCtxPtr pEncCtx = NULL ;
    xmlNodePtr pEncryptedData = NULL ;
    xmlNodePtr pContent = NULL ;

    if( !aTemplate.is() )
        throw RuntimeException() ;

    if( !aEnvironment.is() )
        throw RuntimeException() ;

    //Get Keys Manager
    Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
    if( !xSecTunnel.is() ) {
         throw RuntimeException() ;
    }

    SecurityEnvironment_NssImpl* pSecEnv =
        reinterpret_cast<SecurityEnvironment_NssImpl*>(
            sal::static_int_cast<sal_uIntPtr>(xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ))) ;
    if( pSecEnv == NULL )
        throw RuntimeException() ;

    //Get the encryption template
    Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
    if( !xTemplate.is() ) {
        throw RuntimeException() ;
    }

    Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
    if( !xTplTunnel.is() ) {
        throw RuntimeException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTemplate =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTemplate == NULL ) {
        throw RuntimeException() ;
    }

    // Get the element to be encrypted
    Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ;
    if( !xTarget.is() ) {
        throw XMLEncryptionException() ;
    }

    Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ;
    if( !xTgtTunnel.is() ) {
        throw XMLEncryptionException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTarget =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTarget == NULL ) {
        throw RuntimeException() ;
    }

    pContent = pTarget->getNativeElement() ;

    if( pContent == NULL ) {
        throw XMLEncryptionException() ;
    }

    //remember the position of the element to be signed
    sal_Bool isParentRef = sal_True;
    pEncryptedData = pTemplate->getNativeElement();

    xmlNodePtr pParent = pEncryptedData->parent;
    xmlNodePtr referenceNode;

    if (pEncryptedData == pParent->children)
    {
        referenceNode = pParent;
    }
    else
    {
        referenceNode = pEncryptedData->prev;
        isParentRef = sal_False;
    }

     setErrorRecorder( );

    pMngr = pSecEnv->createKeysManager() ; //i39448
    if( !pMngr ) {
        throw RuntimeException() ;
    }

    //Create Encryption context
    pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
    if( pEncCtx == NULL )
    {
        pSecEnv->destroyKeysManager( pMngr ) ; //i39448
        //throw XMLEncryptionException() ;
        clearErrorRecorder();
        return aTemplate;
    }

    //Find the element to be encrypted.

    //Encrypt the template
    if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 )
    {
        xmlSecEncCtxDestroy( pEncCtx ) ;
        pSecEnv->destroyKeysManager( pMngr ) ; //i39448

        //throw XMLEncryptionException() ;
        clearErrorRecorder();
        return aTemplate;
    }

    xmlSecEncCtxDestroy( pEncCtx ) ;
    pSecEnv->destroyKeysManager( pMngr ) ; //i39448

    //get the new EncryptedData element
    if (isParentRef)
    {
        pTemplate->setNativeElement(referenceNode->children) ;
    }
    else
    {
        pTemplate->setNativeElement(referenceNode->next);
    }

    return aTemplate ;
}

/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: decrypt(
    const Reference< XXMLEncryptionTemplate >& aTemplate ,
    const Reference< XXMLSecurityContext >& aSecurityCtx
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
         com::sun::star::uno::SecurityException) {
    xmlSecKeysMngrPtr pMngr = NULL ;
    xmlSecEncCtxPtr pEncCtx = NULL ;
    xmlNodePtr pEncryptedData = NULL ;

    if( !aTemplate.is() )
        throw RuntimeException() ;

    if( !aSecurityCtx.is() )
        throw RuntimeException() ;

    //Get the encryption template
    Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
    if( !xTemplate.is() ) {
        throw RuntimeException() ;
    }

    Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
    if( !xTplTunnel.is() ) {
        throw RuntimeException() ;
    }

    XMLElementWrapper_XmlSecImpl* pTemplate =
        reinterpret_cast<XMLElementWrapper_XmlSecImpl*>(
            sal::static_int_cast<sal_uIntPtr>(
                xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() )));
    if( pTemplate == NULL ) {
        throw RuntimeException() ;
    }

    pEncryptedData = pTemplate->getNativeElement() ;

    //remember the position of the element to be signed
    sal_Bool isParentRef = sal_True;
    xmlNodePtr pParent = pEncryptedData->parent;
    xmlNodePtr referenceNode;

    if (pEncryptedData == pParent->children)
    {
        referenceNode = pParent;
    }
    else
    {
        referenceNode = pEncryptedData->prev;
        isParentRef = sal_False;
    }

     setErrorRecorder( );

    sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber();
    sal_Int32 i;

    for (i=0; i<nSecurityEnvironment; ++i)
    {
        Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i);

        //Get Keys Manager
        Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
        if( !aEnvironment.is() ) {
             throw RuntimeException() ;
        }

        SecurityEnvironment_NssImpl* pSecEnv =
            reinterpret_cast<SecurityEnvironment_NssImpl*>(
                sal::static_int_cast<sal_uIntPtr>(
                    xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() )));
        if( pSecEnv == NULL )
            throw RuntimeException() ;

        pMngr = pSecEnv->createKeysManager() ; //i39448
        if( !pMngr ) {
            throw RuntimeException() ;
        }

        //Create Encryption context
        pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
        if( pEncCtx == NULL )
        {
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448
            //throw XMLEncryptionException() ;
            clearErrorRecorder();
            return aTemplate;
        }

        //Decrypt the template
        if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL ))
        {
            //The decryption succeeds

            //Destroy the encryption context
            xmlSecEncCtxDestroy( pEncCtx ) ;
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448

            //get the decrypted element
            XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef?
                (referenceNode->children):(referenceNode->next));

            //return ret;
            aTemplate->setTemplate(ret);
            break;
        }
        else
        {
            //The decryption fails, continue with the next security environment
            xmlSecEncCtxDestroy( pEncCtx ) ;
            pSecEnv->destroyKeysManager( pMngr ) ; //i39448
        }
    }

    clearErrorRecorder();
    return aTemplate;
}

/* XInitialization */
void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& /*aArguments*/ ) throw( Exception, RuntimeException ) {
    // TBD
} ;

/* XServiceInfo */
OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) {
    return impl_getImplementationName() ;
}

/* XServiceInfo */
sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
    Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
    const OUString* pArray = seqServiceNames.getConstArray() ;
    for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
        if( *( pArray + i ) == serviceName )
            return sal_True ;
    }
    return sal_False ;
}

/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) {
    return impl_getSupportedServiceNames() ;
}

//Helper for XServiceInfo
Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() {
    ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
    Sequence< OUString > seqServiceNames( 1 ) ;
    seqServiceNames.getArray()[0] = OUString("com.sun.star.xml.crypto.XMLEncryption") ;
    return seqServiceNames ;
}

OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) {
    return OUString("com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl") ;
}

//Helper for registry
Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
    return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ;
}

Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
    //Reference< XSingleServiceFactory > xFactory ;
    //xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
    //return xFactory ;
    return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: delete.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-19 09:30:36 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#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 pchfix02 (1.14.58); FILE MERGED 2006/09/01 17:53:36 kaib 1.14.58.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  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;
}

<|endoftext|>