<commit_before>#include <iostream>

//odd - multiply by 3, add 1
//even - divide by 2
//check number of times it takes to get to 1
//andrew silver

/*
Collatz Conjecture - Start with a number n > 1. Find the number of steps it takes to reach one using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. [EpicDavi (Python)][rramchand (Java)]
 */

//updates November 2013 - next implement using strings to allow for bigger numbers. this will be difficult because need to come up with a way to divide each "number" in a string digit by digit, same with multiplication

//idea - what if using multiple strings, once a number gets to a certain length, make another string for it? could also work on the palindromeconjecture.cpp

unsigned int divide(unsigned const int n,unsigned const int counter){

  if(n &0x1){ //if odd
    if(n == 1){
      return counter;
    }
         return divide (3*n + 1, counter+ 1); //recall function
  }

  else{ //if even
    return divide (n/2, counter + 1);
  }

}

int main(){

  unsigned int n = 1;
  while(n != 0){
  std::cout << "Enter a number greater than 0 to determine the number of steps to reach 1. Enter 0 to quit." << std::endl;
  std::cin >> n;
  unsigned const int counter = 0;
  std::cout << divide(n, counter) << std::endl;
}

  return 0;
}
<commit_msg>added an if check so the program does not evaluate at n = 0, it caused a seg fault<commit_after>#include <iostream>

//odd - multiply by 3, add 1
//even - divide by 2
//check number of times it takes to get to 1
//andrew silver

/*
Collatz Conjecture - Start with a number n > 1. Find the number of steps it takes to reach one using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. [EpicDavi (Python)][rramchand (Java)]
 */

//updates November 2013 - next implement using strings to allow for bigger numbers. this will be difficult because need to come up with a way to divide each "number" in a string digit by digit, same with multiplication

//idea - what if using multiple strings, once a number gets to a certain length, make another string for it? could also work on the palindromeconjecture.cpp

unsigned int divide(unsigned const int n,unsigned const int counter){

  if(n &0x1){ //if odd
    if(n == 1){
      return counter;
    }
         return divide (3*n + 1, counter+ 1); //recall function
  }

  else{ //if even
    return divide (n/2, counter + 1);
  }

}

int main(){

  unsigned int n = 1;
  while(n != 0){
  std::cout << "Enter a number greater than 0 to determine the number of steps to reach 1. Enter 0 to quit." << std::endl;
  std::cin >> n;
  if(n > 0){
  unsigned const int counter = 0;
  std::cout << divide(n, counter) << std::endl;
  }
}

  return 0;
}
<|endoftext|>


<commit_before>#include <math.h>
#include "../include/Mixer3D.h"
#include "../include/World.h"
#include "../include/fft.h"
#include "../include/mit_hrtf_lib.h"

Mixer3D::Mixer3D(int bufSize, int smpRate, int bitD, World *w) :
myWorld(w), bufferSize(bufSize), sampleRate(smpRate), bitDepth(bitD), player(myWorld->getPlayer())
{
    inputAO = new complex[2*bufferSize];
    overlapInput = new complex[2 * bufferSize];
    fInput = new complex[2 * bufferSize];
    fFilter = new complex[2 * bufferSize];

    azimuths = new int[World::MAX_OBJ];
    elevations = new int[World::MAX_OBJ];
    prevAzimuths = new int[World::MAX_OBJ];
    prevElevations = new int[World::MAX_OBJ];

    updateAngles(); // initialize azimuths and elevations

    outputLeft = new complex*[World::MAX_OBJ];
    outputRight = new complex*[World::MAX_OBJ];
    overlapLeft = new complex*[World::MAX_OBJ];
    overlapRight = new complex*[World::MAX_OBJ];

    leftFilter = new short[2 * bufferSize];
    rightFilter = new short[2 * bufferSize];
    complexLeftFilter = new complex*[World::MAX_OBJ];
    complexRightFilter = new complex*[World::MAX_OBJ];

    for (int i = 0; i < World::MAX_OBJ; i++)
    {
        // TODO: Should we initialize filter values?
        overlapLeft[i] = new complex[bufferSize];
        overlapRight[i] = new complex[bufferSize];
        outputLeft[i] = new complex[2*bufferSize];
        outputRight[i] = new complex[2*bufferSize];
        complexLeftFilter[i] = new complex[2*bufferSize];
        complexRightFilter[i] = new complex[2*bufferSize];

        // TODO: Is there a more efficient way to know which objects
        // have changed position relative to the player?
        // Store some state each time an AudioObject is moved?
        // What if the player moves in the same direction?
        prevAzimuths[i] = INVALID_ANGLE;
        prevElevations[i] = INVALID_ANGLE;
    }
}

Mixer3D::~Mixer3D()
{
    delete [] inputAO;
    delete [] outputLeft;
    delete [] outputLeft;
    delete [] leftFilter;
    delete [] rightFilter;
    delete [] complexLeftFilter;
    delete [] complexRightFilter;
    delete [] overlapLeft;
    delete [] overlapRight;
    delete [] overlapInput;
    delete [] prevAzimuths;
    delete [] prevElevations;
    delete [] azimuths;
    delete [] elevations;
}

void Mixer3D::updateAngles() {
    AudioObj* iAudioObj;
    for (int i = 0; i < myWorld->getNumObj(); i++) {
        iAudioObj = myWorld->getAudioObj(i);
        azimuths[i] = player.computeAzimuth(iAudioObj);
        elevations[i] = player.computeElevation(iAudioObj);
    }
}

bool Mixer3D::isPowerOfTwo(int x) {
    return !(x == 0) && !(x & (x - 1));
}

int Mixer3D::loadHRTF(int* pAzimuth, int* pElevation, unsigned int samplerate, unsigned int diffused, complex *&leftFilterIn, complex *&rightFilterIn)
{
    int size = mit_hrtf_get(pAzimuth, pElevation, samplerate, diffused, leftFilter, rightFilter);

    if (size == 0) {
        // TODO: Throw MIT HRTF filter does not exist exception
    }
    for (int i = 0; i < size; i++)
    {
        leftFilterIn[i] = (double)(leftFilter[i]);
        rightFilterIn[i] = (double)(rightFilter[i]);
    }

    return size;
}
void Mixer3D::convolution(complex *input, complex *filter, complex *output, long nSig, long nFil, long nFFT) {

	if (input == NULL || filter == NULL) {
		throw invalid_argument("Input and Filter must be non-NULL.");
	}

	if (!isPowerOfTwo(nFFT) || nFFT < nSig || nFFT < nFil) {
        throw invalid_argument("NFFT must be a power of two, bigger than the signal length, and bigger than the filter length.");
	}

	// Perform FFT on both input and filter.
    // TODO: "Streamline" CFFT class?
	CFFT::Forward(input, fInput, (unsigned int)nFFT);
	CFFT::Forward(filter, fFilter, (unsigned int)nFFT);

	for (int i = 0; i < nFFT; i++) {
		output[i] = fInput[i] * fFilter[i];
    }
	CFFT::Inverse(output, (unsigned int)nFFT);
}

void Mixer3D::stereoConvolution(complex *input, complex *leftFilter, complex *rightFilter, complex *leftOutput, complex *rightOutput, long nSIG, long nFIL, long nFFT)
{
    // TODO: Modify parameter name, input is a data member
    convolution(input, leftFilter, leftOutput, nSIG, nFIL, nFFT);
    convolution(input, rightFilter, rightOutput, nSIG, nFIL, nFFT);
}

void Mixer3D::performMix(short *ioDataLeft, short *ioDataRight)
{
    //Zero the output arrays.
    for(int i = 0; i < bufferSize; i++)
    {
       ioDataLeft[i] = 0;
       ioDataRight[i] = 0;
    }

    //Iterate through all audio objects, obtain input data and calculate resulting audio data for each object.
    // TODO: Possible bug? Cuts short if one audioObj is inactive?
    AudioObj* iAudioObj;
    float iVolume, iDistance, iAmplitudeFactor;
    for (int i = 0; i < myWorld->getNumObj() && myWorld->getAudioObj(i)->isActive(); i++) {
        // dynamically calculate the Azimuth and Elevation between every object and the player
        updateAngles();
        iAudioObj = myWorld->getAudioObj(i);

        // loading in input data for the iteration accordingly
        if (!(iAudioObj->fillAudioData(inputAO, bufferSize))) {
            continue;
        }

        // scale volume according to distance of object from player
        // TODO: Is linear decay by distance realistic?
        iVolume = iAudioObj->getVolume();
        iDistance = player.computeDistanceFrom(iAudioObj) ;
        iAmplitudeFactor = iVolume / iDistance;

        for(int j = 0; j < bufferSize * 2; j++) {
            if ( j >= bufferSize ) {
                // zero pad
                inputAO[j] = 0;
            } else {
                inputAO[j] *= iAmplitudeFactor;
            }
        }

        if (azimuths[i] != prevAzimuths[i] ||
           elevations[i] != prevElevations[i]) {
            // object location relative to player has changed, so fetch a new filter
            filterLength = loadHRTF(&azimuths[i], &elevations[i], sampleRate, 1, complexLeftFilter[i], complexRightFilter[i]);

            // zero pad
            for (int j = filterLength; j < 2 * bufferSize; j++) {
                complexLeftFilter[i][j] = 0;
                complexRightFilter[i][j] = 0;
            }

            if (azimuths[i] < 0) {
                   azimuths[i] = -azimuths[i];
            }

            //Since the filter changed, we perform a convolution on the old input with the new filter and pull out its tail.
            stereoConvolution(overlapInput, complexLeftFilter[i], complexRightFilter[i], outputLeft[i], outputRight[i], bufferSize, filterLength, 2 * bufferSize);

            // update the overlap part for the next iteration
            for (int j = 0; j < bufferSize; j++) {
                    overlapLeft[i][j] = outputLeft[i][j + bufferSize];
                    overlapRight[i][j] = outputRight[i][j + bufferSize];
            }
        }

        //Perform the convolution of the current input and current filter.
        stereoConvolution(inputAO, complexLeftFilter[i], complexRightFilter[i], outputLeft[i], outputRight[i], bufferSize, filterLength, 2 * bufferSize);

        for (int j = 0; j < bufferSize; j++) {
            ioDataLeft[j] +=  (short((outputLeft[i][j].re())/2 + (overlapLeft[i][j].re())/2))/myWorld->getNumObj();
            ioDataRight[j] += (short((outputRight[i][j].re())/2 + (overlapRight[i][j].re())/2))/myWorld->getNumObj();
        }

        //Output the data to the output arrays in short integer format. In addition to pushing the output of the main
        //convolution, we also need to add the overlapped tail of the last output and divide by 2. Finally, we need
        //to divide by the number of audio objects to ensure no clipping.
        for (int j = 0; j < bufferSize; j++)
        {
            ioDataLeft[j]  += (short)( (outputLeft[i][j].re() + overlapLeft[i][j].re()) / 2*myWorld->getNumObj() );
            ioDataRight[j] += (short)( (outputRight[i][j].re() + overlapRight[i][j].re()) / 2*myWorld->getNumObj() );
        }

        //Updating the overlapInput for the next iteration for the correpsonding obejct
        for (int j = 0; j < bufferSize * 2; j++) {
            if (j >= bufferSize) {
                overlapInput[j] = 0;
            } else {
                overlapInput[j] = inputAO[j];
            }
        }

        // TODO: If the filter has been changed, didn't we already do this?
        //Updating the default overlap information for the next iteration if the filter won't be changed
        for (int j = 0 ; j < bufferSize; j++) {
            overlapLeft[i][j] = outputLeft[i][j + bufferSize];
            overlapRight[i][j] = outputRight[i][j + bufferSize];
        }

        //storing the Azimuth value in this iteration for the comparison for the next iteration so that
        //we can know that whether the filter needs to be changed in the next iteration.
        prevAzimuths[i] = azimuths[i];
        prevElevations[i] = elevations[i];
    }
}
<commit_msg>reordered Mixer3D delete calls, deleted 2D arrays properly<commit_after>#include <math.h>
#include "../include/Mixer3D.h"
#include "../include/World.h"
#include "../include/fft.h"
#include "../include/mit_hrtf_lib.h"

Mixer3D::Mixer3D(int bufSize, int smpRate, int bitD, World *w) :
myWorld(w), bufferSize(bufSize), sampleRate(smpRate), bitDepth(bitD), player(myWorld->getPlayer())
{
    inputAO = new complex[2*bufferSize];
    overlapInput = new complex[2 * bufferSize];
    fInput = new complex[2 * bufferSize];
    fFilter = new complex[2 * bufferSize];

    azimuths = new int[World::MAX_OBJ];
    elevations = new int[World::MAX_OBJ];
    prevAzimuths = new int[World::MAX_OBJ];
    prevElevations = new int[World::MAX_OBJ];

    updateAngles(); // initialize azimuths and elevations

    outputLeft = new complex*[World::MAX_OBJ];
    outputRight = new complex*[World::MAX_OBJ];
    overlapLeft = new complex*[World::MAX_OBJ];
    overlapRight = new complex*[World::MAX_OBJ];

    leftFilter = new short[2 * bufferSize];
    rightFilter = new short[2 * bufferSize];
    complexLeftFilter = new complex*[World::MAX_OBJ];
    complexRightFilter = new complex*[World::MAX_OBJ];

    for (int i = 0; i < World::MAX_OBJ; i++)
    {
        // TODO: Should we initialize filter values?
        overlapLeft[i] = new complex[bufferSize];
        overlapRight[i] = new complex[bufferSize];
        outputLeft[i] = new complex[2*bufferSize];
        outputRight[i] = new complex[2*bufferSize];
        complexLeftFilter[i] = new complex[2*bufferSize];
        complexRightFilter[i] = new complex[2*bufferSize];

        // TODO: Is there a more efficient way to know which objects
        // have changed position relative to the player?
        // Store some state each time an AudioObject is moved?
        // What if the player moves in the same direction?
        prevAzimuths[i] = INVALID_ANGLE;
        prevElevations[i] = INVALID_ANGLE;
    }
}

Mixer3D::~Mixer3D()
{
    delete [] inputAO;
    delete [] overlapInput;
    delete [] fInput;
    delete [] fFilter;
    delete [] azimuths;
    delete [] elevations;
    delete [] prevAzimuths;
    delete [] prevElevations;

    delete [] leftFilter;
    delete [] rightFilter;

    for (int i=0; i < World::MAX_OBJ; i++) {
        delete [] overlapLeft[i];
        delete [] overlapRight[i];
        delete [] outputLeft[i];
        delete [] outputRight[i];
        delete [] complexLeftFilter[i];
        delete [] complexRightFilter[i];
    }

    delete [] overlapLeft;
    delete [] overlapRight;
    delete [] outputLeft;
    delete [] outputRight;
    delete [] complexLeftFilter;
    delete [] complexRightFilter;
}

void Mixer3D::updateAngles() {
    AudioObj* iAudioObj;
    for (int i = 0; i < myWorld->getNumObj(); i++) {
        iAudioObj = myWorld->getAudioObj(i);
        azimuths[i] = player.computeAzimuth(iAudioObj);
        elevations[i] = player.computeElevation(iAudioObj);
    }
}

bool Mixer3D::isPowerOfTwo(int x) {
    return !(x == 0) && !(x & (x - 1));
}

int Mixer3D::loadHRTF(int* pAzimuth, int* pElevation, unsigned int samplerate, unsigned int diffused, complex *&leftFilterIn, complex *&rightFilterIn)
{
    int size = mit_hrtf_get(pAzimuth, pElevation, samplerate, diffused, leftFilter, rightFilter);

    if (size == 0) {
        // TODO: Throw MIT HRTF filter does not exist exception
    }
    for (int i = 0; i < size; i++)
    {
        leftFilterIn[i] = (double)(leftFilter[i]);
        rightFilterIn[i] = (double)(rightFilter[i]);
    }

    return size;
}
void Mixer3D::convolution(complex *input, complex *filter, complex *output, long nSig, long nFil, long nFFT) {

	if (input == NULL || filter == NULL) {
		throw invalid_argument("Input and Filter must be non-NULL.");
	}

	if (!isPowerOfTwo(nFFT) || nFFT < nSig || nFFT < nFil) {
        throw invalid_argument("NFFT must be a power of two, bigger than the signal length, and bigger than the filter length.");
	}

	// Perform FFT on both input and filter.
    // TODO: "Streamline" CFFT class?
	CFFT::Forward(input, fInput, (unsigned int)nFFT);
	CFFT::Forward(filter, fFilter, (unsigned int)nFFT);

	for (int i = 0; i < nFFT; i++) {
		output[i] = fInput[i] * fFilter[i];
    }
	CFFT::Inverse(output, (unsigned int)nFFT);
}

void Mixer3D::stereoConvolution(complex *input, complex *leftFilter, complex *rightFilter, complex *leftOutput, complex *rightOutput, long nSIG, long nFIL, long nFFT)
{
    // TODO: Modify parameter name, input is a data member
    convolution(input, leftFilter, leftOutput, nSIG, nFIL, nFFT);
    convolution(input, rightFilter, rightOutput, nSIG, nFIL, nFFT);
}

void Mixer3D::performMix(short *ioDataLeft, short *ioDataRight)
{
    //Zero the output arrays.
    for(int i = 0; i < bufferSize; i++)
    {
       ioDataLeft[i] = 0;
       ioDataRight[i] = 0;
    }

    //Iterate through all audio objects, obtain input data and calculate resulting audio data for each object.
    // TODO: Possible bug? Cuts short if one audioObj is inactive?
    AudioObj* iAudioObj;
    float iVolume, iDistance, iAmplitudeFactor;
    for (int i = 0; i < myWorld->getNumObj() && myWorld->getAudioObj(i)->isActive(); i++) {
        // dynamically calculate the Azimuth and Elevation between every object and the player
        updateAngles();
        iAudioObj = myWorld->getAudioObj(i);

        // loading in input data for the iteration accordingly
        if (!(iAudioObj->fillAudioData(inputAO, bufferSize))) {
            continue;
        }

        // scale volume according to distance of object from player
        // TODO: Is linear decay by distance realistic?
        iVolume = iAudioObj->getVolume();
        iDistance = player.computeDistanceFrom(iAudioObj) ;
        iAmplitudeFactor = iVolume / iDistance;

        for(int j = 0; j < bufferSize * 2; j++) {
            if ( j >= bufferSize ) {
                // zero pad
                inputAO[j] = 0;
            } else {
                inputAO[j] *= iAmplitudeFactor;
            }
        }

        if (azimuths[i] != prevAzimuths[i] ||
           elevations[i] != prevElevations[i]) {
            // object location relative to player has changed, so fetch a new filter
            filterLength = loadHRTF(&azimuths[i], &elevations[i], sampleRate, 1, complexLeftFilter[i], complexRightFilter[i]);

            // zero pad
            for (int j = filterLength; j < 2 * bufferSize; j++) {
                complexLeftFilter[i][j] = 0;
                complexRightFilter[i][j] = 0;
            }

            if (azimuths[i] < 0) {
                   azimuths[i] = -azimuths[i];
            }

            //Since the filter changed, we perform a convolution on the old input with the new filter and pull out its tail.
            stereoConvolution(overlapInput, complexLeftFilter[i], complexRightFilter[i], outputLeft[i], outputRight[i], bufferSize, filterLength, 2 * bufferSize);

            // update the overlap part for the next iteration
            for (int j = 0; j < bufferSize; j++) {
                    overlapLeft[i][j] = outputLeft[i][j + bufferSize];
                    overlapRight[i][j] = outputRight[i][j + bufferSize];
            }
        }

        //Perform the convolution of the current input and current filter.
        stereoConvolution(inputAO, complexLeftFilter[i], complexRightFilter[i], outputLeft[i], outputRight[i], bufferSize, filterLength, 2 * bufferSize);

        for (int j = 0; j < bufferSize; j++) {
            ioDataLeft[j] +=  (short((outputLeft[i][j].re())/2 + (overlapLeft[i][j].re())/2))/myWorld->getNumObj();
            ioDataRight[j] += (short((outputRight[i][j].re())/2 + (overlapRight[i][j].re())/2))/myWorld->getNumObj();
        }

        //Output the data to the output arrays in short integer format. In addition to pushing the output of the main
        //convolution, we also need to add the overlapped tail of the last output and divide by 2. Finally, we need
        //to divide by the number of audio objects to ensure no clipping.
        for (int j = 0; j < bufferSize; j++)
        {
            ioDataLeft[j]  += (short)( (outputLeft[i][j].re() + overlapLeft[i][j].re()) / 2*myWorld->getNumObj() );
            ioDataRight[j] += (short)( (outputRight[i][j].re() + overlapRight[i][j].re()) / 2*myWorld->getNumObj() );
        }

        //Updating the overlapInput for the next iteration for the correpsonding obejct
        for (int j = 0; j < bufferSize * 2; j++) {
            if (j >= bufferSize) {
                overlapInput[j] = 0;
            } else {
                overlapInput[j] = inputAO[j];
            }
        }

        // TODO: If the filter has been changed, didn't we already do this?
        //Updating the default overlap information for the next iteration if the filter won't be changed
        for (int j = 0 ; j < bufferSize; j++) {
            overlapLeft[i][j] = outputLeft[i][j + bufferSize];
            overlapRight[i][j] = outputRight[i][j + bufferSize];
        }

        //storing the Azimuth value in this iteration for the comparison for the next iteration so that
        //we can know that whether the filter needs to be changed in the next iteration.
        prevAzimuths[i] = azimuths[i];
        prevElevations[i] = elevations[i];
    }
}
<|endoftext|>


<commit_before><commit_msg>gtk3: add <cstddef> to vcl/inc/vcl/sysdata.hxx, it seems that g++ 4.6.1 doesn't like to have 'NULL' in plan C++ without this include<commit_after><|endoftext|>


<commit_before>/*
 *
 *                                   C R I S S C R O S S
 *                          A multi purpose cross platform library.
 *                              formerly Codename "Technetium"
 *                             project started August 14, 2006
 *
 * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net> and Rudolf Olah <omouse@gmail.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list
 *       of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this
 *       list of conditions and the following disclaimer in the documentation and/or other
 *       materials provided with the distribution.
 *     * Neither the name of Uplink Laboratories nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without specific
 *       prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "universal_include.h"

#include "core_debug.h"
#include "core_io.h"
#include "core_system.h"

CoreIO::CoreIO ( FILE * _fileBuffer ):
m_lineEnding ( NULL ),
m_fileBuffer ( _fileBuffer ), m_ioMutex ( new CoreMutex (  ) )
{
#if defined ( TARGET_OS_WINDOWS )
	SetLineEndings ( CRLF );
#elif defined ( TARGET_OS_LINUX ) || defined ( TARGET_OS_MACOSX )
	SetLineEndings ( CR );
#else
#	error You are not using a supported OS.
#endif
}

CoreIO::~CoreIO (  )
{
	delete[]m_lineEnding;
	m_lineEnding = NULL;
	delete m_ioMutex;
	m_ioMutex = NULL;
}

bool
CoreIO::EndOfFile (  )
{
	CoreAssert ( this );

	if ( !m_fileBuffer )
		return true;
	return ( feof ( m_fileBuffer ) != 0 );
}

void
CoreIO::Flush (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fflush ( m_fileBuffer );
	m_ioMutex->Unlock (  );
}

int
CoreIO::Forward ( int _position )
{
	CoreAssert ( this );
	int res = Seek ( _position, SEEK_CUR );
	return ( res == 0 );
}

unsigned long
CoreIO::Length (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fpos_t lastpos;
	fgetpos ( m_fileBuffer, &lastpos );
	fseek ( m_fileBuffer, 0, SEEK_END );
	fpos_t endpos;
	fgetpos ( m_fileBuffer, &endpos );
	fsetpos ( m_fileBuffer, &lastpos );
	m_ioMutex->Unlock (  );
#if defined (TARGET_OS_WINDOWS) || defined (TARGET_OS_MACOSX) || defined (TARGET_OS_FREEBSD)
	return ( unsigned long ) endpos;
#elif defined (TARGET_OS_LINUX)
	return ( unsigned long ) endpos.__pos;
#endif
}

char
CoreIO::Read (  )
{
	CoreAssert ( this );

	char retval;

	m_ioMutex->Lock (  );
	retval = ( char ) fgetc ( m_fileBuffer );
	m_ioMutex->Unlock (  );
	return retval;
}

size_t
CoreIO::Read ( char *_buffer, int _bufferLength, int _bufferIndex,
			   int _count )
{
	CoreAssert ( this );

	size_t retval;

	CoreAssert ( _buffer != NULL );
	CoreAssert ( _bufferLength - _bufferIndex < _count );
	CoreAssert ( _bufferIndex > 0 );
	CoreAssert ( _count > 0 );
	m_ioMutex->Lock (  );
	retval = fread ( &_buffer[_bufferIndex], 1, _count, m_fileBuffer );
	m_ioMutex->Unlock (  );
	return retval;
}

const char *
CoreIO::ReadLine (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	char c = getc ( m_fileBuffer );

	if ( c == EOF )
		return NULL;

	static std::string buffer;

	buffer = "";

	while ( c != EOF && c != '\n' )
	{
		buffer += c;
		c = getc ( m_fileBuffer );
	}

	size_t len = buffer.length (  );

	if ( len && buffer[len - 1] == '\r' )
		buffer.resize ( len - 1 );

	m_ioMutex->Unlock (  );
	return buffer.c_str (  );
}

int
CoreIO::Seek ( int _position, int _origin )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	int res = fseek ( m_fileBuffer, _position, _origin );

	m_ioMutex->Unlock (  );
	return res;
}

int
CoreIO::Seek ( int _position )
{
	CoreAssert ( this );

	int res = Seek ( _position, SEEK_SET );

	return ( res == 0 );
}

void
CoreIO::SetLineEndings ( LineEndingType _ending )
{
	CoreAssert ( this );

	delete [] m_lineEnding;
	switch ( _ending )
	{
	case CR:
		m_lineEnding = new char[2];
		sprintf ( m_lineEnding, "\r" );
		break;
	case LF:
		m_lineEnding = new char[2];
		sprintf ( m_lineEnding, "\n" );
		break;
	case CRLF:
		m_lineEnding = new char[3];
		sprintf ( m_lineEnding, "\r\n" );
		break;
	default:
		CoreAssert ( 0 );
	}
}

void
CoreIO::WriteLine ( const char *_format, ... )
{
	CoreAssert ( this );

	if ( _format == NULL )
		return;

	m_ioMutex->Lock (  );

	va_list args;

	va_start ( args, _format );

	// Print out the string
	vfprintf ( m_fileBuffer, _format, args );
	fprintf ( m_fileBuffer, m_lineEnding );

	va_end ( args );

	m_ioMutex->Unlock (  );

}

void
CoreIO::WriteLine (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fprintf ( m_fileBuffer, m_lineEnding );
	m_ioMutex->Unlock (  );
}

void
CoreIO::Write ( const char *_format, ... )
{
	CoreAssert ( this );

	if ( _format == NULL )
		return;
	m_ioMutex->Lock (  );

	va_list args;

	va_start ( args, _format );

	// Print out the string
	vfprintf ( m_fileBuffer, _format, args );

	va_end ( args );
	m_ioMutex->Unlock (  );
}
<commit_msg>Another line ending fix for UNIX.<commit_after>/*
 *
 *                                   C R I S S C R O S S
 *                          A multi purpose cross platform library.
 *                              formerly Codename "Technetium"
 *                             project started August 14, 2006
 *
 * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net> and Rudolf Olah <omouse@gmail.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list
 *       of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this
 *       list of conditions and the following disclaimer in the documentation and/or other
 *       materials provided with the distribution.
 *     * Neither the name of Uplink Laboratories nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without specific
 *       prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "universal_include.h"

#include "core_debug.h"
#include "core_io.h"
#include "core_system.h"

CoreIO::CoreIO ( FILE * _fileBuffer ):
m_lineEnding ( NULL ),
m_fileBuffer ( _fileBuffer ), m_ioMutex ( new CoreMutex (  ) )
{
#if defined ( TARGET_OS_WINDOWS )
	SetLineEndings ( CRLF );
#elif defined ( TARGET_OS_LINUX ) || defined ( TARGET_OS_MACOSX )
	SetLineEndings ( LF );
#else
#	error You are not using a supported OS.
#endif
}

CoreIO::~CoreIO (  )
{
	delete[]m_lineEnding;
	m_lineEnding = NULL;
	delete m_ioMutex;
	m_ioMutex = NULL;
}

bool
CoreIO::EndOfFile (  )
{
	CoreAssert ( this );

	if ( !m_fileBuffer )
		return true;
	return ( feof ( m_fileBuffer ) != 0 );
}

void
CoreIO::Flush (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fflush ( m_fileBuffer );
	m_ioMutex->Unlock (  );
}

int
CoreIO::Forward ( int _position )
{
	CoreAssert ( this );
	int res = Seek ( _position, SEEK_CUR );
	return ( res == 0 );
}

unsigned long
CoreIO::Length (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fpos_t lastpos;
	fgetpos ( m_fileBuffer, &lastpos );
	fseek ( m_fileBuffer, 0, SEEK_END );
	fpos_t endpos;
	fgetpos ( m_fileBuffer, &endpos );
	fsetpos ( m_fileBuffer, &lastpos );
	m_ioMutex->Unlock (  );
#if defined (TARGET_OS_WINDOWS) || defined (TARGET_OS_MACOSX) || defined (TARGET_OS_FREEBSD)
	return ( unsigned long ) endpos;
#elif defined (TARGET_OS_LINUX)
	return ( unsigned long ) endpos.__pos;
#endif
}

char
CoreIO::Read (  )
{
	CoreAssert ( this );

	char retval;

	m_ioMutex->Lock (  );
	retval = ( char ) fgetc ( m_fileBuffer );
	m_ioMutex->Unlock (  );
	return retval;
}

size_t
CoreIO::Read ( char *_buffer, int _bufferLength, int _bufferIndex,
			   int _count )
{
	CoreAssert ( this );

	size_t retval;

	CoreAssert ( _buffer != NULL );
	CoreAssert ( _bufferLength - _bufferIndex < _count );
	CoreAssert ( _bufferIndex > 0 );
	CoreAssert ( _count > 0 );
	m_ioMutex->Lock (  );
	retval = fread ( &_buffer[_bufferIndex], 1, _count, m_fileBuffer );
	m_ioMutex->Unlock (  );
	return retval;
}

const char *
CoreIO::ReadLine (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	char c = getc ( m_fileBuffer );

	if ( c == EOF )
		return NULL;

	static std::string buffer;

	buffer = "";

	while ( c != EOF && c != '\n' )
	{
		buffer += c;
		c = getc ( m_fileBuffer );
	}

	size_t len = buffer.length (  );

	if ( len && buffer[len - 1] == '\r' )
		buffer.resize ( len - 1 );

	m_ioMutex->Unlock (  );
	return buffer.c_str (  );
}

int
CoreIO::Seek ( int _position, int _origin )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	int res = fseek ( m_fileBuffer, _position, _origin );

	m_ioMutex->Unlock (  );
	return res;
}

int
CoreIO::Seek ( int _position )
{
	CoreAssert ( this );

	int res = Seek ( _position, SEEK_SET );

	return ( res == 0 );
}

void
CoreIO::SetLineEndings ( LineEndingType _ending )
{
	CoreAssert ( this );

	delete [] m_lineEnding;
	switch ( _ending )
	{
	case CR:
		m_lineEnding = new char[2];
		sprintf ( m_lineEnding, "\r" );
		break;
	case LF:
		m_lineEnding = new char[2];
		sprintf ( m_lineEnding, "\n" );
		break;
	case CRLF:
		m_lineEnding = new char[3];
		sprintf ( m_lineEnding, "\r\n" );
		break;
	default:
		CoreAssert ( 0 );
	}
}

void
CoreIO::WriteLine ( const char *_format, ... )
{
	CoreAssert ( this );

	if ( _format == NULL )
		return;

	m_ioMutex->Lock (  );

	va_list args;

	va_start ( args, _format );

	// Print out the string
	vfprintf ( m_fileBuffer, _format, args );
	fprintf ( m_fileBuffer, m_lineEnding );

	va_end ( args );

	m_ioMutex->Unlock (  );

}

void
CoreIO::WriteLine (  )
{
	CoreAssert ( this );

	m_ioMutex->Lock (  );
	fprintf ( m_fileBuffer, m_lineEnding );
	m_ioMutex->Unlock (  );
}

void
CoreIO::Write ( const char *_format, ... )
{
	CoreAssert ( this );

	if ( _format == NULL )
		return;
	m_ioMutex->Lock (  );

	va_list args;

	va_start ( args, _format );

	// Print out the string
	vfprintf ( m_fileBuffer, _format, args );

	va_end ( args );
	m_ioMutex->Unlock (  );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: kdedata.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2005-04-08 16:17:04 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Jan Holesovsky <kendy@artax.karlin.mff.cuni.cz>
 *                  Michael Meeks <michael@ximian.com>
 *
 ************************************************************************/

#define _SV_SALDATA_CXX

#define Region QtXRegion
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qpaintdevice.h>
#undef Region

#include <unistd.h>
#include <fcntl.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <poll.h>
#ifdef FREEBSD
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#endif

#ifndef _VCL_KDEDATA_HXX
#include <plugins/kde/kdedata.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#include <osl/module.h>

#include <tools/debug.hxx>

#ifndef _SAL_I18N_INPUTMETHOD_HXX
#include "i18n_im.hxx"
#endif
#ifndef _SAL_I18N_XKBDEXTENSION_HXX
#include "i18n_xkb.hxx"
#endif

#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif

/***************************************************************************
 * class KDEXLib                                                           *
 ***************************************************************************/

class KDEXLib : public SalXLib
{
public:
    KDEXLib() : SalXLib() {}
    virtual ~KDEXLib() {}
    virtual void Init();
};

void KDEXLib::Init()
{
    SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
    pInputMethod->SetLocale();
    XrmInitialize();

    KAboutData *kAboutData = new KAboutData( "OpenOffice.org",
            I18N_NOOP( "OpenOffice.org" ),
            "1.1.0",
            I18N_NOOP( "OpenOffice.org with KDE Native Widget Support." ),
            KAboutData::License_LGPL,
            "(c) 2003, 2004 Novell, Inc",
            I18N_NOOP( "OpenOffice.org is an office suite.\n" ),
            "http://kde.openoffice.org/index.html",
            "dev@kde.openoffice.org");
    kAboutData->addAuthor( "Jan Holesovsky",
            I18N_NOOP( "Original author and maintainer of the KDE NWF." ),
            "kendy@artax.karlin.mff.cuni.cz",
            "http://artax.karlin.mff.cuni.cz/~kendy" );

    int nFakeArgc = 1;
    char** pFakeArgv = NULL;
    USHORT nIdx;
    vos::OExtCommandLine aCommandLine;
    int nParams = aCommandLine.getCommandArgCount();
    rtl::OString aDisplay;
    rtl::OUString aParam, aBin;

    for ( nIdx = 0; nIdx < nParams; ++nIdx )
    {
        aCommandLine.getCommandArg( nIdx, aParam );
        if ( !pFakeArgv && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
        {
            aCommandLine.getCommandArg( nIdx + 1, aParam );
            aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );

            nFakeArgc = 3;
            pFakeArgv = new char*[ nFakeArgc ];
            pFakeArgv[ 1 ] = strdup( "-display" );
            pFakeArgv[ 2 ] = strdup( aDisplay.getStr() );
        }
    }
    if ( !pFakeArgv )
        pFakeArgv = new char*[ nFakeArgc ];

    osl_getExecutableFile( &aParam.pData );
    osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
    pFakeArgv[0] = strdup( rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() ).getStr() );

    KCmdLineArgs::init( nFakeArgc, pFakeArgv, kAboutData );

    // Do not let KApplication eat the DESKTOP_STARTUP_ID
    char *pDesktopStartupId = NULL;
    char *pEnv = getenv( "DESKTOP_STARTUP_ID" );
    if ( pEnv )
    {
        pDesktopStartupId = strdup( pEnv );
        unsetenv( "DESKTOP_STARTUP_ID" );
    }

    KApplication::disableAutoDcopRegistration();
    KStartupInfo::disableAutoAppStartedSending();
    new KApplication();

    // Now set DESKTOP_STARTUP_ID for the VCL initialization
    if ( pDesktopStartupId )
    {
        setenv( "DESKTOP_STARTUP_ID", pDesktopStartupId, 1 );
        free( pDesktopStartupId );
    }

    Display* pDisp = QPaintDevice::x11AppDisplay();
    XVisualInfo aVI;
    Colormap    aColMap;
    int         nScreen = DefaultScreen( pDisp );
    if( SalDisplay::BestVisual( pDisp, nScreen, aVI ) ) // DefaultVisual
        aColMap = DefaultColormap( pDisp, nScreen );
    else
        aColMap = XCreateColormap( pDisp,
                                   RootWindow( pDisp, nScreen ),
                                   aVI.visual,
                                   AllocNone );

    SalDisplay *pSalDisplay = new SalX11Display( pDisp, aVI.visual, aColMap );

    pInputMethod->CreateMethod( pDisp );
    pInputMethod->AddConnectionWatch( pDisp, (void*)this );
    pSalDisplay->SetInputMethod( pInputMethod );

    sal_Bool bOldErrorSetting = GetIgnoreXErrors();
    SetIgnoreXErrors( True );
    SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
    XSync( pDisp, False );

    pKbdExtension->UseExtension( ! WasXError() );
    SetIgnoreXErrors( bOldErrorSetting );

    pSalDisplay->SetKbdExtension( pKbdExtension );
}

/**********************************************************************
 * class KDEData                                                      *
 **********************************************************************/

KDEData::~KDEData()
{
}

void KDEData::Init()
{
    pXLib_ = new KDEXLib();
    pXLib_->Init();
}

/**********************************************************************
 * plugin entry point                                                 *
 **********************************************************************/

extern "C" {
    VCL_DLLPUBLIC SalInstance* create_SalInstance( oslModule pModule )
    {
        KDESalInstance* pInstance = new KDESalInstance( new SalYieldMutex() );
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "created KDESalInstance 0x%p\n", pInstance );
#endif

        // initialize SalData
        SalData *pSalData = new KDEData();
        SetSalData( pSalData );
        pSalData->pInstance_ = pInstance;
        pSalData->Init();
        pSalData->initNWF();

        return pInstance;
    }
}
<commit_msg>INTEGRATION: CWS kdefixes02 (1.5.4); FILE MERGED 2005/04/18 09:37:29 kendy 1.5.4.1: #i47401# Remove the necessity to build with --enable-libsn to have startup notification working with KDE vclplug.<commit_after>/*************************************************************************
 *
 *  $RCSfile: kdedata.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-22 11:33:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Jan Holesovsky <kendy@artax.karlin.mff.cuni.cz>
 *                  Michael Meeks <michael@ximian.com>
 *
 ************************************************************************/

#define _SV_SALDATA_CXX

#define Region QtXRegion
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qpaintdevice.h>
#undef Region

#include <unistd.h>
#include <fcntl.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <poll.h>
#ifdef FREEBSD
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#endif

#ifndef _VCL_KDEDATA_HXX
#include <plugins/kde/kdedata.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#include <osl/module.h>

#include <tools/debug.hxx>

#ifndef _SAL_I18N_INPUTMETHOD_HXX
#include "i18n_im.hxx"
#endif
#ifndef _SAL_I18N_XKBDEXTENSION_HXX
#include "i18n_xkb.hxx"
#endif

#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif

/***************************************************************************
 * class SalKDEDisplay                                                     *
 ***************************************************************************/

SalKDEDisplay::SalKDEDisplay( Display* pDisp, Visual* pVisual, Colormap aColMap )
    : SalX11Display( pDisp, pVisual, aColMap, false )
{
}

SalKDEDisplay::~SalKDEDisplay()
{
    KStartupInfo::appStarted();
}

/***************************************************************************
 * class KDEXLib                                                           *
 ***************************************************************************/

void KDEXLib::Init()
{
    SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
    pInputMethod->SetLocale();
    XrmInitialize();

    KAboutData *kAboutData = new KAboutData( "OpenOffice.org",
            I18N_NOOP( "OpenOffice.org" ),
            "1.1.0",
            I18N_NOOP( "OpenOffice.org with KDE Native Widget Support." ),
            KAboutData::License_LGPL,
            "(c) 2003, 2004 Novell, Inc",
            I18N_NOOP( "OpenOffice.org is an office suite.\n" ),
            "http://kde.openoffice.org/index.html",
            "dev@kde.openoffice.org");
    kAboutData->addAuthor( "Jan Holesovsky",
            I18N_NOOP( "Original author and maintainer of the KDE NWF." ),
            "kendy@artax.karlin.mff.cuni.cz",
            "http://artax.karlin.mff.cuni.cz/~kendy" );

    int nFakeArgc = 1;
    char** pFakeArgv = NULL;
    USHORT nIdx;
    vos::OExtCommandLine aCommandLine;
    int nParams = aCommandLine.getCommandArgCount();
    rtl::OString aDisplay;
    rtl::OUString aParam, aBin;

    for ( nIdx = 0; nIdx < nParams; ++nIdx )
    {
        aCommandLine.getCommandArg( nIdx, aParam );
        if ( !pFakeArgv && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
        {
            aCommandLine.getCommandArg( nIdx + 1, aParam );
            aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );

            nFakeArgc = 3;
            pFakeArgv = new char*[ nFakeArgc ];
            pFakeArgv[ 1 ] = strdup( "-display" );
            pFakeArgv[ 2 ] = strdup( aDisplay.getStr() );
        }
    }
    if ( !pFakeArgv )
        pFakeArgv = new char*[ nFakeArgc ];

    osl_getExecutableFile( &aParam.pData );
    osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
    pFakeArgv[0] = strdup( rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() ).getStr() );

    KCmdLineArgs::init( nFakeArgc, pFakeArgv, kAboutData );

    KApplication::disableAutoDcopRegistration();
    new KApplication();

    Display* pDisp = QPaintDevice::x11AppDisplay();

    SalDisplay *pSalDisplay = new SalKDEDisplay( pDisp,
            static_cast< Visual * >( QPaintDevice::x11AppVisual() ),
            QPaintDevice::x11AppColormap() );

    pInputMethod->CreateMethod( pDisp );
    pInputMethod->AddConnectionWatch( pDisp, (void*)this );
    pSalDisplay->SetInputMethod( pInputMethod );

    sal_Bool bOldErrorSetting = GetIgnoreXErrors();
    SetIgnoreXErrors( True );
    SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
    XSync( pDisp, False );

    pKbdExtension->UseExtension( ! WasXError() );
    SetIgnoreXErrors( bOldErrorSetting );

    pSalDisplay->SetKbdExtension( pKbdExtension );
}

/**********************************************************************
 * class KDEData                                                      *
 **********************************************************************/

KDEData::~KDEData()
{
}

void KDEData::Init()
{
    pXLib_ = new KDEXLib();
    pXLib_->Init();
}

/**********************************************************************
 * plugin entry point                                                 *
 **********************************************************************/

extern "C" {
    VCL_DLLPUBLIC SalInstance* create_SalInstance( oslModule pModule )
    {
        KDESalInstance* pInstance = new KDESalInstance( new SalYieldMutex() );
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "created KDESalInstance 0x%p\n", pInstance );
#endif

        // initialize SalData
        SalData *pSalData = new KDEData();
        SetSalData( pSalData );
        pSalData->pInstance_ = pInstance;
        pSalData->Init();
        pSalData->initNWF();

        return pInstance;
    }
}
<|endoftext|>


<commit_before>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cphvb.h>
#include "darray_extension.h"
#include <cmath>
#include <cstring>
#include <vector>
#include <cassert>

//Finds the largest dimension size possible
cphvb_error find_largest_chunk_dim(cphvb_intp localsize,
                                   cphvb_intp ndim,
                                   const cphvb_intp stride[],
                                   cphvb_intp offset,
                                   const cphvb_intp max_dims[],
                                   cphvb_intp d,
                                   cphvb_intp dims[])
{
    while(1)//TODO:Sort 'd'
    {
        if(stride[d] == 0)
            dims[d] = max_dims[d];
        else
            dims[d] = ceil((localsize - offset) / (double) stride[d]);

        if(dims[d] > max_dims[d])//Overflow of the max dimension size
        {
            dims[d] = max_dims[d];
            break;
        }
        else if(dims[d] <= 0)//Overflow of the local dimension size
        {
            dims[d] = 1;
            ++d;
            if(d >= ndim)
            {
                fprintf(stderr,"Fatal error - All dimensions are "
                               "overflowing in find_largest_chunk_dim()\n");
                return CPHVB_ERROR;
            }
        }
        else
            break;
    }

    if(d+1 >= ndim)
        return CPHVB_SUCCESS;

    //Check for overflow
    cphvb_intp end_elem = offset;
    for(cphvb_intp i=0; i<ndim; ++i)
       end_elem += (dims[i]-1) * stride[i];
    if(end_elem >= localsize)
        --dims[d];

    if(dims[d] <= 0)
    {
        dims[d] = 1;
        return CPHVB_PARTIAL_SUCCESS;//We have to start over with a less significant 'd'
    }
    else
        return CPHVB_SUCCESS;
}

//Get the largest chunk possible
cphvb_error get_largest_chunk(int NPROC,
                              const cphvb_array *ary,
                              const cphvb_intp dim_offset[],
                              cphvb_array *chunk,
                              darray_ext *dary)
{
    cphvb_error ret;
    //Find the least significant dimension not completely included in the last chuck
    cphvb_intp incomplete_dim = 0;
    for(cphvb_intp d=ary->ndim-1; d >= 0; --d)//TODO:Sort 'd'
    {
        if(dim_offset[d] != 0 && dim_offset[d] != ary->shape[d])
        {
            incomplete_dim = d;
            break;
        }
    }

    //Compute the global offset based on the dimension offset
    cphvb_intp offset = ary->start;
    for(cphvb_intp d=0; d<ary->ndim; ++d)
        offset += dim_offset[d] * ary->stride[d];

    //Compute total array base size
    cphvb_intp totalsize=1;
    for(cphvb_intp i=0; i<cphvb_base_array(ary)->ndim; ++i)
        totalsize *= cphvb_base_array(ary)->shape[i];

    //Compute local array base size
    cphvb_intp localsize = totalsize / NPROC;

    //Find the rank
    int rank = offset / localsize;
    //Convert to local offset
    offset = offset % localsize;

    //Find maximum dimension sizes
    cphvb_intp max_dim[CPHVB_MAXDIM];
    for(cphvb_intp d=0; d<incomplete_dim; ++d)//TODO:Sort 'd'
        max_dim[d] = 1;
    max_dim[incomplete_dim] = ary->shape[incomplete_dim] - dim_offset[incomplete_dim];
    for(cphvb_intp d=incomplete_dim+1; d<ary->ndim; ++d)//TODO:Sort 'd'
        max_dim[d] = ary->shape[d];

    //Find largest possible dimension
    cphvb_intp dim[CPHVB_MAXDIM];
    memcpy(dim, max_dim, ary->ndim * sizeof(cphvb_intp));
    ret = CPHVB_PARTIAL_SUCCESS;
    while(ret == CPHVB_PARTIAL_SUCCESS)
    {
        ret = find_largest_chunk_dim(localsize, ary->ndim, ary->stride, offset,
                                     max_dim,incomplete_dim++, dim);//TODO:Sort 'incomplete_dim+1'
    }
    if(ret != CPHVB_SUCCESS)
        return ret;

    //Save chunk
    dary->rank   = rank;
    chunk->base  = cphvb_base_array(ary);
    chunk->type  = ary->type;
    chunk->ndim  = ary->ndim;
    chunk->data  = NULL;
    memcpy(chunk->stride, ary->stride, ary->ndim * sizeof(cphvb_intp));
    chunk->start = offset;
    memcpy(chunk->shape, dim, ary->ndim * sizeof(cphvb_intp));

    return CPHVB_SUCCESS;
}

cphvb_error local_arrays(int NPROC,
                         cphvb_instruction *inst,
                         std::vector<cphvb_array>& chunks,
                         std::vector<darray_ext>& chunks_ext)
{
    cphvb_error ret;
    cphvb_intp dim_offset[CPHVB_MAXDIM];
    memset(dim_offset, 0, inst->operand[0]->ndim * sizeof(cphvb_intp));

    //Handle one chunk at a time
    cphvb_intp first_chunk = 0;
    while(1)
    {
        cphvb_intp op_is_constant = -1;

        for(cphvb_intp o=0; o < cphvb_operands_in_instruction(inst); ++o)
        {
            cphvb_array chunk;
            darray_ext chunk_ext;
            cphvb_array *ary = inst->operand[o];

            if(cphvb_is_constant(ary))
            {
                //Inset empty chunk as placeholder
                cphvb_array chunk;
                darray_ext chunk_ext;
                chunks.push_back(chunk);
                chunks_ext.push_back(chunk_ext);
                assert(op_is_constant == -1);
                op_is_constant = o;
                continue;
            }

            if((ret = get_largest_chunk(NPROC,ary, dim_offset, &chunk, &chunk_ext)) != CPHVB_SUCCESS)
                return ret;

            chunks.push_back(chunk);
            chunks_ext.push_back(chunk_ext);
        }
        cphvb_intp min_dim_size[CPHVB_MAXDIM];
        memcpy(min_dim_size, chunks[first_chunk].shape, chunks[first_chunk].ndim * sizeof(cphvb_intp));

        //Find the greates dimensions included by all operands
        for(cphvb_intp o=1; o < cphvb_operands_in_instruction(inst); ++o)
        {
            if(op_is_constant == o)
                continue;

            cphvb_array *ary = &chunks[first_chunk + o];
            for(cphvb_intp i=0; i < ary->ndim; ++i)
            {
                if(ary->shape[i] < min_dim_size[i])
                    min_dim_size[i] = ary->shape[i];
            }
        }

        //Set the new dimension sizes
        for(cphvb_intp o=0; o < cphvb_operands_in_instruction(inst); ++o)
        {
            if(op_is_constant == o)
                continue;

            cphvb_array *ary = &chunks[first_chunk + o];
            for(cphvb_intp i=0; i < ary->ndim; ++i)
                ary->shape[i] = min_dim_size[i];
        }

        //New "first chunk" for the next iteration
        first_chunk += cphvb_operands_in_instruction(inst);

        //Find the least significant dimension not completely included in the last chuck
        cphvb_intp incomplete_dim = -1;
        for(cphvb_intp d=inst->operand[0]->ndim-1; d >= 0; --d)//TODO:Sort 'd'
        {
            if(min_dim_size[d] != inst->operand[0]->shape[d])
            {
                incomplete_dim = d;
                break;
            }
        }
        if(incomplete_dim == -1)
            return CPHVB_SUCCESS;

        //Update the dimension offsets
        for(cphvb_intp d=incomplete_dim; d >= 0; --d)//TODO:Sort 'd'
        {
            dim_offset[d] += min_dim_size[d];
            if(dim_offset[d] >= inst->operand[0]->shape[d])
            {
                if(d == 0)
                    return CPHVB_SUCCESS;
                dim_offset[d] = 0;
            }
            else
                break;
        }
    }
}

<commit_msg>Fixed a BUG where localsize was zero<commit_after>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cphvb.h>
#include "darray_extension.h"
#include <cmath>
#include <cstring>
#include <vector>
#include <cassert>

//Finds the largest dimension size possible
cphvb_error find_largest_chunk_dim(cphvb_intp localsize,
                                   cphvb_intp ndim,
                                   const cphvb_intp stride[],
                                   cphvb_intp offset,
                                   const cphvb_intp max_dims[],
                                   cphvb_intp d,
                                   cphvb_intp dims[])
{
    while(1)//TODO:Sort 'd'
    {
        if(stride[d] == 0)
            dims[d] = max_dims[d];
        else
            dims[d] = ceil((localsize - offset) / (double) stride[d]);

        if(dims[d] > max_dims[d])//Overflow of the max dimension size
        {
            dims[d] = max_dims[d];
            break;
        }
        else if(dims[d] <= 0)//Overflow of the local dimension size
        {
            dims[d] = 1;
            ++d;
            if(d >= ndim)
            {
                fprintf(stderr,"Fatal error - All dimensions are "
                               "overflowing in find_largest_chunk_dim()\n");
                return CPHVB_ERROR;
            }
        }
        else
            break;
    }

    if(d+1 >= ndim)
        return CPHVB_SUCCESS;

    //Check for overflow
    cphvb_intp end_elem = offset;
    for(cphvb_intp i=0; i<ndim; ++i)
       end_elem += (dims[i]-1) * stride[i];
    if(end_elem >= localsize)
        --dims[d];

    if(dims[d] <= 0)
    {
        dims[d] = 1;
        return CPHVB_PARTIAL_SUCCESS;//We have to start over with a less significant 'd'
    }
    else
        return CPHVB_SUCCESS;
}

//Get the largest chunk possible
cphvb_error get_largest_chunk(int NPROC,
                              const cphvb_array *ary,
                              const cphvb_intp dim_offset[],
                              cphvb_array *chunk,
                              darray_ext *dary)
{
    cphvb_error ret;
    //Find the least significant dimension not completely included in the last chuck
    cphvb_intp incomplete_dim = 0;
    for(cphvb_intp d=ary->ndim-1; d >= 0; --d)//TODO:Sort 'd'
    {
        if(dim_offset[d] != 0 && dim_offset[d] != ary->shape[d])
        {
            incomplete_dim = d;
            break;
        }
    }

    //Compute the global offset based on the dimension offset
    cphvb_intp offset = ary->start;
    for(cphvb_intp d=0; d<ary->ndim; ++d)
        offset += dim_offset[d] * ary->stride[d];

    //Compute total array base size
    cphvb_intp totalsize=1;
    for(cphvb_intp i=0; i<cphvb_base_array(ary)->ndim; ++i)
        totalsize *= cphvb_base_array(ary)->shape[i];

    //Compute local array base size for nrank-1
    cphvb_intp localsize = totalsize / NPROC;
    if(localsize == 0)
        localsize = 1;

    //Find the rank
    int rank = offset / localsize;
    //Convert to local offset
    offset = offset % localsize;
    //Convert localsize to be specific for this rank
    if(rank == NPROC-1)
        localsize = totalsize / NPROC + totalsize % NPROC;

    //Find maximum dimension sizes
    cphvb_intp max_dim[CPHVB_MAXDIM];
    for(cphvb_intp d=0; d<incomplete_dim; ++d)//TODO:Sort 'd'
        max_dim[d] = 1;
    max_dim[incomplete_dim] = ary->shape[incomplete_dim] - dim_offset[incomplete_dim];
    for(cphvb_intp d=incomplete_dim+1; d<ary->ndim; ++d)//TODO:Sort 'd'
        max_dim[d] = ary->shape[d];

    //Find largest possible dimension
    cphvb_intp dim[CPHVB_MAXDIM];
    memcpy(dim, max_dim, ary->ndim * sizeof(cphvb_intp));
    ret = CPHVB_PARTIAL_SUCCESS;
    while(ret == CPHVB_PARTIAL_SUCCESS)
    {
        ret = find_largest_chunk_dim(localsize, ary->ndim, ary->stride, offset,
                                     max_dim,incomplete_dim++, dim);//TODO:Sort 'incomplete_dim+1'
    }
    if(ret != CPHVB_SUCCESS)
        return ret;

    //Save chunk
    dary->rank   = rank;
    chunk->base  = cphvb_base_array(ary);
    chunk->type  = ary->type;
    chunk->ndim  = ary->ndim;
    chunk->data  = NULL;
    memcpy(chunk->stride, ary->stride, ary->ndim * sizeof(cphvb_intp));
    chunk->start = offset;
    memcpy(chunk->shape, dim, ary->ndim * sizeof(cphvb_intp));

    return CPHVB_SUCCESS;
}

cphvb_error local_arrays(int NPROC,
                         cphvb_instruction *inst,
                         std::vector<cphvb_array>& chunks,
                         std::vector<darray_ext>& chunks_ext)
{
    cphvb_error ret;
    cphvb_intp dim_offset[CPHVB_MAXDIM];
    memset(dim_offset, 0, inst->operand[0]->ndim * sizeof(cphvb_intp));

    //Handle one chunk at a time
    cphvb_intp first_chunk = 0;
    while(1)
    {
        cphvb_intp op_is_constant = -1;

        for(cphvb_intp o=0; o < cphvb_operands_in_instruction(inst); ++o)
        {
            cphvb_array chunk;
            darray_ext chunk_ext;
            cphvb_array *ary = inst->operand[o];

            if(cphvb_is_constant(ary))
            {
                //Inset empty chunk as placeholder
                cphvb_array chunk;
                darray_ext chunk_ext;
                chunks.push_back(chunk);
                chunks_ext.push_back(chunk_ext);
                assert(op_is_constant == -1);
                op_is_constant = o;
                continue;
            }

            if((ret = get_largest_chunk(NPROC,ary, dim_offset, &chunk, &chunk_ext)) != CPHVB_SUCCESS)
                return ret;

            chunks.push_back(chunk);
            chunks_ext.push_back(chunk_ext);
        }
        cphvb_intp min_dim_size[CPHVB_MAXDIM];
        memcpy(min_dim_size, chunks[first_chunk].shape, chunks[first_chunk].ndim * sizeof(cphvb_intp));

        //Find the greates dimensions included by all operands
        for(cphvb_intp o=1; o < cphvb_operands_in_instruction(inst); ++o)
        {
            if(op_is_constant == o)
                continue;

            cphvb_array *ary = &chunks[first_chunk + o];
            for(cphvb_intp i=0; i < ary->ndim; ++i)
            {
                if(ary->shape[i] < min_dim_size[i])
                    min_dim_size[i] = ary->shape[i];
            }
        }

        //Set the new dimension sizes
        for(cphvb_intp o=0; o < cphvb_operands_in_instruction(inst); ++o)
        {
            if(op_is_constant == o)
                continue;

            cphvb_array *ary = &chunks[first_chunk + o];
            for(cphvb_intp i=0; i < ary->ndim; ++i)
                ary->shape[i] = min_dim_size[i];
        }

        //New "first chunk" for the next iteration
        first_chunk += cphvb_operands_in_instruction(inst);

        //Find the least significant dimension not completely included in the last chuck
        cphvb_intp incomplete_dim = -1;
        for(cphvb_intp d=inst->operand[0]->ndim-1; d >= 0; --d)//TODO:Sort 'd'
        {
            if(min_dim_size[d] != inst->operand[0]->shape[d])
            {
                incomplete_dim = d;
                break;
            }
        }
        if(incomplete_dim == -1)
            return CPHVB_SUCCESS;

        //Update the dimension offsets
        for(cphvb_intp d=incomplete_dim; d >= 0; --d)//TODO:Sort 'd'
        {
            dim_offset[d] += min_dim_size[d];
            if(dim_offset[d] >= inst->operand[0]->shape[d])
            {
                if(d == 0)
                    return CPHVB_SUCCESS;
                dim_offset[d] = 0;
            }
            else
                break;
        }
    }
}

<|endoftext|>


<commit_before>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"

//ƽַ̨
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
    virtual ~CSysControlLocal();

	virtual void Init();	//ɫҪʼɫҪʼ
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//״̬״̬״̬ӵ״̬ȵȡ
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//Ƿʾ
	virtual int GetMouseGrab();			//ȡ״̬ʾػǲʾ״̬

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"

//ƽַ̨
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
    virtual ~CSysControlLocal();

	virtual void Init();	//ɫҪʼɫҪʼ
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//״̬״̬״̬ӵ״̬ȵȡ
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//Ƿʾ
	virtual int GetMouseGrab();			//ȡ״̬ʾػǲʾ״̬

	virtual void SetControlMode(ControlMode mode);			//ģʽ
	virtual ControlMode GetControlMode() const;				//ȡģʽ

}<|endoftext|>


<commit_before>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// LZW compression -- the LZW/GIF patent has expired, so we can use it now!!!
//
//=============================================================================

#define MSS

#include <stdio.h>
#include <stdlib.h>
#include "ac/common.h"
#include "util/datastream.h"

using AGS::Common::DataStream;
using namespace AGS; // FIXME later

#ifdef _MANAGED
// ensure this doesn't get compiled to .NET IL
#pragma unmanaged
#endif

#if defined (WINDOWS_VERSION)
#include <io.h>
#endif

int insert(int, int);
void _delete(int);

#define N 4096
#define F 16
#define THRESHOLD 3
#define min(xx,yy) ((yy<xx) ? yy : xx)

#define dad (node+1)
#define lson (node+1+N)
#define rson (node+1+N+N)
#define root (node+1+N+N+N)
#define NIL -1

char *lzbuffer;
int *node;
int pos;
long outbytes = 0, maxsize = 0, putbytes = 0;

int insert(int i, int run)
{
  int c, j, k, l, n, match;
  int *p;

  k = l = 1;
  match = THRESHOLD - 1;
  p = &root[(unsigned char)lzbuffer[i]];
  lson[i] = rson[i] = NIL;
  while ((j = *p) != NIL) {
    for (n = min(k, l); n < run && (c = (lzbuffer[j + n] - lzbuffer[i + n])) == 0; n++) ;

    if (n > match) {
      match = n;
      pos = j;
    }

    if (c < 0) {
      p = &lson[j];
      k = n;
    } else if (c > 0) {
      p = &rson[j];
      l = n;
    } else {
      dad[j] = NIL;
      dad[lson[j]] = lson + i - node;
      dad[rson[j]] = rson + i - node;
      lson[i] = lson[j];
      rson[i] = rson[j];
      break;
    }
  }

  dad[i] = p - node;
  *p = i;
  return match;
}

void _delete(int z)
{
  int j;

  if (dad[z] != NIL) {
    if (rson[z] == NIL)
      j = lson[z];
    else if (lson[z] == NIL)
      j = rson[z];
    else {
      j = lson[z];
      if (rson[j] != NIL) {
        do {
          j = rson[j];
        } while (rson[j] != NIL);

        node[dad[j]] = lson[j];
        dad[lson[j]] = dad[j];
        lson[j] = lson[z];
        dad[lson[z]] = lson + j - node;
      }

      rson[j] = rson[z];
      dad[rson[z]] = rson + j - node;
    }

    dad[j] = dad[z];
    node[dad[z]] = j;
    dad[z] = NIL;
  }
}

void lzwcompress(Common::DataStream *lzw_in, Common::DataStream *out)
{
  int ch, i, run, len, match, size, mask;
  char buf[17];

  lzbuffer = (char *)malloc(N + F + (N + 1 + N + N + 256) * sizeof(int));       // 28.5 k !
  if (lzbuffer == NULL) {
    quit("unable to compress: out of memory");
  }

  node = (int *)(lzbuffer + N + F);
  for (i = 0; i < 256; i++)
    root[i] = NIL;

  for (i = NIL; i < N; i++)
    dad[i] = NIL;

  size = mask = 1;
  buf[0] = 0;
  i = N - F - F;

  for (len = 0; len < F && (ch = lzw_in->ReadByte()) != -1; len++) {
    lzbuffer[i + F] = ch;
    i = (i + 1) & (N - 1);
  }

  run = len;

  do {
    ch = lzw_in->ReadByte();
    if (i >= N - F) {
      _delete(i + F - N);
      lzbuffer[i + F] = lzbuffer[i + F - N] = ch;
    } else {
      _delete(i + F);
      lzbuffer[i + F] = ch;
    }

    match = insert(i, run);
    if (ch == -1) {
      run--;
      len--;
    }

    if (len++ >= run) {
      if (match >= THRESHOLD) {
        buf[0] |= mask;
        // possible fix: change int* to short* ??
        *(short *)(buf + size) = ((match - 3) << 12) | ((i - pos - 1) & (N - 1));
        size += 2;
        len -= match;
      } else {
        buf[size++] = lzbuffer[i];
        len--;
      }

      if (!((mask += mask) & 0xFF)) {
        out->WriteArray(buf, size, 1);
        outbytes += size;
        size = mask = 1;
        buf[0] = 0;
      }
    }
    i = (i + 1) & (N - 1);
  } while (len > 0);

  if (size > 1) {
    out->WriteArray(buf, size, 1);
    outbytes += size;
  }

  free(lzbuffer);
}

int expand_to_mem = 0;
unsigned char *membfptr = NULL;
void myputc(int ccc, DataStream *out)
{
  if (maxsize > 0) {
    putbytes++;
    if (putbytes > maxsize)
      return;
  }

  outbytes++;
  if (expand_to_mem) {
    membfptr[0] = ccc;
    membfptr++;
  } else
    out->WriteInt8(ccc);
}

void lzwexpand(DataStream *lzw_in, DataStream *out)
{
  int bits, ch, i, j, len, mask;
  char *lzbuffer;
//  printf(" UnShrinking: %s ",filena);
  putbytes = 0;

  lzbuffer = (char *)malloc(N);
  if (lzbuffer == NULL) {
    quit("compress.cpp: unable to decompress: insufficient memory");
  }
  i = N - F;

  // this end condition just checks for EOF, which is no good to us
  while ((bits = lzw_in->ReadByte()) != -1) {
    for (mask = 0x01; mask & 0xFF; mask <<= 1) {
      if (bits & mask) {
        // MACPORT FIX: read to short and expand
        short jshort = 0;
        jshort = lzw_in->ReadInt16();
        j = jshort;

        len = ((j >> 12) & 15) + 3;
        j = (i - j - 1) & (N - 1);

        while (len--) {
          myputc(lzbuffer[i] = lzbuffer[j], out);
          j = (j + 1) & (N - 1);
          i = (i + 1) & (N - 1);
        }
      } else {
        ch = lzw_in->ReadByte();
        myputc(lzbuffer[i] = ch, out);
        i = (i + 1) & (N - 1);
      }

      if ((putbytes >= maxsize) && (maxsize > 0))
        break;

      if ((lzw_in->EOS()) && (maxsize > 0))
        quit("Read error decompressing image - file is corrupt");
    }                           // end for mask

    if ((putbytes >= maxsize) && (maxsize > 0))
      break;
  }

  free(lzbuffer);
  expand_to_mem = 0;
}

unsigned char *lzwexpand_to_mem(Common::DataStream *in)
{
  unsigned char *membuff = (unsigned char *)malloc(maxsize + 10);
  expand_to_mem = 1;
  membfptr = membuff;
  lzwexpand(in, NULL);
  return membuff;
}
<commit_msg>Initialize local variable in LZW algorythm<commit_after>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// LZW compression -- the LZW/GIF patent has expired, so we can use it now!!!
//
//=============================================================================

#define MSS

#include <stdio.h>
#include <stdlib.h>
#include "ac/common.h"
#include "util/datastream.h"

using AGS::Common::DataStream;
using namespace AGS; // FIXME later

#ifdef _MANAGED
// ensure this doesn't get compiled to .NET IL
#pragma unmanaged
#endif

#if defined (WINDOWS_VERSION)
#include <io.h>
#endif

int insert(int, int);
void _delete(int);

#define N 4096
#define F 16
#define THRESHOLD 3
#define min(xx,yy) ((yy<xx) ? yy : xx)

#define dad (node+1)
#define lson (node+1+N)
#define rson (node+1+N+N)
#define root (node+1+N+N+N)
#define NIL -1

char *lzbuffer;
int *node;
int pos;
long outbytes = 0, maxsize = 0, putbytes = 0;

int insert(int i, int run)
{
  int c, j, k, l, n, match;
  int *p;

  c = NIL;

  k = l = 1;
  match = THRESHOLD - 1;
  p = &root[(unsigned char)lzbuffer[i]];
  lson[i] = rson[i] = NIL;
  while ((j = *p) != NIL) {
    for (n = min(k, l); n < run && (c = (lzbuffer[j + n] - lzbuffer[i + n])) == 0; n++) ;

    if (n > match) {
      match = n;
      pos = j;
    }

    if (c < 0) {
      p = &lson[j];
      k = n;
    } else if (c > 0) {
      p = &rson[j];
      l = n;
    } else {
      dad[j] = NIL;
      dad[lson[j]] = lson + i - node;
      dad[rson[j]] = rson + i - node;
      lson[i] = lson[j];
      rson[i] = rson[j];
      break;
    }
  }

  dad[i] = p - node;
  *p = i;
  return match;
}

void _delete(int z)
{
  int j;

  if (dad[z] != NIL) {
    if (rson[z] == NIL)
      j = lson[z];
    else if (lson[z] == NIL)
      j = rson[z];
    else {
      j = lson[z];
      if (rson[j] != NIL) {
        do {
          j = rson[j];
        } while (rson[j] != NIL);

        node[dad[j]] = lson[j];
        dad[lson[j]] = dad[j];
        lson[j] = lson[z];
        dad[lson[z]] = lson + j - node;
      }

      rson[j] = rson[z];
      dad[rson[z]] = rson + j - node;
    }

    dad[j] = dad[z];
    node[dad[z]] = j;
    dad[z] = NIL;
  }
}

void lzwcompress(Common::DataStream *lzw_in, Common::DataStream *out)
{
  int ch, i, run, len, match, size, mask;
  char buf[17];

  lzbuffer = (char *)malloc(N + F + (N + 1 + N + N + 256) * sizeof(int));       // 28.5 k !
  if (lzbuffer == NULL) {
    quit("unable to compress: out of memory");
  }

  node = (int *)(lzbuffer + N + F);
  for (i = 0; i < 256; i++)
    root[i] = NIL;

  for (i = NIL; i < N; i++)
    dad[i] = NIL;

  size = mask = 1;
  buf[0] = 0;
  i = N - F - F;

  for (len = 0; len < F && (ch = lzw_in->ReadByte()) != -1; len++) {
    lzbuffer[i + F] = ch;
    i = (i + 1) & (N - 1);
  }

  run = len;

  do {
    ch = lzw_in->ReadByte();
    if (i >= N - F) {
      _delete(i + F - N);
      lzbuffer[i + F] = lzbuffer[i + F - N] = ch;
    } else {
      _delete(i + F);
      lzbuffer[i + F] = ch;
    }

    match = insert(i, run);
    if (ch == -1) {
      run--;
      len--;
    }

    if (len++ >= run) {
      if (match >= THRESHOLD) {
        buf[0] |= mask;
        // possible fix: change int* to short* ??
        *(short *)(buf + size) = ((match - 3) << 12) | ((i - pos - 1) & (N - 1));
        size += 2;
        len -= match;
      } else {
        buf[size++] = lzbuffer[i];
        len--;
      }

      if (!((mask += mask) & 0xFF)) {
        out->WriteArray(buf, size, 1);
        outbytes += size;
        size = mask = 1;
        buf[0] = 0;
      }
    }
    i = (i + 1) & (N - 1);
  } while (len > 0);

  if (size > 1) {
    out->WriteArray(buf, size, 1);
    outbytes += size;
  }

  free(lzbuffer);
}

int expand_to_mem = 0;
unsigned char *membfptr = NULL;
void myputc(int ccc, DataStream *out)
{
  if (maxsize > 0) {
    putbytes++;
    if (putbytes > maxsize)
      return;
  }

  outbytes++;
  if (expand_to_mem) {
    membfptr[0] = ccc;
    membfptr++;
  } else
    out->WriteInt8(ccc);
}

void lzwexpand(DataStream *lzw_in, DataStream *out)
{
  int bits, ch, i, j, len, mask;
  char *lzbuffer;
//  printf(" UnShrinking: %s ",filena);
  putbytes = 0;

  lzbuffer = (char *)malloc(N);
  if (lzbuffer == NULL) {
    quit("compress.cpp: unable to decompress: insufficient memory");
  }
  i = N - F;

  // this end condition just checks for EOF, which is no good to us
  while ((bits = lzw_in->ReadByte()) != -1) {
    for (mask = 0x01; mask & 0xFF; mask <<= 1) {
      if (bits & mask) {
        // MACPORT FIX: read to short and expand
        short jshort = 0;
        jshort = lzw_in->ReadInt16();
        j = jshort;

        len = ((j >> 12) & 15) + 3;
        j = (i - j - 1) & (N - 1);

        while (len--) {
          myputc(lzbuffer[i] = lzbuffer[j], out);
          j = (j + 1) & (N - 1);
          i = (i + 1) & (N - 1);
        }
      } else {
        ch = lzw_in->ReadByte();
        myputc(lzbuffer[i] = ch, out);
        i = (i + 1) & (N - 1);
      }

      if ((putbytes >= maxsize) && (maxsize > 0))
        break;

      if ((lzw_in->EOS()) && (maxsize > 0))
        quit("Read error decompressing image - file is corrupt");
    }                           // end for mask

    if ((putbytes >= maxsize) && (maxsize > 0))
      break;
  }

  free(lzbuffer);
  expand_to_mem = 0;
}

unsigned char *lzwexpand_to_mem(Common::DataStream *in)
{
  unsigned char *membuff = (unsigned char *)malloc(maxsize + 10);
  expand_to_mem = 1;
  membfptr = membuff;
  lzwexpand(in, NULL);
  return membuff;
}
<|endoftext|>


<commit_before>/*
 * standard_depths_test.cpp
 *
 *  Created on: March 2, 2015
 *      Author: zzawadz
 */

#include <iostream>
#include "DepthLib.hpp"
#include "../Utils/Utils.hpp"

int main()
{
	arma::colvec x = arma::linspace(1.0, 10.0,10);
	arma::colvec y = arma::linspace(1.0, 10.0,10);

	std::cout << Depth::TukeyUtils::tukey_depth1d(x,y) << std::endl;

	arma::colvec big(10000000);
	big.randn();

	//std::cout << "Depth calculation for vector of size 1000000 took "
	//<< measure<>::execution( [&]() { Depth::TukeyUtils::tukey_depth1d(big, big); }) << " microseconds. "  << std::endl;

	return 0;
}<commit_msg>Test update<commit_after>/*
 * standard_depths_test.cpp
 *
 *  Created on: March 2, 2015
 *      Author: zzawadz
 */

#include <iostream>
#include "DepthLib.hpp"
#include "../Utils/Utils.hpp"

int main()
{
	arma::colvec x = arma::linspace(1.0, 10.0,10);
	arma::colvec y = arma::linspace(1.0, 10.0,10);

	std::cout << Depth::TukeyUtils::tukey_depth1d(x,y) << std::endl;

	//arma::colvec big(10000000);
	//big.randn();

	//std::cout << "Depth calculation for vector of size 1000000 took "
	//<< measure<>::execution( [&]() { Depth::TukeyUtils::tukey_depth1d(big, big); }) << " microseconds. "  << std::endl;

	return 0;
}<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    QTestApp.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "QTestApp.h"

#include <stdio.h>

#include <QTimer>
#include <QWidget>
#include <QKeyEvent>
#include <QMouseEvent>

int QTestApp::Error = 0;

QTestApp::QTestApp(int _argc, char* _argv[])
{
#if QT_VERSION >= 0x050000
  qInstallMessageHandler(QTestApp::messageHandler);
#else
  qInstallMsgHandler(QTestApp::messageHandler);
#endif

  // CMake generated driver removes argv[0],
  // so let's put a dummy back in
  this->Argv.append("qTestApp");
  for(int i=0; i<_argc; i++)
    {
    this->Argv.append(_argv[i]);
    }
  for(int j=0; j<this->Argv.size(); j++)
    {
    this->Argvp.append(this->Argv[j].data());
    }
  this->Argc = this->Argvp.size();
  App = new QApplication(this->Argc, this->Argvp.data());
}

QTestApp::~QTestApp()
{
  delete App;
#if QT_VERSION >= 0x050000
  qInstallMessageHandler(0);
#else
  qInstallMsgHandler(0);
#endif
}

int QTestApp::exec()
{
  if(!QCoreApplication::arguments().contains("--no_exit"))
    {
    QTimer::singleShot(1000, QCoreApplication::instance(), SLOT(quit()));
    }

  int ret = QApplication::exec();
  return Error + ret;
}

#if QT_VERSION >= 0x050000
void QTestApp::messageHandler(QtMsgType type,
  const QMessageLogContext & context,
  const QString & message)
#else
void QTestApp::messageHandler(QtMsgType type, const char *msg)
#endif
{
#if QT_VERSION >= 0x050000
  Q_UNUSED(context)
  const char * msg = qPrintable(message);
#endif
  switch(type)
  {
  case QtDebugMsg:
    fprintf(stderr, "Debug: %s\n", msg);
    break;
  case QtWarningMsg:
    fprintf(stderr, "Warning: %s\n", msg);
    Error++;
    break;
  case QtCriticalMsg:
    fprintf(stderr, "Critical: %s\n", msg);
    Error++;
    break;
  case QtFatalMsg:
    fprintf(stderr, "Fatal: %s\n", msg);
    abort();
  }
}

void QTestApp::delay(int ms)
{
  if(ms > 0)
  {
    QTimer::singleShot(ms, QApplication::instance(), SLOT(quit()));
    QApplication::exec();
  }
}

void QTestApp::simulateEvent(QWidget* w, QEvent* e)
{
  bool status = QApplication::sendEvent(w, e);
  if(!status)
  {
    qWarning("event not handled\n");
  }
  QApplication::processEvents();
}

void QTestApp::keyUp(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QKeyEvent e(QEvent::KeyRelease, key, mod);
  simulateEvent(w, &e);
}

void QTestApp::keyDown(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QKeyEvent e(QEvent::KeyPress, key, mod);
  simulateEvent(w, &e);
}

void QTestApp::keyClick(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  keyDown(w, key, mod, 0);
  keyUp(w, key, mod, 0);
}

void QTestApp::mouseDown(QWidget* w, QPoint pos, Qt::MouseButton btn,
                        Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseButtonPress, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseUp(QWidget* w, QPoint pos, Qt::MouseButton btn,
                      Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseButtonRelease, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseMove(QWidget* w, QPoint pos, Qt::MouseButton btn,
                        Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseMove, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseClick(QWidget* w, QPoint pos, Qt::MouseButton btn,
                         Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  mouseDown(w, pos, btn, mod, 0);
  mouseUp(w, pos, btn, mod, 0);
}

<commit_msg>GUISupport/Qt: Port QTestApp.cxx to Qt 5.5<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    QTestApp.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "QTestApp.h"

#include <stdio.h>

#include <QTimer>
#include <QWidget>
#include <QKeyEvent>
#include <QMouseEvent>

int QTestApp::Error = 0;

QTestApp::QTestApp(int _argc, char* _argv[])
{
#if QT_VERSION >= 0x050000
  qInstallMessageHandler(QTestApp::messageHandler);
#else
  qInstallMsgHandler(QTestApp::messageHandler);
#endif

  // CMake generated driver removes argv[0],
  // so let's put a dummy back in
  this->Argv.append("qTestApp");
  for(int i=0; i<_argc; i++)
    {
    this->Argv.append(_argv[i]);
    }
  for(int j=0; j<this->Argv.size(); j++)
    {
    this->Argvp.append(this->Argv[j].data());
    }
  this->Argc = this->Argvp.size();
  App = new QApplication(this->Argc, this->Argvp.data());
}

QTestApp::~QTestApp()
{
  delete App;
#if QT_VERSION >= 0x050000
  qInstallMessageHandler(0);
#else
  qInstallMsgHandler(0);
#endif
}

int QTestApp::exec()
{
  if(!QCoreApplication::arguments().contains("--no_exit"))
    {
    QTimer::singleShot(1000, QCoreApplication::instance(), SLOT(quit()));
    }

  int ret = QApplication::exec();
  return Error + ret;
}

#if QT_VERSION >= 0x050000
void QTestApp::messageHandler(QtMsgType type,
  const QMessageLogContext & context,
  const QString & message)
#else
void QTestApp::messageHandler(QtMsgType type, const char *msg)
#endif
{
#if QT_VERSION >= 0x050000
  Q_UNUSED(context)
  const char * msg = qPrintable(message);
#endif
  switch(type)
  {
  case QtDebugMsg:
    fprintf(stderr, "Debug: %s\n", msg);
    break;
#if QT_VERSION >= 0x050500
  case QtInfoMsg:
    fprintf(stderr, "Info: %s\n", msg);
    break;
#endif
  case QtWarningMsg:
    fprintf(stderr, "Warning: %s\n", msg);
    Error++;
    break;
  case QtCriticalMsg:
    fprintf(stderr, "Critical: %s\n", msg);
    Error++;
    break;
  case QtFatalMsg:
    fprintf(stderr, "Fatal: %s\n", msg);
    abort();
  }
}

void QTestApp::delay(int ms)
{
  if(ms > 0)
  {
    QTimer::singleShot(ms, QApplication::instance(), SLOT(quit()));
    QApplication::exec();
  }
}

void QTestApp::simulateEvent(QWidget* w, QEvent* e)
{
  bool status = QApplication::sendEvent(w, e);
  if(!status)
  {
    qWarning("event not handled\n");
  }
  QApplication::processEvents();
}

void QTestApp::keyUp(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QKeyEvent e(QEvent::KeyRelease, key, mod);
  simulateEvent(w, &e);
}

void QTestApp::keyDown(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QKeyEvent e(QEvent::KeyPress, key, mod);
  simulateEvent(w, &e);
}

void QTestApp::keyClick(QWidget* w, Qt::Key key, Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  keyDown(w, key, mod, 0);
  keyUp(w, key, mod, 0);
}

void QTestApp::mouseDown(QWidget* w, QPoint pos, Qt::MouseButton btn,
                        Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseButtonPress, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseUp(QWidget* w, QPoint pos, Qt::MouseButton btn,
                      Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseButtonRelease, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseMove(QWidget* w, QPoint pos, Qt::MouseButton btn,
                        Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  QMouseEvent e(QEvent::MouseMove, pos, btn, btn, mod);
  simulateEvent(w, &e);
}

void QTestApp::mouseClick(QWidget* w, QPoint pos, Qt::MouseButton btn,
                         Qt::KeyboardModifiers mod, int ms)
{
  delay(ms);
  mouseDown(w, pos, btn, mod, 0);
  mouseUp(w, pos, btn, mod, 0);
}

<|endoftext|>