<commit_before>/*
 *  Copyright (c) 2011 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 <stdio.h>
#include <time.h>

#include "interpolator.h"
#include "vplib.h"
#include "test_util.h"

using namespace webrtc;

int interpolation_test(CmdArgs& args)
{
    // Read input file, interpolate first frame according to requested method
    // for now only YUV input and output

    FILE* sourceFile;
    FILE* outputFile;

    std::string outname = args.outputFile;
    if (outname == "")
    {
        outname = "InterTest_out.yuv";
    }
    if (args.width < 1 || args.height < 1 ||
        args.dstWidth < 1 || args.dstHeight < 1)
    {
        printf("Error in input dimensions\n" );
        return -1;
    }

    WebRtc_Word32 ret;

    // create interpolator
    webrtc::interpolator* inter = new webrtc::interpolator();
    ret = inter->Set(args.width, args.height,
                     args.dstWidth, args.dstHeight,
                     kI420, kI420,
                     (webrtc::interpolatorType) args.intMethod);
    if (ret != 0)
    {
        printf("Error in set interpolator = %d\n", ret);
        delete inter;
        return ret;
    }

    // read frame into buffer / create destination buffer
    if ((outputFile = fopen(outname.c_str(), "wb")) == NULL)
    {
        printf("Cannot write file %s.\n", outname.c_str());
        exit(1);
    }

    std::string inname = args.inputFile;
    if ((sourceFile = fopen(inname.c_str(), "rb")) == NULL)
    {
        printf("Cannot read file %s.\n", inname.c_str());
        exit(1);
    }

    WebRtc_UWord32 inRequiredSize = args.width * args.height * 3 >> 1;
    WebRtc_UWord32 outRequiredSize = args.dstWidth * args.dstHeight * 3 >> 1;
    WebRtc_UWord8* inputBuffer = new WebRtc_UWord8[inRequiredSize];
    WebRtc_UWord8* outputBuffer = new WebRtc_UWord8[outRequiredSize];
    WebRtc_UWord32 outputBufferSz = outRequiredSize;

    clock_t startClock, TotalClock;
    TotalClock = 0;
    int frameCnt = 0;

    // running through entire sequence
    while (feof(sourceFile) == 0)
    {
        if (inRequiredSize != fread(inputBuffer, 1, inRequiredSize, sourceFile))
        {
            break;
        }

        startClock = clock();
        ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
        TotalClock += clock() - startClock;

        if (ret == args.dstHeight)
        {
            fwrite(outputBuffer, 1, outRequiredSize, outputFile);
            ret = 0;  // signaling OK to main tester
        }
        else
        {
            printf("frame #%d: Interpolation Error, ret = %d\n", frameCnt, ret);
        }
        frameCnt++;
        printf(".");
    }

    printf("\nProcessed %d frames\n", frameCnt);
    if (frameCnt)
    {
        printf("\nAvg. Time per frame[mS]: %.2lf\n",
              (1000.0 * static_cast<double>(TotalClock + 0.0)
               /CLOCKS_PER_SEC)/frameCnt);
    }

    delete [] outputBuffer;
    outputBuffer = NULL;
    outputBufferSz = 0;

    // running some sanity checks
    ret = inter->Set(0, 10, 20, 30, kI420, kI420,
                    (webrtc::interpolatorType) args.intMethod);
    TEST(ret < 0);
    ret = inter->Set(1, 10, 0, 30, kI420, kI420,
                       (webrtc::interpolatorType) args.intMethod);
    TEST(ret < 0);

    rewind(sourceFile);
    if (inRequiredSize != fread(inputBuffer, 1, inRequiredSize, sourceFile))
    {
        printf("Error reading input file\n");
        return -1;
    }

    ret = inter->Set(20, 10, 20, 30, kI420, kI420,
                     (webrtc::interpolatorType) 2);
    TEST(ret < 0);
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret < 0);

    // computing required size for user-defined settings
    WebRtc_UWord32 dstRequiredSize = args.dstWidth * args.dstHeight * 3 >> 1;
    // null output buffer - should allocate required size
    ret = inter->Set(args.width, args.height,
                     args.dstWidth, args.dstHeight,
                     kI420, kI420,
                     (webrtc::interpolatorType) args.intMethod);
    TEST(ret == 0);
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    // output buffer too small (should reallocate)
    outputBufferSz = dstRequiredSize / 2;
    outputBuffer = new WebRtc_UWord8[outputBufferSz];
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    // output buffer too large (should maintain existing buffer size)
    outputBufferSz = dstRequiredSize + 20;
    outputBuffer = new WebRtc_UWord8[outputBufferSz];
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize + 20);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    fclose(sourceFile);
    fclose(outputFile);

    delete inter;
    delete [] inputBuffer;

    return 0;
}
<commit_msg>Fix win compile error for interpolator_test Review URL: http://webrtc-codereview.appspot.com/269003<commit_after>/*
 *  Copyright (c) 2011 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 <stdio.h>
#include <time.h>

#include "interpolator.h"
#include "vplib.h"
#include "test_util.h"

using namespace webrtc;

int interpolation_test(CmdArgs& args)
{
    // Read input file, interpolate first frame according to requested method
    // for now only YUV input and output

    FILE* sourceFile;
    FILE* outputFile;

    std::string outname = args.outputFile;
    if (outname.empty())
    {
        outname = "InterTest_out.yuv";
    }
    if (args.width < 1 || args.height < 1 ||
        args.dstWidth < 1 || args.dstHeight < 1)
    {
        printf("Error in input dimensions\n" );
        return -1;
    }

    WebRtc_Word32 ret;

    // create interpolator
    webrtc::interpolator* inter = new webrtc::interpolator();
    ret = inter->Set(args.width, args.height,
                     args.dstWidth, args.dstHeight,
                     kI420, kI420,
                     (webrtc::interpolatorType) args.intMethod);
    if (ret != 0)
    {
        printf("Error in set interpolator = %d\n", ret);
        delete inter;
        return ret;
    }

    // read frame into buffer / create destination buffer
    if ((outputFile = fopen(outname.c_str(), "wb")) == NULL)
    {
        printf("Cannot write file %s.\n", outname.c_str());
        exit(1);
    }

    std::string inname = args.inputFile;
    if ((sourceFile = fopen(inname.c_str(), "rb")) == NULL)
    {
        printf("Cannot read file %s.\n", inname.c_str());
        exit(1);
    }

    WebRtc_UWord32 inRequiredSize = args.width * args.height * 3 >> 1;
    WebRtc_UWord32 outRequiredSize = args.dstWidth * args.dstHeight * 3 >> 1;
    WebRtc_UWord8* inputBuffer = new WebRtc_UWord8[inRequiredSize];
    WebRtc_UWord8* outputBuffer = new WebRtc_UWord8[outRequiredSize];
    WebRtc_UWord32 outputBufferSz = outRequiredSize;

    clock_t startClock, TotalClock;
    TotalClock = 0;
    int frameCnt = 0;

    // running through entire sequence
    while (feof(sourceFile) == 0)
    {
        if (inRequiredSize != fread(inputBuffer, 1, inRequiredSize, sourceFile))
        {
            break;
        }

        startClock = clock();
        ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
        TotalClock += clock() - startClock;

        if (ret == args.dstHeight)
        {
            fwrite(outputBuffer, 1, outRequiredSize, outputFile);
            ret = 0;  // signaling OK to main tester
        }
        else
        {
            printf("frame #%d: Interpolation Error, ret = %d\n", frameCnt, ret);
        }
        frameCnt++;
        printf(".");
    }

    printf("\nProcessed %d frames\n", frameCnt);
    if (frameCnt)
    {
        printf("\nAvg. Time per frame[mS]: %.2lf\n",
              (1000.0 * static_cast<double>(TotalClock + 0.0)
               /CLOCKS_PER_SEC)/frameCnt);
    }

    delete [] outputBuffer;
    outputBuffer = NULL;
    outputBufferSz = 0;

    // running some sanity checks
    ret = inter->Set(0, 10, 20, 30, kI420, kI420,
                    (webrtc::interpolatorType) args.intMethod);
    TEST(ret < 0);
    ret = inter->Set(1, 10, 0, 30, kI420, kI420,
                       (webrtc::interpolatorType) args.intMethod);
    TEST(ret < 0);

    rewind(sourceFile);
    if (inRequiredSize != fread(inputBuffer, 1, inRequiredSize, sourceFile))
    {
        printf("Error reading input file\n");
        return -1;
    }

    ret = inter->Set(20, 10, 20, 30, kI420, kI420,
                     (webrtc::interpolatorType) 2);
    TEST(ret < 0);
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret < 0);

    // computing required size for user-defined settings
    WebRtc_UWord32 dstRequiredSize = args.dstWidth * args.dstHeight * 3 >> 1;
    // null output buffer - should allocate required size
    ret = inter->Set(args.width, args.height,
                     args.dstWidth, args.dstHeight,
                     kI420, kI420,
                     (webrtc::interpolatorType) args.intMethod);
    TEST(ret == 0);
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    // output buffer too small (should reallocate)
    outputBufferSz = dstRequiredSize / 2;
    outputBuffer = new WebRtc_UWord8[outputBufferSz];
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    // output buffer too large (should maintain existing buffer size)
    outputBufferSz = dstRequiredSize + 20;
    outputBuffer = new WebRtc_UWord8[outputBufferSz];
    ret = inter->Interpolate(inputBuffer, outputBuffer, outputBufferSz);
    TEST(ret == args.dstHeight);
    TEST(outputBufferSz == dstRequiredSize + 20);
    if (outputBuffer)
    {
        delete [] outputBuffer;
    }

    fclose(sourceFile);
    fclose(outputFile);

    delete inter;
    delete [] inputBuffer;

    return 0;
}
<|endoftext|>


<commit_before>// $Id: support.C,v 1.11 2000/07/06 14:44:09 oliver Exp $

#include <BALL/MOLMEC/COMMON/support.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/atomIterator.h>
#include <BALL/COMMON/limits.h>

using namespace std;

namespace BALL
{

	namespace MolmecSupport
	{

		Size calculateNonBondedAtomPairs
			(vector< pair <Atom*, Atom*> >& pair_vector,
			 const AtomVector& atom_vector,
			 const Box3& box, double distance,
			 bool periodic_boundary_enabled,
			 PairListAlgorithmType type)
		{

			// determine lower and upper corner of the hash grid that contains the box
			// plus "distance" many units on each side
			Vector3 lower(Limits<float>::max(), Limits<float>::max(), Limits<float>::max());
			Vector3 upper(Limits<float>::min(), Limits<float>::min(), Limits<float>::min());

			// Iterators for the atom vector
			AtomVector::ConstIterator atom_it;
			AtomVector::ConstIterator atom_it2;

			// Position vectors
			Vector3 position;
			Vector3 new_position;
			Vector3 difference;

			// the box width / length / depth
			double period_x;
			double period_y;
			double period_z;

			// Are atoms stored in atom_vector?

			if (atom_vector.size() == 0)
			{
				Log.warn() << " calculateNonBondedAtomPairs: atom_vector is empty " << endl;
				return 0;
			}

			// Test if periodic boundary is enabled or not

			if (periodic_boundary_enabled)
			{
				// calculate the size of the box
				period_x = box.getWidth();
				period_y = box.getHeight();
				period_z = box.getDepth();

				if (distance < period_x)
				{
					lower.x = box.a.x - distance;
					upper.x = box.b.x + distance;
				}
				else
				{
					lower.x = box.a.x - period_x;
					upper.x = box.b.x + period_x;
				}

				if (distance < period_y)
				{
					lower.y = box.a.y - distance;
					upper.y = box.b.y + distance;
				}
				else
				{
					lower.y = box.a.y - period_y;
					upper.y = box.b.y + period_y;
				}

				if (distance < period_z)
				{
					lower.z = box.a.z - distance;
					upper.z = box.b.z + distance;
				}
				else
				{
					lower.z = box.a.z - period_z;
					upper.z = box.b.z + period_z;
				}
			}
			else
			{
				for (atom_it = atom_vector.begin(); atom_it != atom_vector.end(); ++atom_it)
				{
					position = (*atom_it)->getPosition();
					if (position.x < lower.x) lower.x = position.x;
					if (position.y < lower.y) lower.y = position.y;
					if (position.z < lower.z) lower.z = position.z;
					if (position.x > upper.x) upper.x = position.x;
					if (position.y > upper.y) upper.y = position.y;
					if (position.z > upper.z) upper.z = position.z;
				}

				lower.x -= distance;
				lower.y -= distance;
				lower.z -= distance;
				upper.x += distance;
				upper.y += distance;
				upper.z += distance;
			}

			// Counter for the number of neighbored atom pairs.
			Size	counter = 0;

			// Squared distance
			double  squared_distance = distance * distance;

			// initialize the hash grid
			HashGrid3<Atom*>	grid(lower - Vector3(0.1), upper - lower + Vector3(0.2), distance);
			HashGridBox3<Atom*>* hbox;

			// Iterators and hash box pointer for the grid search
			HashGridBox3<Atom*>::BoxIterator box_it;
			HashGridBox3<Atom*>::DataIterator data_it;

			// Test if periodic boundary is enabled or not

			if (periodic_boundary_enabled)
			{
				// Calculate the half periods for determining the minimal image
				double half_period_x = period_x * 0.5;
				double half_period_y = period_y * 0.5;
				double half_period_z = period_z * 0.5;

				// Check what kind of algorithm should be used for determining the neighbours

				if (type == BRUTE_FORCE)
				{
					// Brute force algorithm

					for ( atom_it = atom_vector.begin(); atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();
						for (atom_it2 = atom_it, atom_it2++; atom_it2 != atom_vector.end(); ++atom_it2)
						{
							new_position = position;
							difference = position - (*atom_it2)->getPosition();

							if (difference.x < -half_period_x)
								new_position.x += period_x;
							else if (difference.x > half_period_x)
								new_position.x -= period_x;

							if (difference.y < -half_period_y)
								new_position.y += period_y;
							else if (difference.y > half_period_y)
								new_position.y -= period_y;

							if (difference.z < -half_period_z)
								new_position.z += period_z;
							else if (difference.z > half_period_z)
								new_position.z -= period_z;

							if ((new_position.getSquareDistance((*atom_it2)->getPosition())) <= squared_distance)
							{
								pair_vector.push_back(pair<Atom*, Atom*>(*atom_it, *atom_it2));
								counter++;
							}
						}
					}
				}
				else
				{
					// Use a hash grid with box length "distance" to determine all neigboured atom pairs

					for (atom_it = atom_vector.begin() ; atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();

						// Search all neighbor atoms of "atom_it" that are stored in the hash grid

						// Calculate the 27 images of the atom and determine their neighbours

						for (short x = -1; x < 2 ; x++)
						{
							new_position.x = position.x + x * period_x;
							for (short y = -1; y < 2 ; y++)
							{
								new_position.y = position.y + y * period_y;
								for (short z = -1; z < 2 ; z++)
								{
									new_position.z = position.z + z * period_z;
									hbox = grid.getBox(new_position);

									if (hbox != 0)
									{
										for (box_it = hbox->beginBox(); +box_it; ++box_it)
										{
											for (data_it = (*box_it).beginData(); +data_it; ++data_it)
											{

												difference = new_position - (*data_it)->getPosition();
												if (difference.x > -half_period_x && difference.x <= half_period_x &&
														difference.y > -half_period_y && difference.y <= half_period_y &&
														difference.z > -half_period_z && difference.z <= half_period_z &&
														difference.getSquareLength() <= squared_distance)
												{
													pair_vector.push_back(pair<Atom*, Atom*>(*atom_it, *data_it));
													counter++;
												}
											}
										}
									}
								}
							}
						}

						// insert the new atom into the hash grid
						grid.insert(position, (*atom_it));
					}
				}
			}
			else
			{
				// Check what kind of algorithm should be used for calculating the neighbours
				if (type == BRUTE_FORCE)
				{
					// Brute force algorithm
					for (Size atom_index_a = 0 ; atom_index_a < (atom_vector.size() - 1) ; ++atom_index_a)
					{
						position = atom_vector[atom_index_a]->getPosition();
						for (Size atom_index_b = atom_index_a + 1; atom_index_b < atom_vector.size(); ++atom_index_b)
						{
							if (((position.getSquareDistance(atom_vector[atom_index_b]->getPosition())) <= squared_distance)
									&& !atom_vector[atom_index_a]->isBondedTo(*atom_vector[atom_index_b])
									&& !atom_vector[atom_index_a]->isGeminal(*atom_vector[atom_index_b]))
							{
								pair_vector.push_back(pair<Atom*,Atom*>(atom_vector[atom_index_a], atom_vector[atom_index_b]));
								counter++;
							}
						}
					}

				}
				else
				{
					// Use a hash grid with box length "distance" to determine all neigboured atom pairs

					for (atom_it = atom_vector.begin(); atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();

						// Search all neighbor atoms of "atom_it" that are stored in the hash grid
						hbox = grid.getBox(position);
						if (hbox != 0)
						{
							for (box_it = hbox->beginBox(); +box_it; ++box_it)
							{
								for (data_it = (*box_it).beginData(); +data_it; ++data_it)
								{
									if (((position.getSquareDistance((*data_it)->getPosition())) <= squared_distance)
											&& !(*data_it)->isBondedTo(**atom_it)
											&& !(*data_it)->isGeminal(**atom_it))
									{
										pair_vector.push_back(pair<Atom*,Atom*>((*atom_it),(*data_it)));
										counter++;
									}
								}
							}
						}
						else
						{
							Log.warn() << "calculateNonBondedAtomPairs: hbox = 0 for position " << position
													<< " (grid dimensions: " << grid.getOrigin() << ")" << endl;
						}

						// Insert the new atom into the hash grid
						grid.insert(position, (*atom_it));
					}
				}
			}

			return counter;
		}

		// Add solvent molecules to systemA if they lie in the box "box" and if
		// they do not overlap with molecules in systemA. The solvent molecules
		// are added to systemA.

		Size addNonOverlappingMolecules
			(System&  system_A, const System& system_B,
			 const Box3& box, double distance)
		{
			Vector3	vector(distance);

			// Initialize HashGrid for storing atoms of system_A
			HashGrid3<Atom*> grid(box.a - vector, box.b + vector, distance);

			// Insert the atoms into the hash grid
			AtomIterator atom_it;
			for (atom_it = system_A.beginAtom(); +atom_it; ++atom_it)
			{
				grid.insert(atom_it->getPosition(), &*atom_it);
			}

			Molecule* old_molecule = 0;
			Molecule* new_molecule = 0;
			bool	add = false;
			Size atom_counter = 0;
			Size mol_counter = 0;
			double square_distance = distance * distance;
			double mass = 0;
			Vector3	center_of_gravity(0.0);

			// Iterate over all atoms in system_B and test the different molecules as follows:
			// Calculate the number of atoms of the molecule and its mass. If the number of molecules
			// is larger 0 and the mass is larger 0, then a another test has to be carried out whether
			// the center of gravity is in the box. If so, the molecule will be inserted in system_A:

			atom_it = system_B.beginAtom();
			old_molecule = atom_it->getMolecule();
			for (	; +atom_it; ++atom_it)
			{
				// Test if a new molecule is reached and if the old can be inserted into sytemA

				new_molecule = atom_it->getMolecule();
				if (new_molecule != old_molecule)
				{
					if (add == true)
					{
						if (atom_counter > 0 && mass != 0)
						{
							center_of_gravity /= mass;
							if (center_of_gravity.x >= box.a.x && center_of_gravity.x <= box.b.x &&
									center_of_gravity.y >= box.a.y && center_of_gravity.y <= box.b.y &&
									center_of_gravity.z >= box.a.z && center_of_gravity.z <= box.b.z )
							{
										system_A.insert(*new Molecule(*old_molecule));
										mol_counter++;
							}
						}
					}

					old_molecule = new_molecule;
					add = true;
					center_of_gravity.x = 0;
					center_of_gravity.y = 0;
					center_of_gravity.z = 0;
					atom_counter = 0;
					mass = 0;
				}

				HashGridBox3<Atom*>* hbox;
				HashGridBox3<Atom*>::BoxIterator box_it;
				HashGridBox3<Atom*>::DataIterator data_it;
				Vector3 position = (*atom_it).getPosition();

				float atomic_mass = atom_it->getElement().getAtomicWeight();
				center_of_gravity += (atomic_mass * position);
				mass += atomic_mass;
				atom_counter++;

				hbox = grid.getBox(position);

				if (hbox != 0)
				{
					for (box_it = hbox->beginBox(); +box_it && add; ++box_it)
					{
						for (data_it = box_it->beginData(); +data_it && add ; ++data_it)
						{
							if ((position.getSquareDistance((*data_it)->getPosition())) < square_distance)
							{
								add = false;
							}
						}
					}
				}
			}

			return(mol_counter);
		}

	}	// namespace MolmecSupport

} // namespace BALL
<commit_msg>fixed: addNonOverlappingMolecule() did not work: hash grid was initialized incorrectly cosmetic changes<commit_after>// $Id: support.C,v 1.12 2000/07/10 21:22:48 oliver Exp $

#include <BALL/MOLMEC/COMMON/support.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/atomIterator.h>
#include <BALL/COMMON/limits.h>

using namespace std;

namespace BALL
{

	namespace MolmecSupport
	{

		Size calculateNonBondedAtomPairs
			(vector< pair <Atom*, Atom*> >& pair_vector,
			 const AtomVector& atom_vector,
			 const Box3& box, double distance,
			 bool periodic_boundary_enabled,
			 PairListAlgorithmType type)
		{

			// determine lower and upper corner of the hash grid that contains the box
			// plus "distance" many units on each side
			Vector3 lower(Limits<float>::max(), Limits<float>::max(), Limits<float>::max());
			Vector3 upper(Limits<float>::min(), Limits<float>::min(), Limits<float>::min());

			// Iterators for the atom vector
			AtomVector::ConstIterator atom_it;
			AtomVector::ConstIterator atom_it2;

			// Position vectors
			Vector3 position;
			Vector3 new_position;
			Vector3 difference;

			// the box width / length / depth
			double period_x;
			double period_y;
			double period_z;

			// Are atoms stored in atom_vector?

			if (atom_vector.size() == 0)
			{
				Log.warn() << " calculateNonBondedAtomPairs: atom_vector is empty " << endl;
				return 0;
			}

			// Test if periodic boundary is enabled or not

			if (periodic_boundary_enabled)
			{
				// calculate the size of the box
				period_x = box.getWidth();
				period_y = box.getHeight();
				period_z = box.getDepth();

				if (distance < period_x)
				{
					lower.x = box.a.x - distance;
					upper.x = box.b.x + distance;
				}
				else
				{
					lower.x = box.a.x - period_x;
					upper.x = box.b.x + period_x;
				}

				if (distance < period_y)
				{
					lower.y = box.a.y - distance;
					upper.y = box.b.y + distance;
				}
				else
				{
					lower.y = box.a.y - period_y;
					upper.y = box.b.y + period_y;
				}

				if (distance < period_z)
				{
					lower.z = box.a.z - distance;
					upper.z = box.b.z + distance;
				}
				else
				{
					lower.z = box.a.z - period_z;
					upper.z = box.b.z + period_z;
				}
			}
			else
			{
				for (atom_it = atom_vector.begin(); atom_it != atom_vector.end(); ++atom_it)
				{
					position = (*atom_it)->getPosition();
					if (position.x < lower.x) lower.x = position.x;
					if (position.y < lower.y) lower.y = position.y;
					if (position.z < lower.z) lower.z = position.z;
					if (position.x > upper.x) upper.x = position.x;
					if (position.y > upper.y) upper.y = position.y;
					if (position.z > upper.z) upper.z = position.z;
				}

				lower.x -= distance;
				lower.y -= distance;
				lower.z -= distance;
				upper.x += distance;
				upper.y += distance;
				upper.z += distance;
			}

			// Counter for the number of neighbored atom pairs.
			Size	counter = 0;

			// Squared distance
			double  squared_distance = distance * distance;

			// initialize the hash grid
			HashGrid3<Atom*>	grid(lower - Vector3(0.1), upper - lower + Vector3(0.2), distance);
			HashGridBox3<Atom*>* hbox;

			// Iterators and hash box pointer for the grid search
			HashGridBox3<Atom*>::BoxIterator box_it;
			HashGridBox3<Atom*>::DataIterator data_it;

			// Test if periodic boundary is enabled or not

			if (periodic_boundary_enabled)
			{
				// Calculate the half periods for determining the minimal image
				double half_period_x = period_x * 0.5;
				double half_period_y = period_y * 0.5;
				double half_period_z = period_z * 0.5;

				// Check what kind of algorithm should be used for determining the neighbours

				if (type == BRUTE_FORCE)
				{
					// Brute force algorithm

					for ( atom_it = atom_vector.begin(); atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();
						for (atom_it2 = atom_it, atom_it2++; atom_it2 != atom_vector.end(); ++atom_it2)
						{
							new_position = position;
							difference = position - (*atom_it2)->getPosition();

							if (difference.x < -half_period_x)
								new_position.x += period_x;
							else if (difference.x > half_period_x)
								new_position.x -= period_x;

							if (difference.y < -half_period_y)
								new_position.y += period_y;
							else if (difference.y > half_period_y)
								new_position.y -= period_y;

							if (difference.z < -half_period_z)
								new_position.z += period_z;
							else if (difference.z > half_period_z)
								new_position.z -= period_z;

							if ((new_position.getSquareDistance((*atom_it2)->getPosition())) <= squared_distance)
							{
								pair_vector.push_back(pair<Atom*, Atom*>(*atom_it, *atom_it2));
								counter++;
							}
						}
					}
				}
				else
				{
					// Use a hash grid with box length "distance" to determine all neigboured atom pairs

					for (atom_it = atom_vector.begin() ; atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();

						// Search all neighbor atoms of "atom_it" that are stored in the hash grid

						// Calculate the 27 images of the atom and determine their neighbours

						for (short x = -1; x < 2 ; x++)
						{
							new_position.x = position.x + x * period_x;
							for (short y = -1; y < 2 ; y++)
							{
								new_position.y = position.y + y * period_y;
								for (short z = -1; z < 2 ; z++)
								{
									new_position.z = position.z + z * period_z;
									hbox = grid.getBox(new_position);

									if (hbox != 0)
									{
										for (box_it = hbox->beginBox(); +box_it; ++box_it)
										{
											for (data_it = (*box_it).beginData(); +data_it; ++data_it)
											{

												difference = new_position - (*data_it)->getPosition();
												if (difference.x > -half_period_x && difference.x <= half_period_x &&
														difference.y > -half_period_y && difference.y <= half_period_y &&
														difference.z > -half_period_z && difference.z <= half_period_z &&
														difference.getSquareLength() <= squared_distance)
												{
													pair_vector.push_back(pair<Atom*, Atom*>(*atom_it, *data_it));
													counter++;
												}
											}
										}
									}
								}
							}
						}

						// insert the new atom into the hash grid
						grid.insert(position, (*atom_it));
					}
				}
			}
			else
			{
				// Check what kind of algorithm should be used for calculating the neighbours
				if (type == BRUTE_FORCE)
				{
					// Brute force algorithm
					for (Size atom_index_a = 0 ; atom_index_a < (atom_vector.size() - 1) ; ++atom_index_a)
					{
						position = atom_vector[atom_index_a]->getPosition();
						for (Size atom_index_b = atom_index_a + 1; atom_index_b < atom_vector.size(); ++atom_index_b)
						{
							if (((position.getSquareDistance(atom_vector[atom_index_b]->getPosition())) <= squared_distance)
									&& !atom_vector[atom_index_a]->isBondedTo(*atom_vector[atom_index_b])
									&& !atom_vector[atom_index_a]->isGeminal(*atom_vector[atom_index_b]))
							{
								pair_vector.push_back(pair<Atom*,Atom*>(atom_vector[atom_index_a], atom_vector[atom_index_b]));
								counter++;
							}
						}
					}

				}
				else
				{
					// Use a hash grid with box length "distance" to determine all neigboured atom pairs

					for (atom_it = atom_vector.begin(); atom_it != atom_vector.end() ; ++atom_it)
					{
						position = (*atom_it)->getPosition();

						// Search all neighbor atoms of "atom_it" that are stored in the hash grid
						hbox = grid.getBox(position);
						if (hbox != 0)
						{
							for (box_it = hbox->beginBox(); +box_it; ++box_it)
							{
								for (data_it = (*box_it).beginData(); +data_it; ++data_it)
								{
									if (((position.getSquareDistance((*data_it)->getPosition())) <= squared_distance)
											&& !(*data_it)->isBondedTo(**atom_it)
											&& !(*data_it)->isGeminal(**atom_it))
									{
										pair_vector.push_back(pair<Atom*,Atom*>((*atom_it),(*data_it)));
										counter++;
									}
								}
							}
						}
						else
						{
							Log.warn() << "calculateNonBondedAtomPairs: hbox = 0 for position " << position
													<< " (grid dimensions: " << grid.getOrigin() << ")" << endl;
						}

						// Insert the new atom into the hash grid
						grid.insert(position, (*atom_it));
					}
				}
			}

			return counter;
		}

		// Add solvent molecules from "solvent" to "solute" if they lie
		// in the box "box" and if they do not overlap with molecules in "solute".
		Size addNonOverlappingMolecules
			(System& solute, const System& solvent, const Box3& box, double distance)
		{
			// Initialize HashGrid for storing atoms of solute
			// (we add 1% of the distance to make sure we get no points
			// on the grid boundary)
			Vector3	vector(distance * 1.02);
			HashGrid3<Atom*> grid(box.a - vector, box.b - box.a + vector + vector, distance);

			// Insert the atoms of the solute into the hash grid
			AtomIterator atom_it = solute.beginAtom();
			for ( ; +atom_it; ++atom_it)
			{
				grid.insert(atom_it->getPosition(), &*atom_it);
			}

			Molecule* old_molecule = 0;
			Molecule* new_molecule = 0;
			bool add = true;
			Size atom_counter = 0;
			Size mol_counter = 0;
			double square_distance = distance * distance;
			double mass = 0;
			Vector3	center_of_gravity(0.0);

			// Iterate over all atoms in solvent and test the different molecules as follows:
			// Calculate the number of atoms of the molecule and its mass. If the number of molecules
			// is larger 0 and the mass is larger 0, then a another test has to be carried out whether
			// the center of gravity is in the box. If so, the molecule will be inserted in solute:

			atom_it = solvent.beginAtom();
			if (atom_it != solvent.endAtom())
			{
				old_molecule = atom_it->getMolecule();
				for (	; +atom_it; ++atom_it)
				{
					// Test if a new molecule is reached and if the old can be inserted
					// into the solute system
					new_molecule = atom_it->getMolecule();
					if (new_molecule != old_molecule)
					{
						if (add == true)
						{
							if ((atom_counter > 0) && (mass != 0))
							{
								center_of_gravity /= mass;
								if ((center_of_gravity.x >= box.a.x) && (center_of_gravity.x <= box.b.x)
										&& (center_of_gravity.y >= box.a.y) && (center_of_gravity.y <= box.b.y)
										&& (center_of_gravity.z >= box.a.z) && (center_of_gravity.z <= box.b.z))
								{
									// copy the solvent molecule and insert it into
									// the solute system
									Molecule* solvent_molecule = new Molecule(*old_molecule);
									solute.insert(*solvent_molecule);
									mol_counter++;
								}
							}
						}

						old_molecule = new_molecule;
						add = true;
						center_of_gravity.x = 0;
						center_of_gravity.y = 0;
						center_of_gravity.z = 0;
						atom_counter = 0;
						mass = 0;
					}

					Vector3 position = atom_it->getPosition();

					float atomic_mass = atom_it->getElement().getAtomicWeight();
					center_of_gravity += atomic_mass * position;
					mass += atomic_mass;
					atom_counter++;

					// check for all collisions with any of the solute's atoms
					HashGridBox3<Atom*>* hbox = grid.getBox(position);
					if ((hbox != 0) && add)
					{
						HashGridBox3<Atom*>::DataIterator data_it;
						HashGridBox3<Atom*>::BoxIterator box_it;
						for (box_it = hbox->beginBox(); +box_it && add; ++box_it)
						{
							for (data_it = box_it->beginData(); +data_it && add; ++data_it)
							{
								if ((position.getSquareDistance((*data_it)->getPosition())) < square_distance)
								{
									add = false;
								}
							}
						}
					}
				}
			}

			// return the number of solvent molecules
			return mol_counter;
		}

	}	// namespace MolmecSupport

} // namespace BALL
<|endoftext|>


<commit_before>//
// PROJECT:         Aspia
// FILE:            console/about_dialog.cc
// LICENSE:         GNU General Public License 3
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "console/about_dialog.h"

#include <QAbstractButton>
#include <QDesktopServices>

#include "version.h"

namespace aspia {

namespace {

const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "http://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";

const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };
const char* kTranslators[] = { "Dmitry Chapyshev (Russian)" };
const char* kThirdParty[] =
{
    "Qt Framework © 2015 The Qt Company Ltd., GPL 3",
    "libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
    "libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
    "libsodium © 2013-2017 Frank Denis, ISC License",
    "protobuf © 2014 Google Inc., BSD 3-Clause License",
    "zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
    "FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
    "Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};

QString createList(const QString& title, const char* array[], size_t array_size)
{
    if (!array_size)
        return QString();

    QString list;

    for (size_t i = 0; i < array_size; ++i)
    {
        list.append(QString("• %1").arg(array[i]));
        if (i + 1 != array_size)
            list.append(QLatin1String("
"));
    }

    return QString("%1
%2").arg(title).arg(list);
}

} // namespace

AboutDialog::AboutDialog(QWidget* parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    setWindowFlag(Qt::WindowContextHelpButtonHint, false);

    ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));

    QString license =
        QString("%1
%2
%3")
        .arg(tr("Aspia is free software released under GNU General Public License 3."))
        .arg(tr("You can get a copy of license here:"))
        .arg(kGplLink);

    QString license_translation =
        QString("%1
%2")
        .arg(tr("You can also get a translation of GNU GPL license here:"))
        .arg(kGplTranslationLink);

    QString links =
        QString("%1
%2 %3
%4 %5")
        .arg(tr("Links:"))
        .arg(tr("Home page:")).arg(kHomeLink)
        .arg(tr("GitHub page:")).arg(kGitHubLink);

    QString developers =
        createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
    QString translators =
        createList(tr("Translators:"), kTranslators, _countof(kTranslators));
    QString third_party =
        createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));

    QString html;

    html += "";
    html += "
" + license + "
";
    html += "
" + license_translation + "
";
    html += "
" + links + "
";
    html += "
" + developers + "
";
    html += "
" + translators + "
";
    html += "
" + third_party + "
";
    html += "";

    ui.text_edit->setHtml(html);

    connect(ui.push_button_donate, &QPushButton::pressed, [this]()
    {
        QDesktopServices::openUrl(QUrl(kDonateLink));
    });

    connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}

AboutDialog::~AboutDialog() = default;

} // namespace aspia
<commit_msg>- Update translators list.<commit_after>//
// PROJECT:         Aspia
// FILE:            console/about_dialog.cc
// LICENSE:         GNU General Public License 3
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "console/about_dialog.h"

#include <QAbstractButton>
#include <QDesktopServices>

#include "version.h"

namespace aspia {

namespace {

const char kGplLink[] = "https://www.gnu.org/licenses/gpl.html";
const char kGplTranslationLink[] = "http://www.gnu.org/licenses/translations.html";
const char kHomeLink[] = "https://aspia.org";
const char kGitHubLink[] = "https://github.com/dchapyshev/aspia";
const char kDonateLink[] = "https://aspia.org/donate";

const char* kDevelopers[] = { "Dmitry Chapyshev (dmitry@aspia.ru)" };

const char* kTranslators[] =
{
    "Dmitry Chapyshev (Russian)",
    "Mark Jansen (Dutch)"
};

const char* kThirdParty[] =
{
    "Qt Framework © 2015 The Qt Company Ltd., GPL 3",
    "libvpx © 2010, The WebM Project authors, BSD 3-Clause License",
    "libyuv © 2011 The LibYuv Project Authors, BSD 3-Clause License",
    "libsodium © 2013-2017 Frank Denis, ISC License",
    "protobuf © 2014 Google Inc., BSD 3-Clause License",
    "zlib-ng © 1995-2013 Jean-loup Gailly and Mark Adler, Zlib License",
    "FatCow Icons © 2009-2014 FatCow Web Hosting, Creative Commons Attribution 3.0 License",
    "Fugue Icons © 2013 Yusuke Kamiyamane, Creative Commons Attribution 3.0 License"
};

QString createList(const QString& title, const char* array[], size_t array_size)
{
    if (!array_size)
        return QString();

    QString list;

    for (size_t i = 0; i < array_size; ++i)
    {
        list.append(QString("• %1").arg(array[i]));
        if (i + 1 != array_size)
            list.append(QLatin1String("
"));
    }

    return QString("%1
%2").arg(title).arg(list);
}

} // namespace

AboutDialog::AboutDialog(QWidget* parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    setWindowFlag(Qt::WindowContextHelpButtonHint, false);

    ui.label_version->setText(tr("Version: %1").arg(QLatin1String(ASPIA_VERSION_STRING)));

    QString license =
        QString("%1
%2
%3")
        .arg(tr("Aspia is free software released under GNU General Public License 3."))
        .arg(tr("You can get a copy of license here:"))
        .arg(kGplLink);

    QString license_translation =
        QString("%1
%2")
        .arg(tr("You can also get a translation of GNU GPL license here:"))
        .arg(kGplTranslationLink);

    QString links =
        QString("%1
%2 %3
%4 %5")
        .arg(tr("Links:"))
        .arg(tr("Home page:")).arg(kHomeLink)
        .arg(tr("GitHub page:")).arg(kGitHubLink);

    QString developers =
        createList(tr("Developers:"), kDevelopers, _countof(kDevelopers));
    QString translators =
        createList(tr("Translators:"), kTranslators, _countof(kTranslators));
    QString third_party =
        createList(tr("Third-party components:"), kThirdParty, _countof(kThirdParty));

    QString html;

    html += "";
    html += "
" + license + "
";
    html += "
" + license_translation + "
";
    html += "
" + links + "
";
    html += "
" + developers + "
";
    html += "
" + translators + "
";
    html += "
" + third_party + "
";
    html += "";

    ui.text_edit->setHtml(html);

    connect(ui.push_button_donate, &QPushButton::pressed, [this]()
    {
        QDesktopServices::openUrl(QUrl(kDonateLink));
    });

    connect(ui.push_button_close, &QPushButton::pressed, this, &AboutDialog::close);
}

AboutDialog::~AboutDialog() = default;

} // namespace aspia
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlComponent.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-26 14:42:16 $
 *
 *  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_dbaccess.hxx"
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif

namespace dbaxml
{
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLComponent)

OXMLComponent::OXMLComponent( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const ::rtl::OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ,const ::rtl::OUString& _sComponentServiceName
                ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_bAsTemplate(sal_False)
{
    DBG_CTOR(OXMLComponent,NULL);

    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        ::rtl::OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_HREF:
                m_sHREF = sValue;
                break;
            case XML_TOK_COMPONENT_NAME:
                m_sName = sValue;
                // sanitize the name. Previously, we allowed to create forms/reports/queries which contain
                // a / in their name, which nowadays is forbidden. To not lose such objects if they're contained
                // in older files, we replace the slash with something less offending.
                m_sName = m_sName.replace( '/', '_' );
                break;
            case XML_TOK_AS_TEMPLATE:
                m_bAsTemplate = (sValue == s_sTRUE ? sal_True : sal_False);
                break;
        }
    }
    if ( m_sHREF.getLength() && m_sName.getLength() && _xParentContainer.is() )
    {
        Sequence< Any > aArguments(3);
        PropertyValue aValue;
        // set as folder
        aValue.Name = PROPERTY_NAME;
        aValue.Value <<= m_sName;
        aArguments[0] <<= aValue;

        aValue.Name = PROPERTY_PERSISTENT_NAME;
        sal_Int32 nIndex = m_sHREF.lastIndexOf('/')+1;
        aValue.Value <<= m_sHREF.getToken(0,'/',nIndex);
        aArguments[1] <<= aValue;

        aValue.Name = PROPERTY_AS_TEMPLATE;
        aValue.Value <<= m_bAsTemplate;
        aArguments[2] <<= aValue;

        try
        {
            Reference< XMultiServiceFactory > xORB( _xParentContainer, UNO_QUERY_THROW );
            Reference< XInterface > xComponent( xORB->createInstanceWithArguments( _sComponentServiceName, aArguments ) );
            Reference< XNameContainer > xNameContainer( _xParentContainer, UNO_QUERY_THROW );
            xNameContainer->insertByName( m_sName, makeAny( xComponent ) );
        }
        catch(Exception&)
        {
            DBG_UNHANDLED_EXCEPTION();
        }
    }
}
// -----------------------------------------------------------------------------

OXMLComponent::~OXMLComponent()
{

    DBG_DTOR(OXMLComponent,NULL);
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.8.120); FILE MERGED 2008/03/31 13:26:54 rt 1.8.120.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlComponent.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif

namespace dbaxml
{
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLComponent)

OXMLComponent::OXMLComponent( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const ::rtl::OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ,const ::rtl::OUString& _sComponentServiceName
                ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_bAsTemplate(sal_False)
{
    DBG_CTOR(OXMLComponent,NULL);

    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        ::rtl::OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_HREF:
                m_sHREF = sValue;
                break;
            case XML_TOK_COMPONENT_NAME:
                m_sName = sValue;
                // sanitize the name. Previously, we allowed to create forms/reports/queries which contain
                // a / in their name, which nowadays is forbidden. To not lose such objects if they're contained
                // in older files, we replace the slash with something less offending.
                m_sName = m_sName.replace( '/', '_' );
                break;
            case XML_TOK_AS_TEMPLATE:
                m_bAsTemplate = (sValue == s_sTRUE ? sal_True : sal_False);
                break;
        }
    }
    if ( m_sHREF.getLength() && m_sName.getLength() && _xParentContainer.is() )
    {
        Sequence< Any > aArguments(3);
        PropertyValue aValue;
        // set as folder
        aValue.Name = PROPERTY_NAME;
        aValue.Value <<= m_sName;
        aArguments[0] <<= aValue;

        aValue.Name = PROPERTY_PERSISTENT_NAME;
        sal_Int32 nIndex = m_sHREF.lastIndexOf('/')+1;
        aValue.Value <<= m_sHREF.getToken(0,'/',nIndex);
        aArguments[1] <<= aValue;

        aValue.Name = PROPERTY_AS_TEMPLATE;
        aValue.Value <<= m_bAsTemplate;
        aArguments[2] <<= aValue;

        try
        {
            Reference< XMultiServiceFactory > xORB( _xParentContainer, UNO_QUERY_THROW );
            Reference< XInterface > xComponent( xORB->createInstanceWithArguments( _sComponentServiceName, aArguments ) );
            Reference< XNameContainer > xNameContainer( _xParentContainer, UNO_QUERY_THROW );
            xNameContainer->insertByName( m_sName, makeAny( xComponent ) );
        }
        catch(Exception&)
        {
            DBG_UNHANDLED_EXCEPTION();
        }
    }
}
// -----------------------------------------------------------------------------

OXMLComponent::~OXMLComponent()
{

    DBG_DTOR(OXMLComponent,NULL);
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlDocuments.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 06:46:48 $
 *
 *  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_dbaccess.hxx"
#ifndef DBA_XMLDOCUMENTS_HXX
#include "xmlDocuments.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef DBA_XMLQUERY_HXX
#include "xmlQuery.hxx"
#endif
#ifndef DBA_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLHIERARCHYCOLLECTION_HXX
#include "xmlHierarchyCollection.hxx"
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLDocuments)

OXMLDocuments::OXMLDocuments( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                , const OUString& rLName
                ,const Reference< XNameAccess >& _xContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ,const ::rtl::OUString& _sComponentServiceName) :
    SvXMLImportContext( rImport, nPrfx, rLName )
        ,m_xContainer(_xContainer)
        ,m_sCollectionServiceName(_sCollectionServiceName)
        ,m_sComponentServiceName(_sComponentServiceName)
{
    DBG_CTOR(OXMLDocuments,NULL);

}
// -----------------------------------------------------------------------------
OXMLDocuments::OXMLDocuments( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                , const OUString& rLName
                ,const Reference< XNameAccess >& _xContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
        ,m_xContainer(_xContainer)
        ,m_sCollectionServiceName(_sCollectionServiceName)
{
    DBG_CTOR(OXMLDocuments,NULL);
}
// -----------------------------------------------------------------------------
OXMLDocuments::OXMLDocuments( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                , const OUString& rLName
) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    DBG_CTOR(OXMLDocuments,NULL);
}
// -----------------------------------------------------------------------------

OXMLDocuments::~OXMLDocuments()
{

    DBG_DTOR(OXMLDocuments,NULL);
}
// -----------------------------------------------------------------------------

SvXMLImportContext* OXMLDocuments::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    const SvXMLTokenMap&    rTokenMap   = GetOwnImport().GetDocumentsElemTokenMap();

    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
        case XML_TOK_TABLE:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLTable( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,SERVICE_SDB_TABLEDEFINITION);
            break;
        case XML_TOK_QUERY:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer );
            break;
        case XML_TOK_COMPONENT:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName );
            break;
        //  case XML_TOK_QUERY_COLLECTION:
        case XML_TOK_COMPONENT_COLLECTION:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName );
            break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDocuments::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba23a (1.5.74); FILE MERGED 2007/02/26 11:48:09 fs 1.5.74.1: remove unused code Issue number:  #i74804# Submitted by:  jnavrati@openoffice.org Reviewed by:   frank.schoenheit@sun.com<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlDocuments.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:15:20 $
 *
 *  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_dbaccess.hxx"
#ifndef DBA_XMLDOCUMENTS_HXX
#include "xmlDocuments.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef DBA_XMLQUERY_HXX
#include "xmlQuery.hxx"
#endif
#ifndef DBA_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLHIERARCHYCOLLECTION_HXX
#include "xmlHierarchyCollection.hxx"
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLDocuments)

OXMLDocuments::OXMLDocuments( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                , const OUString& rLName
                ,const Reference< XNameAccess >& _xContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ,const ::rtl::OUString& _sComponentServiceName) :
    SvXMLImportContext( rImport, nPrfx, rLName )
        ,m_xContainer(_xContainer)
        ,m_sCollectionServiceName(_sCollectionServiceName)
        ,m_sComponentServiceName(_sComponentServiceName)
{
    DBG_CTOR(OXMLDocuments,NULL);

}
// -----------------------------------------------------------------------------
OXMLDocuments::OXMLDocuments( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                , const OUString& rLName
                ,const Reference< XNameAccess >& _xContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
        ,m_xContainer(_xContainer)
        ,m_sCollectionServiceName(_sCollectionServiceName)
{
    DBG_CTOR(OXMLDocuments,NULL);
}
// -----------------------------------------------------------------------------

OXMLDocuments::~OXMLDocuments()
{

    DBG_DTOR(OXMLDocuments,NULL);
}
// -----------------------------------------------------------------------------

SvXMLImportContext* OXMLDocuments::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    const SvXMLTokenMap&    rTokenMap   = GetOwnImport().GetDocumentsElemTokenMap();

    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
        case XML_TOK_TABLE:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLTable( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,SERVICE_SDB_TABLEDEFINITION);
            break;
        case XML_TOK_QUERY:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer );
            break;
        case XML_TOK_COMPONENT:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName );
            break;
        //  case XML_TOK_QUERY_COLLECTION:
        case XML_TOK_COMPONENT_COLLECTION:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName );
            break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLDocuments::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>Revert "PWGDQ/LMEE: change min. value of TOFbeta"<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableRowExchange.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:37:46 $
 *
 *  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 DBAUI_TABLEROW_EXCHANGE_HXX
#define DBAUI_TABLEROW_EXCHANGE_HXX

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

namespace dbaui
{
    class OTableRow;
    class OTableRowExchange : public TransferableHelper
    {
        ::std::vector<OTableRow*> m_vTableRow;
    public:
        OTableRowExchange(const ::std::vector<OTableRow*>& _rvTableRow);
    protected:
        virtual void        AddSupportedFormats();
        virtual sal_Bool    GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
        virtual sal_Bool    WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
        virtual void        ObjectReleased();
    };
}
#endif // DBAUI_TABLEROW_EXCHANGE_HXX

<commit_msg>INTEGRATION: CWS dba203c (1.2.110); FILE MERGED 2006/04/13 13:57:17 oj 1.2.110.1: hold TableRow now with a shared_ptr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableRowExchange.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-04 08:43:35 $
 *
 *  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 DBAUI_TABLEROW_EXCHANGE_HXX
#define DBAUI_TABLEROW_EXCHANGE_HXX

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
#include <boost/shared_ptr.hpp>

namespace dbaui
{
    class OTableRow;
    class OTableRowExchange : public TransferableHelper
    {
        ::std::vector< ::boost::shared_ptr<OTableRow> > m_vTableRow;
    public:
        OTableRowExchange(const ::std::vector< ::boost::shared_ptr<OTableRow> >& _rvTableRow);
    protected:
        virtual void        AddSupportedFormats();
        virtual sal_Bool    GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
        virtual sal_Bool    WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
        virtual void        ObjectReleased();
    };
}
#endif // DBAUI_TABLEROW_EXCHANGE_HXX

<|endoftext|>


<commit_before><commit_msg>Fix CNM charm<commit_after><|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
#ifndef _Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_
#define _Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace Stroika {
    namespace Foundation {
        namespace IO {
            namespace Network {

                /*
                 ********************************************************************************
                 ******************************* WaitForSocketIOReady ***************************
                 ********************************************************************************
                 */
                template <typename SOCKET_SUBTYPE>
                WaitForSocketIOReady<SOCKET_SUBTYPE>::WaitForSocketIOReady (const Traversal::Iterable<SOCKET_SUBTYPE>& sockets)
                    : inherited (sockets.Select<Socket::PlatformNativeHandle> ([](const Socket& s) { return s.GetNativeSocket (); }))
                {
                    for (SOCKET_SUBTYPE i : sockets) {
                        fMapping_.Add (i, i.GetNativeSocket ());
                    }
                }
                template <typename SOCKET_SUBTYPE>
                inline Traversal::Iterable<SOCKET_SUBTYPE> WaitForSocketIOReady<SOCKET_SUBTYPE>::Wait (Time::DurationSecondsType waitFor)
                {
                    return fMapping_.InverseMap (inherited::Wait (waitFor));
                }
                template <typename SOCKET_SUBTYPE>
                inline Traversal::Iterable<SOCKET_SUBTYPE> WaitForSocketIOReady<SOCKET_SUBTYPE>::WaitUntil (Time::DurationSecondsType timeoutAt)
                {
                    return fMapping_.InverseMap (inherited::Wait (waitFor));
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_*/
<commit_msg>small fixes to IO::Network::WaitForSocketIOReady<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
#ifndef _Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_
#define _Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace Stroika {
    namespace Foundation {
        namespace IO {
            namespace Network {

                /*
                 ********************************************************************************
                 ********************** IO::Network::WaitForSocketIOReady ***********************
                 ********************************************************************************
                 */
                template <typename SOCKET_SUBTYPE>
                WaitForSocketIOReady<SOCKET_SUBTYPE>::WaitForSocketIOReady (const Traversal::Iterable<SOCKET_SUBTYPE>& sockets)
                    : inherited (sockets.template Select<Socket::PlatformNativeHandle> ([](const Socket& s) { return s.GetNativeSocket (); }))
                {
                    for (SOCKET_SUBTYPE i : sockets) {
                        fMapping_.Add (i, i.GetNativeSocket ());
                    }
                }
                template <typename SOCKET_SUBTYPE>
                inline Traversal::Iterable<SOCKET_SUBTYPE> WaitForSocketIOReady<SOCKET_SUBTYPE>::Wait (Time::DurationSecondsType waitFor)
                {
                    return fMapping_.InverseMap (inherited::Wait (waitFor));
                }
                template <typename SOCKET_SUBTYPE>
                inline Traversal::Iterable<SOCKET_SUBTYPE> WaitForSocketIOReady<SOCKET_SUBTYPE>::WaitUntil (Time::DurationSecondsType timeoutAt)
                {
                    return fMapping_.InverseMap (inherited::WaitUntil (timeoutAt));
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_IO_Network_WaitForSocketIOReady_inl_*/
<|endoftext|>


<commit_before><commit_msg>small fix<commit_after><|endoftext|>


<commit_before><commit_msg>Increase of multiplicity reach for Pb-Pb<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,
 * Applied Mathematics, Norway.
 *
 * Contact information: E-mail: tor.dokken@sintef.no
 * SINTEF ICT, Department of Applied Mathematics,
 * P.O. Box 124 Blindern,
 * 0314 Oslo, Norway.
 *
 * This file is part of GoTools.
 *
 * GoTools is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * GoTools 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with GoTools. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public
 * License, a covered work must retain the producer line in every data
 * file that is created or manipulated using GoTools.
 *
 * Other Usage
 * You can be released from the requirements of the license by purchasing
 * a commercial license. Buying such a license is mandatory as soon as you
 * develop commercial activities involving the GoTools library without
 * disclosing the source code of your own applications.
 *
 * This file may be used in accordance with the terms contained in a
 * written agreement between you and SINTEF ICT.
 */

#define BOOST_TEST_MODULE gotools-core/HermiteApprEvalSurfTest
#include <boost/test/included/unit_test.hpp>

#include <fstream>
#include "GoTools/compositemodel/OffsetSurfaceUtils.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/geometry/Utils.h"

using namespace Go;
using std::vector;
using std::ifstream;
using std::string;

struct Config {
public:
    Config()
    {

        const std::string datadir = "data/"; // Relative to build/gotools-core

        infiles.push_back(datadir + "bounded_surface.g2");
        numloops.push_back(1);

        infiles.push_back(datadir + "test_bounded_sf_2.g2");
        numloops.push_back(1);

        infiles.push_back(datadir + "test_bounded_sf_3.g2");
        numloops.push_back(1);

    }

public:
    ObjectHeader header;
    vector<string> infiles;
    vector<int> numloops;
};

BOOST_AUTO_TEST_CASE(HermiteApprEvalSurfTest)
{

    vector<string> filenames;
    vector<double> offset, epsgeo;

    const std::string data_basedir("../../gotools-data/compositemodel/Offset");

#if 1
    filenames.push_back(data_basedir+"/TopSolid/TopSolid_bump.g2");
    offset.push_back(-3.0e-03);
    epsgeo.push_back(1.0e-05);
#endif

#if 1
    // Self-intersections for offset dist of appr 0.3 and larger.
    filenames.push_back(data_basedir+"/test_bezier.g2");
    offset.push_back(0.1);
    epsgeo.push_back(1.0e-03);
#endif

    for (size_t ki = 0; ki < filenames.size(); ++ki)
    {
        std::cout << "\nTesting offsetSurfaceSet() for file " << filenames[ki] <<
            ", offset: " << offset[ki] << ", epsgeo: " << epsgeo[ki] << std::endl;

        ifstream infile(filenames[ki]);
        if (!(infile.good()))
        {
            BOOST_ERROR("Input file not found or file corrupted!");
            continue;
        }

        vector<shared_ptr<ParamSurface> > sfs;
        while (!infile.eof())
        {
            ObjectHeader header;
            infile >> header;
            if (header.classType() != Class_SplineSurface)
            {
                BOOST_ERROR("Input was not a SplineSurface, not yet supported!");
                continue;
            }

            shared_ptr<ParamSurface> sf(new SplineSurface());
            sf->read(infile);

            sfs.push_back(sf);

            Utils::eatwhite(infile);
        }

        shared_ptr<SplineSurface> offset_sf;
        OffsetSurfaceStatus status = OffsetSurfaceUtils::offsetSurfaceSet(sfs, offset[ki], epsgeo[ki], offset_sf);

        if (offset_sf.get() == NULL)
        {
            BOOST_ERROR("Offset surface was not created.");
            continue;
        }

        if (status == OFFSET_OK)
        {
            MESSAGE("Success!");
        }
        else
        {
            MESSAGE("Failure! Returned status (!= 0): " << status);
            continue;
        }

        // Since we may need to handle self intersections and kinks in the input surface set we are not
        // guaranteed that we are within the offset-dist +/- epsgeo for all points. Assuming that the
        // method is capable of reporting on the status.
        BOOST_CHECK_EQUAL(status, OFFSET_OK);
        if (status != 0)
        {
            continue;
        }
    }
}
<commit_msg>Updated unit test with new datadir location.<commit_after>/*
 * Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,
 * Applied Mathematics, Norway.
 *
 * Contact information: E-mail: tor.dokken@sintef.no
 * SINTEF ICT, Department of Applied Mathematics,
 * P.O. Box 124 Blindern,
 * 0314 Oslo, Norway.
 *
 * This file is part of GoTools.
 *
 * GoTools is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * GoTools 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with GoTools. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public
 * License, a covered work must retain the producer line in every data
 * file that is created or manipulated using GoTools.
 *
 * Other Usage
 * You can be released from the requirements of the license by purchasing
 * a commercial license. Buying such a license is mandatory as soon as you
 * develop commercial activities involving the GoTools library without
 * disclosing the source code of your own applications.
 *
 * This file may be used in accordance with the terms contained in a
 * written agreement between you and SINTEF ICT.
 */

#define BOOST_TEST_MODULE gotools-core/HermiteApprEvalSurfTest
#include <boost/test/included/unit_test.hpp>

#include <fstream>
#include "GoTools/compositemodel/OffsetSurfaceUtils.h"
#include "GoTools/geometry/ObjectHeader.h"
#include "GoTools/geometry/Utils.h"

using namespace Go;
using std::vector;
using std::ifstream;
using std::string;

struct Config {
public:
    Config()
    {

#ifdef GOTOOLS_TEST_PRIVATE_DATA
        const std::string data_basedir("../../gotools-private-data/compositemodel/Offset");
        filenames.push_back(data_basedir+"/TopSolid/TopSolid_bump.g2");
        offset.push_back(-3.0e-03);
        epsgeo.push_back(1.0e-05);

        // Self-intersections for offset dist of appr 0.3 and larger.
        filenames.push_back(data_basedir+"/test_bezier.g2");
        offset.push_back(0.1);
        epsgeo.push_back(1.0e-03);
#endif

    }

public:
    vector<string> filenames;
    vector<double> offset, epsgeo;
};

BOOST_FIXTURE_TEST_CASE(HermiteApprEvalSurfTest, Config)
{

    for (size_t ki = 0; ki < filenames.size(); ++ki)
    {
        std::cout << "\nTesting offsetSurfaceSet() for file " << filenames[ki] <<
            ", offset: " << offset[ki] << ", epsgeo: " << epsgeo[ki] << std::endl;

        ifstream infile(filenames[ki]);
        if (!(infile.good()))
        {
            BOOST_ERROR("Input file not found or file corrupted!");
            continue;
        }

        vector<shared_ptr<ParamSurface> > sfs;
        while (!infile.eof())
        {
            ObjectHeader header;
            infile >> header;
            if (header.classType() != Class_SplineSurface)
            {
                BOOST_ERROR("Input was not a SplineSurface, not yet supported!");
                continue;
            }

            shared_ptr<ParamSurface> sf(new SplineSurface());
            sf->read(infile);

            sfs.push_back(sf);

            Utils::eatwhite(infile);
        }

        shared_ptr<SplineSurface> offset_sf;
        OffsetSurfaceStatus status = OffsetSurfaceUtils::offsetSurfaceSet(sfs, offset[ki], epsgeo[ki], offset_sf);

        if (offset_sf.get() == NULL)
        {
            BOOST_ERROR("Offset surface was not created.");
            continue;
        }

        if (status == OFFSET_OK)
        {
            MESSAGE("Success!");
        }
        else
        {
            MESSAGE("Failure! Returned status (!= 0): " << status);
            continue;
        }

        // Since we may need to handle self intersections and kinks in the input surface set we are not
        // guaranteed that we are within the offset-dist +/- epsgeo for all points. Assuming that the
        // method is capable of reporting on the status.
        BOOST_CHECK_EQUAL(status, OFFSET_OK);
        if (status != 0)
        {
            continue;
        }
    }
}
<|endoftext|>


<commit_before>#include "scripting.hpp"
#include "../Phasor/Version.h"
#include "script-events.h"
#include "PhasorAPI/phasorapi.h"
#include "../Common/FileIO.h"
#include "../Phasor/Globals.h"

#include <array>

namespace scripting {

	std::array<size_t, 3> compatibleVersions = {200, 201, 202};
	static const std::string log_prefix = "   ";

	// only care about its memory address
	const char PhasorScript::thisKey = 0;

	//
	// --------------------------------------------------------------
	//

	PhasorScript& PhasorScript::get(lua_State* L) {
		lua_pushlightuserdata(L, (void *)&thisKey);
		lua_gettable(L, LUA_REGISTRYINDEX);
		PhasorScript* pThis = static_cast<PhasorScript*>(lua_touserdata(L, -1));
		lua_pop(L, 1);
		if (!pThis) luaL_error(L, "cannot find reference to this! (phasor bug)");
		return *pThis;
	}

	void PhasorScript::block(std::string f) {
		blockedFunctions.insert(std::move(f));
	}

	bool PhasorScript::isBlocked(const std::string& f) const {
		return blockedFunctions.find(f) != blockedFunctions.end();
	}

	//
	// --------------------------------------------------------------
	//

	size_t getRequiredVersion(lua::State& state) {
		boost::optional<size_t> required = state.getGlobal<phlua::PhasorPop, size_t>("required_version");
		if (required) return *required;
		if (!state.hasFunction("GetRequiredVersion"))
			throw std::exception("function GetRequiredVersion undefined");

		size_t version;
		phlua::Caller<size_t> c(state);
		std::tie(version) = c.call("GetRequiredVersion", std::make_tuple());
		if (c.hasError())
			throw std::exception("cannot determine required version");

		return version;
	}

	void checkCompatibility(lua::State& state) {
		size_t required = getRequiredVersion(state);
		for (size_t v : compatibleVersions) {
			if (v == required) return;
		}

		throw std::exception("script is not compatible with this version of Phasor");
	}

	//
	// --------------------------------------------------------------
	//

	ScriptHandler::ScriptHandler(std::string scriptDir, COutStream& errStream)
		: scriptDir(std::move(scriptDir)), errStream(errStream)
	{}

	bool ScriptHandler::isLoaded(const std::string& script) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			if ((*itr)->getName() == script) return true;
		}
		return false;
	}

	bool ScriptHandler::loadScript(const std::string& name, bool persistent, std::shared_ptr<PhasorScript>& out)
	{
		if (isLoaded(name)) {
			errStream << name << " is already loaded." << endl;
			return false;
		}

		std::string file = scriptDir + name + ".lua";

		try {
			std::shared_ptr<PhasorScript> script = PhasorScript::create(persistent,
																		file,
																		name,
																		phasorapi::funcTable.begin(),
																		phasorapi::funcTable.end());

			lua::State& state = script->getState();
			checkCompatibility(state);

			if (state.hasFunction("OnScriptLoad")) {
				phlua::Caller<> c(state);
				c.call("OnScriptLoad", std::make_tuple(GetCurrentProcessId(), PHASOR_HALO_BUILDA, persistent));
			}

			// Blacklist any functions that aren't defined
			for (auto itr = events::eventList.begin();
				 itr != events::eventList.end(); ++itr)
			{
				if (!state.hasFunction(itr->c_str()))
					script->block(*itr);
			}

			out = script;

		} catch (std::exception& e) {
			NoFlush _(errStream);
			errStream << L"script '" << name << "' cannot be loaded." <<
				endl << log_prefix << e.what() << endl;
			return false;
		}

		return true;
	}

	bool ScriptHandler::loadScript(const std::string& name, bool persistent)
	{
		std::shared_ptr<PhasorScript> script;
		if (!loadScript(name, persistent, script)) return false;
		scripts.push_back(script);
		return false;
	}

	void ScriptHandler::loadPersistentScripts() {
		std::wstring persistent = WidenString(scriptDir) + L"\\persistent\\*.lua";

		std::list<std::wstring> files;
		NDirectory::FindFiles(persistent, files);

		for (auto itr = files.cbegin(); itr != files.cend(); ++itr) {
			std::wstring script = L"persistent\\" + *itr;
			// remove .lua
			script = script.substr(0, script.size() - 4);
			loadScript(NarrowString(script).c_str(), true);
		}
	}

	void ScriptHandler::unloadScript(PhasorScript& script) {
		lua::State& state = script.getState();
		if (state.hasFunction("OnScriptUnload")) {
			phlua::Caller<> c(state);
			c.call("OnScriptUnload", std::make_tuple());
		}
	}

	bool ScriptHandler::unloadScript(const std::string& script) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ) {
			if ((*itr)->getName() == script) {
				unloadScript(**itr);
				itr = scripts.erase(itr);
				return true;
			}
			++itr;
		}
		return false;
	}

	void ScriptHandler::unloadAllScripts(bool includePersistent) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ) {
			if (includePersistent || !(*itr)->isPersistent()) {
				unloadScript(**itr);
				itr = scripts.erase(itr);
			} else ++itr;
		}
	}

	bool ScriptHandler::reloadScript(const std::string& script)	{
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			if ((*itr)->getName() == script) {
				bool persistent = (*itr)->isPersistent();
				unloadScript(**itr);
				return loadScript(script, persistent, *itr);
			}
		}
		return false;
	}

	void ScriptHandler::reloadAllScripts(bool includePersistent)
	{
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			bool persistent = (*itr)->isPersistent();
			if (includePersistent || !persistent) {
				std::string name = (*itr)->getName();
				unloadScript(**itr);
				loadScript(name, persistent, *itr);
			}
		}
	}

	std::vector<std::string> ScriptHandler::getLoadedScripts() const {
		std::vector<std::string> loaded;
		loaded.reserve(scripts.size());
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr)
			loaded.push_back((*itr)->getName());
		return loaded;
	}

	void ScriptHandler::handleError(PhasorScript& script, const std::string& func,
									const char* what)
	{
		NoFlush _(errStream); // flush once at the end of the func

		errStream << L"Error in '" << script.getName() << L'\'' <<  endl;
		errStream << log_prefix << L"Error: " << what << endl;

		script.block(func);

		errStream << log_prefix << L"Action: Further calls to '" << func <<
				L"' will be ignored." << endl;

		errStream << endl;
	}

}<commit_msg>Spaces instead of tabs<commit_after>#include "scripting.hpp"
#include "../Phasor/Version.h"
#include "script-events.h"
#include "PhasorAPI/phasorapi.h"
#include "../Common/FileIO.h"
#include "../Phasor/Globals.h"

#include <array>

namespace scripting {

	std::array<size_t, 3> compatibleVersions = {200, 201, 202};
	static const std::string log_prefix = "   ";

	// only care about its memory address
	const char PhasorScript::thisKey = 0;

	//
	// --------------------------------------------------------------
	//

	PhasorScript& PhasorScript::get(lua_State* L) {
		lua_pushlightuserdata(L, (void *)&thisKey);
		lua_gettable(L, LUA_REGISTRYINDEX);
		PhasorScript* pThis = static_cast<PhasorScript*>(lua_touserdata(L, -1));
		lua_pop(L, 1);
		if (!pThis) luaL_error(L, "cannot find reference to this! (phasor bug)");
		return *pThis;
	}

	void PhasorScript::block(std::string f) {
		blockedFunctions.insert(std::move(f));
	}

	bool PhasorScript::isBlocked(const std::string& f) const {
		return blockedFunctions.find(f) != blockedFunctions.end();
	}

	//
	// --------------------------------------------------------------
	//

	size_t getRequiredVersion(lua::State& state) {
		boost::optional<size_t> required = state.getGlobal<phlua::PhasorPop, size_t>("required_version");
		if (required) return *required;
		if (!state.hasFunction("GetRequiredVersion"))
			throw std::exception("function GetRequiredVersion undefined");

		size_t version;
		phlua::Caller<size_t> c(state);
		std::tie(version) = c.call("GetRequiredVersion", std::make_tuple());
		if (c.hasError())
			throw std::exception("cannot determine required version");

		return version;
	}

	void checkCompatibility(lua::State& state) {
		size_t required = getRequiredVersion(state);
		for (size_t v : compatibleVersions) {
			if (v == required) return;
		}

		throw std::exception("script is not compatible with this version of Phasor");
	}

	//
	// --------------------------------------------------------------
	//

	ScriptHandler::ScriptHandler(std::string scriptDir, COutStream& errStream)
		: scriptDir(std::move(scriptDir)), errStream(errStream)
	{}

	bool ScriptHandler::isLoaded(const std::string& script) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			if ((*itr)->getName() == script) return true;
		}
		return false;
	}

	bool ScriptHandler::loadScript(const std::string& name, bool persistent, std::shared_ptr<PhasorScript>& out)
	{
		if (isLoaded(name)) {
			errStream << name << " is already loaded." << endl;
			return false;
		}

		std::string file = scriptDir + name + ".lua";

		try {

			std::shared_ptr<PhasorScript> script = PhasorScript::create(persistent,
                                                                        file,
                                                                        name,
                                                                        phasorapi::funcTable.begin(),
                                                                        phasorapi::funcTable.end());

			lua::State& state = script->getState();
			checkCompatibility(state);

			if (state.hasFunction("OnScriptLoad")) {
				phlua::Caller<> c(state);
				c.call("OnScriptLoad", std::make_tuple(GetCurrentProcessId(), PHASOR_HALO_BUILDA, persistent));
			}

			// Blacklist any functions that aren't defined
			for (auto itr = events::eventList.begin();
				 itr != events::eventList.end(); ++itr)
			{
				if (!state.hasFunction(itr->c_str()))
					script->block(*itr);
			}

			out = script;

		} catch (std::exception& e) {
			NoFlush _(errStream);
			errStream << L"script '" << name << "' cannot be loaded." <<
				endl << log_prefix << e.what() << endl;
			return false;
		}

		return true;
	}

	bool ScriptHandler::loadScript(const std::string& name, bool persistent)
	{
		std::shared_ptr<PhasorScript> script;
		if (!loadScript(name, persistent, script)) return false;
		scripts.push_back(script);
		return false;
	}

	void ScriptHandler::loadPersistentScripts() {
		std::wstring persistent = WidenString(scriptDir) + L"\\persistent\\*.lua";

		std::list<std::wstring> files;
		NDirectory::FindFiles(persistent, files);

		for (auto itr = files.cbegin(); itr != files.cend(); ++itr) {
			std::wstring script = L"persistent\\" + *itr;
			// remove .lua
			script = script.substr(0, script.size() - 4);
			loadScript(NarrowString(script).c_str(), true);
		}
	}

	void ScriptHandler::unloadScript(PhasorScript& script) {
		lua::State& state = script.getState();
		if (state.hasFunction("OnScriptUnload")) {
			phlua::Caller<> c(state);
			c.call("OnScriptUnload", std::make_tuple());
		}
	}

	bool ScriptHandler::unloadScript(const std::string& script) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ) {
			if ((*itr)->getName() == script) {
				unloadScript(**itr);
				itr = scripts.erase(itr);
				return true;
			}
			++itr;
		}
		return false;
	}

	void ScriptHandler::unloadAllScripts(bool includePersistent) {
		for (auto itr = scripts.begin(); itr != scripts.end(); ) {
			if (includePersistent || !(*itr)->isPersistent()) {
				unloadScript(**itr);
				itr = scripts.erase(itr);
			} else ++itr;
		}
	}

	bool ScriptHandler::reloadScript(const std::string& script)	{
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			if ((*itr)->getName() == script) {
				bool persistent = (*itr)->isPersistent();
				unloadScript(**itr);
				return loadScript(script, persistent, *itr);
			}
		}
		return false;
	}

	void ScriptHandler::reloadAllScripts(bool includePersistent)
	{
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr) {
			bool persistent = (*itr)->isPersistent();
			if (includePersistent || !persistent) {
				std::string name = (*itr)->getName();
				unloadScript(**itr);
				loadScript(name, persistent, *itr);
			}
		}
	}

	std::vector<std::string> ScriptHandler::getLoadedScripts() const {
		std::vector<std::string> loaded;
		loaded.reserve(scripts.size());
		for (auto itr = scripts.begin(); itr != scripts.end(); ++itr)
			loaded.push_back((*itr)->getName());
		return loaded;
	}

	void ScriptHandler::handleError(PhasorScript& script, const std::string& func,
									const char* what)
	{
		NoFlush _(errStream); // flush once at the end of the func

		errStream << L"Error in '" << script.getName() << L'\'' <<  endl;
		errStream << log_prefix << L"Error: " << what << endl;

		script.block(func);

		errStream << log_prefix << L"Action: Further calls to '" << func <<
				L"' will be ignored." << endl;

		errStream << endl;
	}

}<|endoftext|>