<commit_before>/*************************************************************************
 *
 *  $RCSfile: thread.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jl $ $Date: 2001-03-13 10:39:37 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _THREAD_HXX_
#define _THREAD_HXX_

#ifdef __cplusplus

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif

namespace osl
{
/** threadFunc is the function which is executed by the threads
    created by the osl::Thread class. The function's signature
    matches the one of oslWorkerFunction which is declared in
    osl/thread.h .
*/
extern "C" inline void SAL_CALL threadFunc( void* param);

class Thread
{
    Thread( const Thread& );
    Thread& operator= ( const Thread& );
public:
    // these are here to force memory de/allocation to sal lib.
    inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW ()
        { return ::rtl_allocateMemory( nSize ); }
    inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW ()
        { ::rtl_freeMemory( pMem ); }
    inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW ()
        { return pMem; }
    inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW ()
        {}

    Thread(): m_hThread(0){}

    virtual  ~Thread()
    {
        osl_destroyThread( m_hThread);
    }

    sal_Bool SAL_CALL create()
    {
        OSL_ASSERT(m_hThread == 0); // only one running thread per instance
           if (m_hThread)
            return sal_False;

        if (m_hThread= osl_createSuspendedThread( threadFunc,
                                             (void*)this))
            osl_resumeThread(m_hThread);

        return m_hThread != 0;
    }

    sal_Bool SAL_CALL createSuspended()
    {
        OSL_ASSERT(m_hThread == 0); // only one running thread per instance
        if( m_hThread)
            return sal_False;
        m_hThread= osl_createSuspendedThread( threadFunc,
                                             (void*)this);
        return m_hThread != 0;
    }

    virtual void SAL_CALL suspend()
    {
        osl_suspendThread(m_hThread);
    }

    virtual void SAL_CALL resume()
    {
        osl_resumeThread(m_hThread);
    }

    virtual void SAL_CALL terminate()
    {
        osl_terminateThread(m_hThread);
    }

    virtual void SAL_CALL join()
    {
        osl_joinWithThread(m_hThread);
    }

    sal_Bool SAL_CALL isRunning()
    {
        return m_hThread != 0 && osl_isThreadRunning(m_hThread);
    }

    void SAL_CALL setPriority( oslThreadPriority Priority)
    {
        osl_setThreadPriority(m_hThread, Priority);
    }

    oslThreadPriority SAL_CALL getPriority()
    {
        return osl_getThreadPriority(m_hThread);
    }

    oslThreadIdentifier SAL_CALL getIdentifier() const
    {
        return osl_getThreadIdentifier(m_hThread);
    }

    static oslThreadIdentifier SAL_CALL getCurrentIdentifier()
    {
        return osl_getThreadIdentifier(0);
    }

    virtual oslThreadSleep SAL_CALL sleep(const TimeValue& Delay)
    {
        return osl_sleepThread(m_hThread, &Delay);
    }

    virtual sal_Bool SAL_CALL awake()
    {
        return osl_awakeThread(m_hThread);
    }

    static void SAL_CALL wait(const TimeValue& Delay)
    {
        osl_waitThread(&Delay);
    }

    static void SAL_CALL yield()
    {
        osl_yieldThread();
    }

    virtual sal_Bool SAL_CALL schedule()
    {
        return osl_scheduleThread(m_hThread);
    }

    SAL_CALL operator oslThread() const
    {
        return m_hThread;
    }

protected:

    /** The thread functions calls the protected functions
        run and onTerminated.
    */
    friend void SAL_CALL threadFunc( void* param);

    virtual void SAL_CALL run() = 0;

    virtual void SAL_CALL onTerminated()
    {
    }

private:
    oslThread m_hThread;
};

extern "C" inline void SAL_CALL threadFunc( void* param)
{
        Thread* pObj= (Thread*)param;
        pObj->run();
        pObj->onTerminated();
}

class ThreadData
{
    ThreadData( const ThreadData& );
    ThreadData& operator= (const ThreadData& );
public:
     /// Create a thread specific local data key
    ThreadData( oslThreadKeyCallbackFunction pCallback= 0 )
    {
        m_hKey = osl_createThreadKey( pCallback );
    }

    /// Destroy a thread specific local data key
    ~ThreadData()
    {
           osl_destroyThreadKey(m_hKey);
    }

    /** Set the data associated with the data key.
        @returns True if operation was successfull
    */
    sal_Bool SAL_CALL setData(void *pData)
    {
           return (osl_setThreadKeyData(m_hKey, pData));
    }

    /** Get the data associated with the data key.
        @returns The data asscoitaed with the data key or
        NULL if no data was set
    */
    void* SAL_CALL getData()
    {
           return osl_getThreadKeyData(m_hKey);
    }

    operator oslThreadKey() const
    {
        return m_hKey;
    }

private:
    oslThreadKey m_hKey;
};

} // end namespace osl
#endif
#endif<commit_msg>Fixed use of SAL_THROW macro.<commit_after>/*************************************************************************
 *
 *  $RCSfile: thread.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mhu $ $Date: 2001-03-13 11:58:57 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _THREAD_HXX_
#define _THREAD_HXX_

#ifdef __cplusplus

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif

namespace osl
{
/** threadFunc is the function which is executed by the threads
    created by the osl::Thread class. The function's signature
    matches the one of oslWorkerFunction which is declared in
    osl/thread.h .
*/
extern "C" inline void SAL_CALL threadFunc( void* param);

class Thread
{
    Thread( const Thread& );
    Thread& operator= ( const Thread& );
public:
    // these are here to force memory de/allocation to sal lib.
    inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW (())
        { return ::rtl_allocateMemory( nSize ); }
    inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW (())
        { ::rtl_freeMemory( pMem ); }
    inline static void * SAL_CALL operator new( size_t, void * pMem ) SAL_THROW (())
        { return pMem; }
    inline static void SAL_CALL operator delete( void *, void * ) SAL_THROW (())
        {}

    Thread(): m_hThread(0){}

    virtual  ~Thread()
    {
        osl_destroyThread( m_hThread);
    }

    sal_Bool SAL_CALL create()
    {
        OSL_ASSERT(m_hThread == 0); // only one running thread per instance
           if (m_hThread)
            return sal_False;

        if (m_hThread= osl_createSuspendedThread( threadFunc,
                                             (void*)this))
            osl_resumeThread(m_hThread);

        return m_hThread != 0;
    }

    sal_Bool SAL_CALL createSuspended()
    {
        OSL_ASSERT(m_hThread == 0); // only one running thread per instance
        if( m_hThread)
            return sal_False;
        m_hThread= osl_createSuspendedThread( threadFunc,
                                             (void*)this);
        return m_hThread != 0;
    }

    virtual void SAL_CALL suspend()
    {
        osl_suspendThread(m_hThread);
    }

    virtual void SAL_CALL resume()
    {
        osl_resumeThread(m_hThread);
    }

    virtual void SAL_CALL terminate()
    {
        osl_terminateThread(m_hThread);
    }

    virtual void SAL_CALL join()
    {
        osl_joinWithThread(m_hThread);
    }

    sal_Bool SAL_CALL isRunning()
    {
        return m_hThread != 0 && osl_isThreadRunning(m_hThread);
    }

    void SAL_CALL setPriority( oslThreadPriority Priority)
    {
        osl_setThreadPriority(m_hThread, Priority);
    }

    oslThreadPriority SAL_CALL getPriority()
    {
        return osl_getThreadPriority(m_hThread);
    }

    oslThreadIdentifier SAL_CALL getIdentifier() const
    {
        return osl_getThreadIdentifier(m_hThread);
    }

    static oslThreadIdentifier SAL_CALL getCurrentIdentifier()
    {
        return osl_getThreadIdentifier(0);
    }

    virtual oslThreadSleep SAL_CALL sleep(const TimeValue& Delay)
    {
        return osl_sleepThread(m_hThread, &Delay);
    }

    virtual sal_Bool SAL_CALL awake()
    {
        return osl_awakeThread(m_hThread);
    }

    static void SAL_CALL wait(const TimeValue& Delay)
    {
        osl_waitThread(&Delay);
    }

    static void SAL_CALL yield()
    {
        osl_yieldThread();
    }

    virtual sal_Bool SAL_CALL schedule()
    {
        return osl_scheduleThread(m_hThread);
    }

    SAL_CALL operator oslThread() const
    {
        return m_hThread;
    }

protected:

    /** The thread functions calls the protected functions
        run and onTerminated.
    */
    friend void SAL_CALL threadFunc( void* param);

    virtual void SAL_CALL run() = 0;

    virtual void SAL_CALL onTerminated()
    {
    }

private:
    oslThread m_hThread;
};

extern "C" inline void SAL_CALL threadFunc( void* param)
{
        Thread* pObj= (Thread*)param;
        pObj->run();
        pObj->onTerminated();
}

class ThreadData
{
    ThreadData( const ThreadData& );
    ThreadData& operator= (const ThreadData& );
public:
     /// Create a thread specific local data key
    ThreadData( oslThreadKeyCallbackFunction pCallback= 0 )
    {
        m_hKey = osl_createThreadKey( pCallback );
    }

    /// Destroy a thread specific local data key
    ~ThreadData()
    {
           osl_destroyThreadKey(m_hKey);
    }

    /** Set the data associated with the data key.
        @returns True if operation was successfull
    */
    sal_Bool SAL_CALL setData(void *pData)
    {
           return (osl_setThreadKeyData(m_hKey, pData));
    }

    /** Get the data associated with the data key.
        @returns The data asscoitaed with the data key or
        NULL if no data was set
    */
    void* SAL_CALL getData()
    {
           return osl_getThreadKeyData(m_hKey);
    }

    operator oslThreadKey() const
    {
        return m_hKey;
    }

private:
    oslThreadKey m_hKey;
};

} // end namespace osl
#endif
#endif
<|endoftext|>


<commit_before><commit_msg>Drop the trailing white space crack<commit_after><|endoftext|>


<commit_before><commit_msg>coverity#1266485 Untrusted value as argument<commit_after><|endoftext|>


<commit_before><commit_msg>vcl: fix the MapMode ctor too to limit precision to 32 bits<commit_after><|endoftext|>


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

#include <testpp/test.h>
#include "default_output.h"

/**
 * Define tests
 */
testpp_suite_c parent_suite( "parent" );
testpp_suite_c simple_suite( "simple", parent_suite );
testpp_suite_c special_suite( "special", parent_suite );
testpp_suite_c assertion_suite( "assertion" );

/**
 * This is a sample test for using in tests.
 */
template < int N >
class test_sample
: public testpp_c
{
public:
	void test() { tested = true; }
	static bool tested;
};

template < int N >
bool test_sample< N >::tested = false;

class test_custom
: public testpp_c
{
public:
	void test()
	{
		assertpp( m_x ).t();
		assertpp( m_x ) == 5;
	}

	void setup()
	{
		m_x = 5;
	}

	void teardown()
	{
		m_x = 0;
	}

private:
	int m_x;
};
REGISTER_TESTPP( test_custom );
// REGISTER_SUITE_TESTPP( test_custom, parent_suite );

// expansion of what the TESTPP macro does
class simple_test : public testpp_c { void test(); };
/*
static testpp_runner_i simple_test_runner( new simple_test(), "simple_test"
		, __FILE__, __LINE__ );
		*/
void simple_test::test()
{
}

SUITE_TESTPP( test_equality_assertion, assertion_suite )
{
	int value( 5 );
	assertpp( value ) == 5;
}

TESTPP( test_equality_assertion_failure )
{
	int value( 5 );
	assertpp( value ) == 4;
}

TESTPP( test_inequality_assertion )
{
	int value( 5 );
	assertpp( value ) != 4;
}

TESTPP( test_inequality_assertion_failure )
{
	int value( 5 );
	assertpp( value ) != 5;
}

TESTPP( test_string_equality_assertion )
{
	std::string value( "hello" );
	assertpp( value ) == "hello";
}

/**
 * Test the static is_before() function when the result should be true.
 */
TESTPP( test_is_before_yes )
{
	assertpp( testpp_c::is_before( 2030, 12, 28 ) ).t();
}

/**
 * Test the static is_before() function when the result should be false.
 */
TESTPP( test_is_before_no )
{
	assertpp( testpp_c::is_before( 2004, 7, 24 ) ).f();
}

TESTPP( test_suite_match )
{
	testpp_suite_c suite( "special" );
	assertpp( suite.match( "special" ) ).t();
}

TESTPP( test_parent_suite_match )
{
	testpp_suite_c parent( "parent" );
	testpp_suite_c suite( "special", parent );
	assertpp( suite.match( "parent" ) ).t();
}

TESTPP( test_duplicate_runner )
{
	/*
	can't run these b/c they alter the list of runners.  need to fix this.
	testpp_runner_c< test_duplicate_runner > runner( "tst_runner_in_suite"
			, __FILE__, __LINE__ );
	assertpp( runner.in_suite( "simple" ) ).f();
	*/
}

TESTPP( test_runner_in_suite )
{
	/*
	can't run these b/c they alter the list of runners.  need to fix this.
	testpp_runner_c< test_runner_in_suite > runner( "tst_runner_in_suite"
			, simple_suite, __FILE__, __LINE__ );
	assertpp( runner.in_suite( "simple" ) ).t();
	*/
}

/**
 * Test that the testpp_set constructor works and defaults values properly.
 */
TESTPP( test_testpp_set_constructor )
{
	testpp_set_c set;

	assertpp( set.test_files().empty() ).t();
	assertpp( set.test_suites().empty() ).t();
}

/**
 * Test that adding tests to the testpp_set works and the test_files
 * and test_suites work better.
 */
TESTPP( test_testpp_set_add_tests )
{
	testpp_set_c set;
	human_testpp_output_c output;
	std::ostringstream stream;
	output.set_stream( stream );

	set.add< test_sample< 1 > >( "sample1", "file1.cpp", 118 );
	set.add< test_sample< 2 > >( "sample2", "file2.cpp", 120 );

	assertpp( set.test_files().size() ) == 2;
	assertpp( set.test_suites().size() ) == 0;

	set.run( output );

	assertpp( test_sample< 1 >::tested ).t();
	assertpp( test_sample< 2 >::tested ).t();
}

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

#include <testpp/test.h>
#include "default_output.h"

/**
 * Define tests
 */
testpp_suite_c parent_suite( "parent" );
testpp_suite_c simple_suite( "simple", parent_suite );
testpp_suite_c special_suite( "special", parent_suite );
testpp_suite_c assertion_suite( "assertion" );

/**
 * This is a sample test for using in tests.
 */
template < int N >
class test_sample
: public testpp_c
{
public:
	void test() { tested = true; }
	static bool tested;
};

template < int N >
bool test_sample< N >::tested = false;

class test_custom
: public testpp_c
{
public:
	void test()
	{
		assertpp( m_x ).t();
		assertpp( m_x ) == 5;
	}

	void setup()
	{
		m_x = 5;
	}

	void teardown()
	{
		m_x = 0;
	}

private:
	int m_x;
};
REGISTER_TESTPP( test_custom );
// REGISTER_SUITE_TESTPP( test_custom, parent_suite );

// expansion of what the TESTPP macro does
class simple_test : public testpp_c { void test(); };
/*
static testpp_runner_i simple_test_runner( new simple_test(), "simple_test"
		, __FILE__, __LINE__ );
		*/
void simple_test::test()
{
}

SUITE_TESTPP( test_equality_assertion, assertion_suite )
{
	int value( 5 );
	assertpp( value ) == 5;
}

TESTPP( test_equality_assertion_failure )
{
	int value( 5 );
	assertpp( value ) == 4;
}

TESTPP( test_inequality_assertion )
{
	int value( 5 );
	assertpp( value ) != 4;
}

TESTPP( test_inequality_assertion_failure )
{
	int value( 5 );
	assertpp( value ) != 5;
}

TESTPP( test_string_equality_assertion )
{
	std::string value( "hello" );
	assertpp( value ) == "hello";
}

/**
 * Test the static is_before() function when the result should be true.
 */
TESTPP( test_is_before_yes )
{
	assertpp( testpp_c::is_before( 2030, 12, 28 ) ).t();
}

/**
 * Test the static is_before() function when the result should be false.
 */
TESTPP( test_is_before_no )
{
	assertpp( testpp_c::is_before( 2004, 7, 24 ) ).f();
}

/**
 * Exercise the ignore_until function.  Doesn't actually assert anything,
 * just gets it used in the testpp tests.
 */
TESTPP( test_use_ignore_until )
{
	ignore_until( 2030, 12, 29 );
}

/**
 * Exercise the not_implemented function.  Doesn't actually assert
 * anything.
 */
TESTPP( test_use_not_implemented )
{
	not_implemented();
}

/**
 * Exercise the not_implemented (until) funciton.  Verify what happens
 * when it's still before the not implemented date.
 */
TESTPP( test_use_not_implemented_until )
{
	not_implemented( 2030, 12, 29 );
}

TESTPP( test_suite_match )
{
	testpp_suite_c suite( "special" );
	assertpp( suite.match( "special" ) ).t();
}

TESTPP( test_parent_suite_match )
{
	testpp_suite_c parent( "parent" );
	testpp_suite_c suite( "special", parent );
	assertpp( suite.match( "parent" ) ).t();
}

TESTPP( test_duplicate_runner )
{
	/*
	can't run these b/c they alter the list of runners.  need to fix this.
	testpp_runner_c< test_duplicate_runner > runner( "tst_runner_in_suite"
			, __FILE__, __LINE__ );
	assertpp( runner.in_suite( "simple" ) ).f();
	*/
}

TESTPP( test_runner_in_suite )
{
	/*
	can't run these b/c they alter the list of runners.  need to fix this.
	testpp_runner_c< test_runner_in_suite > runner( "tst_runner_in_suite"
			, simple_suite, __FILE__, __LINE__ );
	assertpp( runner.in_suite( "simple" ) ).t();
	*/
}

/**
 * Test that the testpp_set constructor works and defaults values properly.
 */
TESTPP( test_testpp_set_constructor )
{
	testpp_set_c set;

	assertpp( set.test_files().empty() ).t();
	assertpp( set.test_suites().empty() ).t();
}

/**
 * Test that adding tests to the testpp_set works and the test_files
 * and test_suites work better.
 */
TESTPP( test_testpp_set_add_tests )
{
	testpp_set_c set;
	human_testpp_output_c output;
	std::ostringstream stream;
	output.set_stream( stream );

	set.add< test_sample< 1 > >( "sample1", "file1.cpp", 118 );
	set.add< test_sample< 2 > >( "sample2", "file2.cpp", 120 );

	assertpp( set.test_files().size() ) == 2;
	assertpp( set.test_suites().size() ) == 0;

	set.run( output );

	assertpp( test_sample< 1 >::tested ).t();
	assertpp( test_sample< 2 >::tested ).t();
}

<|endoftext|>


<commit_before>// *******************************************************************
//   (C) Copyright 2015 Leiden Institute of Advanced Computer Science
//   Universiteit Leiden
//   All Rights Reserved
// *******************************************************************
// Sandbox (testing playground)
// *******************************************************************
// FILE INFORMATION:
//   File:     sandbox.cc
//   Author:   Jonathan K. Vis
//   Revision: 1.0.0
//   Date:     2015/03/02
// *******************************************************************
// DESCRIPTION:
//  General testing playground: protein frame shift construction code.
// *******************************************************************

#include <cstdio>
#include <cstdlib>

typedef char char_t;

#include <map>

static unsigned int const FRAME_SHIFT_0            = 0x00;
static unsigned int const FRAME_SHIFT_1            = 0x01;
static unsigned int const FRAME_SHIFT_2            = 0x02;
static unsigned int const FRAME_SHIFT_REVERSE_IDEM = 0x04;
static unsigned int const FRAME_SHIFT_REVERSE_1    = 0x08;
static unsigned int const FRAME_SHIFT_REVERSE_2    = 0x10;

static char_t const* const codon_string = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF";

static char_t const IUPAC_BASE[4] =
{
  'A',
  'C',
  'G',
  'T'
}; // IUPAC_BASE

char_t codon_table[64] = {'\0'};
std::multimap<char_t const, unsigned int const> codon_map;

unsigned int frame_shift(char_t const reference, char_t const sample_1, char_t const sample_2)
{
  std::pair<std::multimap<char_t const, unsigned int const>::const_iterator, std::multimap<char_t const, unsigned int const>::const_iterator> const range_1 = codon_map.equal_range(sample_1);
  std::pair<std::multimap<char_t const, unsigned int const>::const_iterator, std::multimap<char_t const, unsigned int const>::const_iterator> const range_2 = codon_map.equal_range(sample_2);

  unsigned int shift = FRAME_SHIFT_0;
  for (std::multimap<char_t const, unsigned int const>::const_iterator it_1 = range_1.first; it_1 != range_1.second; ++it_1)
  {
    for (std::multimap<char_t const, unsigned int const>::const_iterator it_2 = range_2.first; it_2 != range_2.second; ++it_2)
    {
      const unsigned int codon_1 = ((it_1->second << 0x2) | (it_2->second >> 0x4)) & 0x3f;
      const unsigned int codon_2 = ((it_1->second << 0x4) | (it_2->second >> 0x2)) & 0x3f;
      if (reference == codon_table[codon_1])
      {
        shift |= FRAME_SHIFT_1;
      } // if
      if (reference == codon_table[codon_2])
      {
        shift |= FRAME_SHIFT_2;
      } // if
      if (shift == (FRAME_SHIFT_1 | FRAME_SHIFT_2))
      {
        return shift;
      } // if
      printf("%d %d -> %d %d\n", it_1->second, it_2->second, codon_1, codon_2);
    } // for
  } // for
  return shift;
} // frame_shift

void print_codon(unsigned int const index)
{
  printf("%c%c%c", IUPAC_BASE[index >> 0x4], IUPAC_BASE[(index >> 0x2) & 0x3], IUPAC_BASE[index & 0x3]);
} // print_codon

unsigned int reverse_complement(unsigned int const index)
{
  return (~((index >> 0x4) | (((index >> 0x2) & 0x3) << 2) | ((index & 0x3) << 0x4)) & 0x3f);
} // reverse_complement

unsigned int frame_shift_reverse(char_t const reference, char_t const sample_1)
{
  std::pair<std::multimap<char_t const, unsigned int const>::const_iterator, std::multimap<char_t const, unsigned int const>::const_iterator> const range_1 = codon_map.equal_range(sample_1);

  unsigned int shift = FRAME_SHIFT_0;
  for (std::multimap<char_t const, unsigned int const>::const_iterator it_1 = range_1.first; it_1 != range_1.second; ++it_1)
  {
    if (reference == codon_table[reverse_complement(it_1->second)])
    {
      shift |= FRAME_SHIFT_REVERSE_IDEM;
    } // if
  } // for
  return shift;
} // frame_shift_reverse

int main(int, char* [])
{
  for (unsigned int i = 0; i < 64; ++i)
  {
    codon_table[i] = codon_string[i];
    codon_map.insert(std::pair<char_t const, unsigned int const>(codon_table[i], i));
  } // for

  unsigned int const shift = frame_shift_reverse('D', 'V');
  printf("%d\n", shift);
  return 0;
} // main

<commit_msg>Adding reverse frame shift matching<commit_after>#include <cstdio>

typedef char char_t;
typedef unsigned long long uint64_t;

static unsigned int const FRAME_SHIFT_NONE      = 0x00;
static unsigned int const FRAME_SHIFT_1         = 0x01;
static unsigned int const FRAME_SHIFT_2         = 0x02;
static unsigned int const FRAME_SHIFT_REVERSE   = 0x04;
static unsigned int const FRAME_SHIFT_REVERSE_1 = 0x08;
static unsigned int const FRAME_SHIFT_REVERSE_2 = 0x10;

// default codon string
char_t const* const CODON_STRING = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF";

char_t const IUPAC_BASE[4] =
{
  'A',
  'C',
  'G',
  'T'
}; // IUPAC_BASE

// bitstrings with ASCII index: for each acid (as ASCII value) which
// codons are coding for it (64 bits: 1 is coding)
static uint64_t acid_map[128]   = {0x0};
// for each codon what is the corresponding acid (as ASCII value)
static   char_t codon_table[64] = {'\0'};

void print_codon(FILE*stream, unsigned int const index)
{
  fprintf(stream, "%c%c%c", IUPAC_BASE[index >> 0x4],
                            IUPAC_BASE[(index >> 0x2) & 0x3],
                            IUPAC_BASE[index & 0x3]);
  return;
} // print_codon

void print_mapping(FILE* stream)
{
  for (unsigned int i = 0; i < 128; ++i)
  {
    if (acid_map[i] != 0x0)
    {
      fprintf(stream, "%c: ", static_cast<char_t>(i));
      for (unsigned int j = 0; j < 64; ++j)
      {
        if (((acid_map[i] >> j) & 0x1) == 0x1)
        {
          print_codon(stream, j);
          fprintf(stream, " (%d) ", j);
        } // if
      } // for
      fprintf(stream, "\n");
    } // if
  } // for
  for (unsigned int i = 0; i < 64; ++i)
  {
    print_codon(stream, i);
    fprintf(stream, " (%d): %c\n", i, codon_table[i]);
  } // for
  return;
} // print_mapping

// calculate all possible forwards frame shifts: find the sample codon
// in the combination of the two reference condons
unsigned int frame_shift_forward(char_t const reference_1,
                                 char_t const reference_2,
                                 char_t const sample)
{
  unsigned int shift = FRAME_SHIFT_NONE;
  for (unsigned int i = 0; i < 64; ++i)
  {
    // i-th bit set: so i-th codon is coding for this
    // acid (reference_1)
    if (((acid_map[static_cast<unsigned int>(reference_1)] >> i) & 0x1) == 0x1)
    {
      for (unsigned int j = 0; j < 64; ++j)
      {
        // j-th bit set: so j-th codon is coding for this
        // acid (reference_2)
        if (((acid_map[static_cast<unsigned int>(reference_2)] >> j) & 0x1) == 0x1)
        {
          // calculate the two frame shifted codons with the reference
          // codons.
          // codon_1 last two bases of reference_1 concat with first
          // base of reference_2
          unsigned int const codon_1 = ((i & 0xf) << 0x2) | (j >> 0x4);
          // codon_2 last base of reference_1 concat with first two
          // bases of reference_2
          unsigned int const codon_2 = ((i & 0x3) << 0x4) | ((j & 0x3c) >> 0x2);

          for (unsigned int k = 0; k < 64; ++k)
          {
            // k-th bit set: so k-th codon is coding for this
            // acid (sample)
            if (((acid_map[static_cast<unsigned int>(sample)] >> k) & 0x1) == 0x1)
            {
              if (codon_1 == k)
              {
                shift |= FRAME_SHIFT_2;
              } // if
              if (codon_2 == k)
              {
                shift |= FRAME_SHIFT_1;
              } // if
              if (shift == (FRAME_SHIFT_1 | FRAME_SHIFT_2))
              {
                //return shift;
              } // if
            } // if
          } // for
        } // if
      } // for
    } // if
  } // for
  return shift;
} // frame_shift_forward

// calculate all possible reverse frame shifts: find the sample codon
// in the combination of the (two) reference condon(s)
unsigned int frame_shift_reverse(char_t const reference_1,
                                 char_t const reference_2,
                                 char_t const sample)
{
  unsigned int shift = FRAME_SHIFT_NONE;
  for (unsigned int i = 0; i < 64; ++i)
  {
    // i-th bit set: so i-th codon is coding for this
    // acid (reference_1)
    if (((acid_map[static_cast<unsigned int>(reference_1)] >> i) & 0x1) == 0x1)
    {
      // reverse complement codon
      unsigned int const codon_0 = ((i >> 0x4) | (i & 0xc) | ((i & 0x3) << 0x4)) ^ 0x3f;
      for (unsigned int j = 0; j < 64; ++j)
      {
        // j-th bit set: so j-th codon is coding for this
        // acid (reference_2)
        if (((acid_map[static_cast<unsigned int>(reference_2)] >> j) & 0x1) == 0x1)
        {
          unsigned int const codon_1 = ((i >> 0x4) | (i & 0xc) | ((j & 0x3) << 0x4)) ^ 0x3f;
          unsigned int const codon_2 = ((i >> 0x4) | ((j & 0x30) >> 0x2) | ((j & 0x3) << 0x4)) ^ 0x3f;
          for (unsigned int k = 0; k < 64; ++k)
          {
            // k-th bit set: so k-th codon is coding for this
            // acid (sample)
            if (((acid_map[static_cast<unsigned int>(sample)] >> k) & 0x1) == 0x1)
            {
              print_codon(stdout, codon_0);
              printf(" ");
              print_codon(stdout, codon_1);
              printf(" ");
              print_codon(stdout, codon_2);
              printf(" -- ");
              print_codon(stdout, k);
              printf("\n");
              if (codon_0 == k)
              {
                shift |= FRAME_SHIFT_REVERSE;
              } // if
              if (codon_1 == k)
              {
                shift |= FRAME_SHIFT_REVERSE_2;
              } // if
              if (codon_2 == k)
              {
                shift |= FRAME_SHIFT_REVERSE_1;
              } // if
              if (shift == (FRAME_SHIFT_REVERSE | FRAME_SHIFT_REVERSE_1 | FRAME_SHIFT_REVERSE_2))
              {
                //return shift;
              } // if
            } // if
          } // for
        } // if
      } // for
    } // if
  } // for
  return shift;
} // frame_shift_reverse

// entry point
int main(int, char* [])
{
  // initialize acid_map and codon_map: assume CODON_STRING holds at
  // least 64 ASCII characters (from the lower 127)
  for (unsigned int i = 0; i < 64; ++i)
  {
    // update bitstring: set i-th bit
    acid_map[CODON_STRING[i] & 0x7f] |= (0x1ll << i);
    // update codon table
    codon_table[i] = CODON_STRING[i];
  } // for

  printf("frame shift (forward) = %d\n", frame_shift_forward('D', 'Y', 'L'));
  printf("frame shift (reverse) = %d\n", frame_shift_reverse('L', 'S', 'Q'));

  return 0;
} // main

<|endoftext|>


<commit_before>#include <iostream>
#include <ctime>
#include "server.hpp"

int main(int argc, char* argv[])
{
	uv_loop_t* loop = uv_default_loop();
	net::tcp_server a(loop);

	a.set_read_cb([](net::server_socket* tcp){
			size_t len = tcp->input()->size();
			std::cout << "server revc " << len << std::endl;
			//tcp->input()->debug(buffer::debug_type::chars);
			tcp->output()->append(*(tcp->input()));
			tcp->input()->clear();
	});

	a.set_connection_cb([](net::server_socket* tcp){
			std::cout << "server accept connection :" << tcp->id() << std::endl;
	});

	a.set_close_cb([](net::server_socket* tcp){
			std::cout << "server disconnect connection :" << tcp->id() << std::endl;
	});

	char ip[] = "127.0.0.1";
	bool result = a.listen(ip, 5000);
	std::cout << "listen result " << result << std::endl;

	uv_run(loop, UV_RUN_DEFAULT);
	return 0;
}
<commit_msg>update to lastest buffer<commit_after>#include <iostream>
#include <ctime>
#include "server.hpp"

int main(int argc, char* argv[])
{
	uv_loop_t* loop = uv_default_loop();
	net::tcp_server a(loop);

	a.set_read_cb([](net::server_socket* tcp){
			size_t len = tcp->input()->size();
			std::cout << "server revc " << len << std::endl;
			//tcp->input()->debug(buffer::debug_type::chars);
			tcp->output()->write(*(tcp->input()));
	});

	a.set_connection_cb([](net::server_socket* tcp){
			std::cout << "server accept connection :" << tcp->id() << std::endl;
	});

	a.set_close_cb([](net::server_socket* tcp){
			std::cout << "server disconnect connection :" << tcp->id() << std::endl;
	});

	char ip[] = "127.0.0.1";
	bool result = a.listen(ip, 5000);
	std::cout << "listen result " << result << std::endl;

	uv_run(loop, UV_RUN_DEFAULT);
	return 0;
}
<|endoftext|>


<commit_before>/**
 * datamanager.tcc -
 * @author: Jonathan Beard
 * @version: Tue Oct 14 14:15:00 2014
 *
 * Copyright 2014 Jonathan Beard
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef _DATAMANAGER_TCC_
#define _DATAMANAGER_TCC_  1
#include <cassert>
#include <cstddef>
#include <array>
#include <mutex>
#include <thread>
#include <queue>

#include "ringbuffertypes.hpp"
#include "bufferdata.tcc"

namespace dm{
enum access_key : int { allocate = 0, allocate_range, push,
                        recycle, pop, peek, size, N };
}

template < class T,
           Type::RingBufferType B,
           size_t SIZE = 0 > class DataManager
{
public:

   DataManager( ) = default;

   void set( Buffer::Data< T, B > *buffer )
   {
      assert( buffer != nullptr );
      buffer_a = buffer;
      buffer_b = buffer;
   }

   void resize( Buffer::Data< T, B > *new_buffer )
   {
      for(;;)
      {
         resizing = true;
         if( ! (volatile bool) flag.any() )
         {
            break;
         }
      }
      /** nobody should have outstanding references to the old buff **/
      Buffer::Data< T, B > *old_buffer( (this)->get() );
      new_buffer->copyFrom( old_buffer );
      (this)->set( new_buffer );
      delete( old_buffer );
      resizing = false;
   }

   auto get() noexcept -> Buffer::Data< T, B >*
   {
      struct Copy
      {
         Copy( Buffer::Data< T, B > *a, Buffer::Data< T, B > *b ) : a( a ),
                                                                    b( b )
         {
         }
         Buffer::Data< T, B > *a = nullptr;
         Buffer::Data< T, B > *b = nullptr;
      } copy( buffer_a, buffer_b );
      while( copy.a != copy.b )
      {
         copy.a = buffer_a;
         copy.b = buffer_b;
      }
      return( copy.a );
   }

   void  enterBuffer( dm::access_key key ) noexcept
   {
      flag[ (std::size_t) key ] = true;
   }

   void exitBuffer( dm::access_key key ) noexcept
   {
      flag[ (std::size_t) key ] = false;
   }

   volatile bool notResizing() noexcept
   {
      return( ! resizing );
   }

private:
   Buffer::Data< T, B > *buffer_b            = (Buffer::Data< T, B >*)0;
   Buffer::Data< T, B > *buffer_a            = (Buffer::Data< T, B >*)1;

   volatile bool                    resizing = false;
   std::bitset< dm::access_key::N > flag;
};
#endif /* END _DATAMANAGER_TCC_ */
<commit_msg>updates<commit_after>/**
 * datamanager.tcc -
 * @author: Jonathan Beard
 * @version: Tue Oct 14 14:15:00 2014
 *
 * Copyright 2014 Jonathan Beard
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef _DATAMANAGER_TCC_
#define _DATAMANAGER_TCC_  1
#include <cassert>
#include <cstddef>
#include <array>
#include <mutex>
#include <thread>
#include <bitset>

#include "ringbuffertypes.hpp"
#include "bufferdata.tcc"

namespace dm{
enum access_key : int { allocate = 0, allocate_range, push,
                        recycle, pop, peek, size, N };
}

template < class T,
           Type::RingBufferType B,
           size_t SIZE = 0 > class DataManager
{
public:

   DataManager( ) = default;

   void set( Buffer::Data< T, B > *buffer )
   {
      assert( buffer != nullptr );
      buffer_a = buffer;
      buffer_b = buffer;
   }

   void resize( Buffer::Data< T, B > *new_buffer )
   {
      for(;;)
      {
         resizing = true;
         if( ! (volatile bool) flag.any() )
         {
            break;
         }
      }
      /** nobody should have outstanding references to the old buff **/
      Buffer::Data< T, B > *old_buffer( (this)->get() );
      new_buffer->copyFrom( old_buffer );
      (this)->set( new_buffer );
      delete( old_buffer );
      resizing = false;
   }

   auto get() noexcept -> Buffer::Data< T, B >*
   {
      struct Copy
      {
         Copy( Buffer::Data< T, B > *a, Buffer::Data< T, B > *b ) : a( a ),
                                                                    b( b )
         {
         }
         Buffer::Data< T, B > *a = nullptr;
         Buffer::Data< T, B > *b = nullptr;
      } copy( buffer_a, buffer_b );
      while( copy.a != copy.b )
      {
         copy.a = buffer_a;
         copy.b = buffer_b;
      }
      return( copy.a );
   }

   void  enterBuffer( dm::access_key key ) noexcept
   {
      flag[ (std::size_t) key ] = true;
   }

   void exitBuffer( dm::access_key key ) noexcept
   {
      flag[ (std::size_t) key ] = false;
   }

   volatile bool notResizing() noexcept
   {
      return( ! resizing );
   }

private:
   Buffer::Data< T, B > *buffer_b            = (Buffer::Data< T, B >*)0;
   Buffer::Data< T, B > *buffer_a            = (Buffer::Data< T, B >*)1;

   volatile bool                    resizing = false;
   std::bitset< dm::access_key::N > flag;
};
#endif /* END _DATAMANAGER_TCC_ */
<|endoftext|>


<commit_before>/*
    Copyright (C) 1998,2000 by Jorrit Tyberghein
    Largely rewritten by Ivan Avramovic <ivan@avramovic.com>

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <math.h>
#include "sysdef.h"
#include "csgeom/math2d.h"
#include "csgeom/box.h"
#include "csgeom/poly2d.h"

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

// This algorithm assumes that the polygon is convex and that
// the vertices of the polygon are oriented in clockwise ordering.
// If this was not the case then the polygon should not be drawn (culled)
// and this routine would not be called for it.
int csMath2::InPoly2D (const csVector2& v,
                       csVector2* P, int n, csBox2* bounding_box)
{
  if (!bounding_box->In (v.x, v.y)) return CS_POLY_OUT;
  int i, i1;
  int side;
  i1 = n-1;
  for (i = 0 ; i < n ; i++)
  {
    // If this vertex is left of the polygon edge we are outside the polygon.
    side = WhichSide2D (v, P[i1], P[i]);
    if (side < 0) return CS_POLY_OUT;
    else if (side == 0) return CS_POLY_ON;
    i1 = i;
  }
  return CS_POLY_IN;
}

bool csMath2::PlanesClose (const csPlane2& p1, const csPlane2& p2)
{
  if (PlanesEqual (p1, p2)) return true;
  csPlane2 p1n = p1; p1n.Normalize ();
  csPlane2 p2n = p2; p2n.Normalize ();
  return PlanesEqual (p1n, p2n);
}

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

bool csIntersect2::IntersectPolygon (const csPlane2& plane,
	csPoly2D* poly, csSegment2& seg)
{
  csVector2& v1 = seg.Start ();
  csVector2& v2 = seg.End ();
  int i, i1;
  float c, c1;
  csVector2 isect;
  float dist;
  i1 = poly->GetNumVertices ()-1;
  c1 = plane.Classify ((*poly)[i1]);
  bool found_v1 = false;
  bool found_v2 = false;
  for (i = 0 ; i < poly->GetNumVertices () ; i++)
  {
    c = plane.Classify ((*poly)[i]);
    if ((c < 0 && c1 > 0) || (c1 < 0 && c > 0))
    {
      csIntersect2::Plane ((*poly)[i1], (*poly)[i],
      	  plane, isect, dist);
      if (!found_v1) { v1 = isect; found_v1 = true; }
      else { v2 = isect; found_v2 = true; break; }
    }

    i1 = i;
    c1 = c;
  }
  if (!found_v1) return false;
  if (!found_v2) v2 = v1;
  return true;
}

bool csIntersect2::Segments (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect, float& dist)
{
  float denom;
  float r, s;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

//            (Ya1-Yb1)(Xb2-Xb1)-(Xa1-Xb1)(Yb2-Yb1)
//        r = -------------------------------------  (eqn 1)
//            (Xa2-Xa1)(Yb2-Yb1)-(Ya2-Ya1)(Xb2-Xb1)
//
//            (Ya1-Yb1)(Xa2-Xa1)-(Xa1-Xb1)(Ya2-Ya1)
//        s = -------------------------------------  (eqn 2)
//            (Xa2-Xa1)(Yb2-Yb1)-(Ya2-Ya1)(Xb2-Xb1)

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  r = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;
  s = ((a1.y-b1.y)*(a2.x-a1.x) - (a1.x-b1.x)*(a2.y-a1.y)) / denom;
  dist = r;

  if ( ( r < -SMALL_EPSILON || r > 1+SMALL_EPSILON ) ||
       ( s < -SMALL_EPSILON || s > 1+SMALL_EPSILON ) ) return false;

  isect.x = a1.x + dist*(a2.x-a1.x);
  isect.y = a1.y + dist*(a2.y-a1.y);

  return true;
}

bool csIntersect2::SegmentLine (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect, float& dist)
{
  float denom;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  dist = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;
  if ( dist < -SMALL_EPSILON || dist > 1+SMALL_EPSILON ) return false;

  isect.x = a1.x + dist*(a2.x-a1.x);
  isect.y = a1.y + dist*(a2.y-a1.y);

  return true;
}

bool csIntersect2::Lines (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect)
{
  float denom, r;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  r = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;

  isect.x = a1.x + r*(a2.x-a1.x);
  isect.y = a1.y + r*(a2.y-a1.y);

  return true;
}

bool csIntersect2::Plane (const csVector2& u, const csVector2& v,
                          const csPlane2& p, csVector2& isect, float& dist)
{
  float x,y, denom;

  x = v.x-u.x;  y = v.y-u.y;
  denom = p.norm.x*x + p.norm.y*y;
  if (ABS (denom) < SMALL_EPSILON) return false; // they are parallel

  dist = -(p.norm*u + p.CC) / denom;
  if (dist < -SMALL_EPSILON || dist > 1+SMALL_EPSILON) return false;

  isect.x = u.x + dist*x;  isect.y = u.y + dist*y;
  return true;
}

static bool csIntersect2::Planes (const csPlane2& p1, const csPlane2& p2,
                    csVector2& isect)
{
  // p1: A1x+B1y+C1 = 0
  // p2: A2x+B2y+C2 = 0
//@@@@@@@@@@@@@@@@@@@@@ TO BE IMPLEMENTED!
  CRASH;
  return false;
}

//---------------------------------------------------------------------------
<commit_msg>Fixed a compilation error.<commit_after>/*
    Copyright (C) 1998,2000 by Jorrit Tyberghein
    Largely rewritten by Ivan Avramovic <ivan@avramovic.com>

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <math.h>
#include "sysdef.h"
#include "csgeom/math2d.h"
#include "csgeom/box.h"
#include "csgeom/poly2d.h"

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

// This algorithm assumes that the polygon is convex and that
// the vertices of the polygon are oriented in clockwise ordering.
// If this was not the case then the polygon should not be drawn (culled)
// and this routine would not be called for it.
int csMath2::InPoly2D (const csVector2& v,
                       csVector2* P, int n, csBox2* bounding_box)
{
  if (!bounding_box->In (v.x, v.y)) return CS_POLY_OUT;
  int i, i1;
  int side;
  i1 = n-1;
  for (i = 0 ; i < n ; i++)
  {
    // If this vertex is left of the polygon edge we are outside the polygon.
    side = WhichSide2D (v, P[i1], P[i]);
    if (side < 0) return CS_POLY_OUT;
    else if (side == 0) return CS_POLY_ON;
    i1 = i;
  }
  return CS_POLY_IN;
}

bool csMath2::PlanesClose (const csPlane2& p1, const csPlane2& p2)
{
  if (PlanesEqual (p1, p2)) return true;
  csPlane2 p1n = p1; p1n.Normalize ();
  csPlane2 p2n = p2; p2n.Normalize ();
  return PlanesEqual (p1n, p2n);
}

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

bool csIntersect2::IntersectPolygon (const csPlane2& plane,
	csPoly2D* poly, csSegment2& seg)
{
  csVector2& v1 = seg.Start ();
  csVector2& v2 = seg.End ();
  int i, i1;
  float c, c1;
  csVector2 isect;
  float dist;
  i1 = poly->GetNumVertices ()-1;
  c1 = plane.Classify ((*poly)[i1]);
  bool found_v1 = false;
  bool found_v2 = false;
  for (i = 0 ; i < poly->GetNumVertices () ; i++)
  {
    c = plane.Classify ((*poly)[i]);
    if ((c < 0 && c1 > 0) || (c1 < 0 && c > 0))
    {
      csIntersect2::Plane ((*poly)[i1], (*poly)[i],
      	  plane, isect, dist);
      if (!found_v1) { v1 = isect; found_v1 = true; }
      else { v2 = isect; found_v2 = true; break; }
    }

    i1 = i;
    c1 = c;
  }
  if (!found_v1) return false;
  if (!found_v2) v2 = v1;
  return true;
}

bool csIntersect2::Segments (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect, float& dist)
{
  float denom;
  float r, s;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

//            (Ya1-Yb1)(Xb2-Xb1)-(Xa1-Xb1)(Yb2-Yb1)
//        r = -------------------------------------  (eqn 1)
//            (Xa2-Xa1)(Yb2-Yb1)-(Ya2-Ya1)(Xb2-Xb1)
//
//            (Ya1-Yb1)(Xa2-Xa1)-(Xa1-Xb1)(Ya2-Ya1)
//        s = -------------------------------------  (eqn 2)
//            (Xa2-Xa1)(Yb2-Yb1)-(Ya2-Ya1)(Xb2-Xb1)

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  r = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;
  s = ((a1.y-b1.y)*(a2.x-a1.x) - (a1.x-b1.x)*(a2.y-a1.y)) / denom;
  dist = r;

  if ( ( r < -SMALL_EPSILON || r > 1+SMALL_EPSILON ) ||
       ( s < -SMALL_EPSILON || s > 1+SMALL_EPSILON ) ) return false;

  isect.x = a1.x + dist*(a2.x-a1.x);
  isect.y = a1.y + dist*(a2.y-a1.y);

  return true;
}

bool csIntersect2::SegmentLine (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect, float& dist)
{
  float denom;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  dist = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;
  if ( dist < -SMALL_EPSILON || dist > 1+SMALL_EPSILON ) return false;

  isect.x = a1.x + dist*(a2.x-a1.x);
  isect.y = a1.y + dist*(a2.y-a1.y);

  return true;
}

bool csIntersect2::Lines (
  const csSegment2& a, const csSegment2& b,
  csVector2& isect)
{
  float denom, r;
  const csVector2& a1 = a.Start ();
  const csVector2& a2 = a.End ();
  const csVector2& b1 = b.Start ();
  const csVector2& b2 = b.End ();

  denom = (a2.x-a1.x)*(b2.y-b1.y) - (a2.y-a1.y)*(b2.x-b1.x);
  if (ABS (denom) < EPSILON) return false;

  r = ((a1.y-b1.y)*(b2.x-b1.x) - (a1.x-b1.x)*(b2.y-b1.y)) / denom;

  isect.x = a1.x + r*(a2.x-a1.x);
  isect.y = a1.y + r*(a2.y-a1.y);

  return true;
}

bool csIntersect2::Plane (const csVector2& u, const csVector2& v,
                          const csPlane2& p, csVector2& isect, float& dist)
{
  float x,y, denom;

  x = v.x-u.x;  y = v.y-u.y;
  denom = p.norm.x*x + p.norm.y*y;
  if (ABS (denom) < SMALL_EPSILON) return false; // they are parallel

  dist = -(p.norm*u + p.CC) / denom;
  if (dist < -SMALL_EPSILON || dist > 1+SMALL_EPSILON) return false;

  isect.x = u.x + dist*x;  isect.y = u.y + dist*y;
  return true;
}

bool csIntersect2::Planes (const csPlane2& p1, const csPlane2& p2,
                    csVector2& isect)
{
  // p1: A1x+B1y+C1 = 0
  // p2: A2x+B2y+C2 = 0
//@@@@@@@@@@@@@@@@@@@@@ TO BE IMPLEMENTED!
  CRASH;
  return false;
}

//---------------------------------------------------------------------------
<|endoftext|>


<commit_before>/**
 * @file   Logger.cpp
 * @brief  Logger class implementation.
 * @author zer0
 * @date   2017-04-13
 * @date   2019-07-02 (Move namespace: log/mgr -> log)
 */

#include <libtbag/log/Logger.hpp>
#include <cassert>
#include <cstring>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace log {

Logger::Logger(std::string const & name,
               SharedSink const & sink,
               SharedGenerator const & generator,
               int level,
               bool auto_flush)
        : NAME(name), _sink(sink), _generator(generator), _level(level), _auto_flush(auto_flush)
{
    assert(static_cast<bool>(_sink));
}

Logger::~Logger()
{
    _sink->flush();
    _sink.reset();
    _generator.reset();
}

void Logger::flush() const
{
    assert(static_cast<bool>(_sink));
    _sink->flush();
}

bool Logger::write(int level, char const * level_name, char const * message, int size) const
{
    if (youShallNotPass(level)) {
        return true;
    }
    if (!_sink) {
        return false;
    }

    assert(level_name != nullptr);
    assert(message != nullptr);
    assert(size >= 1);

    char buffer[Generator::STACK_BUFFER_SIZE];
    int write_buffer_size;
    if (_generator) {
        write_buffer_size = _generator->make(buffer, Generator::STACK_BUFFER_SIZE, NAME.c_str(),
                                             level, level_name, message, size);
    } else {
        write_buffer_size = 0;
    }

    bool write_result;
    if (write_buffer_size >= 1) {
        write_result = _sink->write(level, buffer, write_buffer_size);
    } else {
        write_result = _sink->write(level, message, size);
    }

    if (_auto_flush) {
        _sink->flush();
    }

    return write_result;
}

bool Logger::write(int level, char const * level_name, char const * message) const
{
    return write(level, level_name, message, ::strlen(message));
}

bool Logger::write(int level, char const * level_name, std::string const & message) const
{
    return write(level, level_name, message.c_str(), static_cast<int>(message.size()));
}

bool Logger::write(int level, char const * message, int size) const
{
    return write(level, getTextWithLevelStep(level), message, size);
}

bool Logger::write(int level, char const * message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(int level, std::string const & message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(Severity const & severity, char const * message, int size) const
{
    return write(severity.getLevel(), severity.getText(), message, size);
}

bool Logger::write(Severity const & severity, char const * message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

bool Logger::write(Severity const & severity, std::string const & message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

} // namespace log

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<commit_msg>Refactoring Logger::write() method.<commit_after>/**
 * @file   Logger.cpp
 * @brief  Logger class implementation.
 * @author zer0
 * @date   2017-04-13
 * @date   2019-07-02 (Move namespace: log/mgr -> log)
 */

#include <libtbag/log/Logger.hpp>
#include <libtbag/util/BufferInfo.hpp>

#include <cassert>
#include <cstring>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace log {

Logger::Logger(std::string const & name,
               SharedSink const & sink,
               SharedGenerator const & generator,
               int level,
               bool auto_flush)
        : NAME(name), _sink(sink), _generator(generator), _level(level), _auto_flush(auto_flush)
{
    assert(static_cast<bool>(_sink));
}

Logger::~Logger()
{
    _sink->flush();
    _sink.reset();
    _generator.reset();
}

void Logger::flush() const
{
    assert(static_cast<bool>(_sink));
    _sink->flush();
}

bool Logger::write(int level, char const * level_name, char const * message, int size) const
{
    if (youShallNotPass(level)) {
        return true;
    }
    if (!_sink) {
        return false;
    }

    assert(level_name != nullptr);
    assert(message != nullptr);
    assert(size >= 1);

    bool write_result;
    if (_generator) {
        auto const required_buffer_size = _generator->getPaddingByte() + size;
        if (Generator::STACK_BUFFER_SIZE >= required_buffer_size) {
            TBAG_CONSTEXPR static auto const buffer_size = Generator::STACK_BUFFER_SIZE;
            char buffer[buffer_size];
            auto const generated_size = _generator->make(buffer, buffer_size, NAME.c_str(),
                                                         level, level_name, message, size);
            assert(generated_size >= 1);
            assert(generated_size <= buffer_size);
            write_result = _sink->write(level, buffer, generated_size);
        } else {
            libtbag::util::Buffer buffer(required_buffer_size);
            auto const generated_size = _generator->make(buffer.data(), required_buffer_size, NAME.c_str(),
                                                         level, level_name, message, size);
            assert(generated_size >= 1);
            assert(generated_size <= required_buffer_size);
            write_result = _sink->write(level, buffer.data(), generated_size);
        }
    } else {
        write_result = _sink->write(level, message, size);
    }

    if (write_result && _auto_flush) {
        _sink->flush();
    }

    return write_result;
}

bool Logger::write(int level, char const * level_name, char const * message) const
{
    return write(level, level_name, message, ::strlen(message));
}

bool Logger::write(int level, char const * level_name, std::string const & message) const
{
    return write(level, level_name, message.c_str(), static_cast<int>(message.size()));
}

bool Logger::write(int level, char const * message, int size) const
{
    return write(level, getTextWithLevelStep(level), message, size);
}

bool Logger::write(int level, char const * message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(int level, std::string const & message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(Severity const & severity, char const * message, int size) const
{
    return write(severity.getLevel(), severity.getText(), message, size);
}

bool Logger::write(Severity const & severity, char const * message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

bool Logger::write(Severity const & severity, std::string const & message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

} // namespace log

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<|endoftext|>


<commit_before>#include <media/codecs/vorbis/VorbisFile.h>
#include <system/System.h>

namespace lime {

	typedef struct {

		unsigned char* data;
		ogg_int64_t size;
		ogg_int64_t pos;

	} VorbisFile_Buffer;

	static size_t VorbisFile_BufferRead (void* dest, size_t eltSize, size_t nelts, VorbisFile_Buffer* src) {

		size_t len = eltSize * nelts;

		if ((src->pos + len) > src->size) {

			len = src->size - src->pos;

		}

		if (len > 0) {

			memcpy (dest, (src->data + src->pos), len);
			src->pos += len;

		}

		return len;

	}

	static int VorbisFile_BufferSeek (VorbisFile_Buffer* src, ogg_int64_t pos, int whence) {

		switch (whence) {

			case SEEK_CUR:

				src->pos += pos;
				break;

			case SEEK_END:

				src->pos = src->size - pos;
				break;

			case SEEK_SET:

				src->pos = pos;
				break;

			default:

				return -1;

		}

		if (src->pos < 0) {

			src->pos = 0;
			return -1;

		}

		if (src->pos > src->size) {

			return -1;

		}

		return 0;

	}

	static int VorbisFile_BufferClose (VorbisFile_Buffer* src) {

		free (src);
		return 0;

	}

	static long VorbisFile_BufferTell (VorbisFile_Buffer* src) {

		return src->pos;

	}

	static ov_callbacks VORBIS_FILE_BUFFER_CALLBACKS = {

		(size_t (*)(void *, size_t, size_t, void *)) VorbisFile_BufferRead,
		(int (*)(void *, ogg_int64_t, int)) VorbisFile_BufferSeek,
		(int (*)(void *)) VorbisFile_BufferClose,
		(long (*)(void *)) VorbisFile_BufferTell

	};

	static size_t VorbisFile_FileRead (void* dest, size_t eltSize, size_t nelts, FILE_HANDLE* file) {

		return lime::fread (dest, eltSize, nelts, file);

	}

	static int VorbisFile_FileSeek (FILE_HANDLE* file, ogg_int64_t pos, int whence) {

		return lime::fseek (file, pos, whence);

	}

	static int VorbisFile_FileClose (FILE_HANDLE* file) {

		return lime::fclose (file);

	}

	static long VorbisFile_FileTell (FILE_HANDLE* file) {

		return lime::ftell (file);

	}

	static ov_callbacks VORBIS_FILE_FILE_CALLBACKS = {

		(size_t (*)(void *, size_t, size_t, void *)) VorbisFile_FileRead,
		(int (*)(void *, ogg_int64_t, int)) VorbisFile_FileSeek,
		(int (*)(void *)) VorbisFile_FileClose,
		(long (*)(void *)) VorbisFile_FileTell

	};

	OggVorbis_File* VorbisFile::FromBytes (Bytes* bytes) {

		OggVorbis_File* vorbisFile = new OggVorbis_File;
		memset (vorbisFile, 0, sizeof (OggVorbis_File));

		VorbisFile_Buffer* buffer = new VorbisFile_Buffer ();
		buffer->data = bytes->b;
		buffer->size = bytes->length;
		buffer->pos = 0;

		if (ov_open_callbacks (buffer, vorbisFile, NULL, 0, VORBIS_FILE_BUFFER_CALLBACKS) != 0) {

			free (buffer);
			free (vorbisFile);
			return 0;

		}

		return vorbisFile;

	}

	OggVorbis_File* VorbisFile::FromFile (const char* path) {

		if (path) {

			FILE_HANDLE *file = lime::fopen (path, "rb");

			if (file) {

				OggVorbis_File* vorbisFile = new OggVorbis_File;
				memset (vorbisFile, 0, sizeof (OggVorbis_File));

				if (ov_open_callbacks (file, vorbisFile, NULL, 0, VORBIS_FILE_FILE_CALLBACKS) != 0) {

					free (vorbisFile);
					lime::fclose (file);
					return 0;

				}

				return vorbisFile;

			}

		}

		return 0;

	}

}<commit_msg>vorbisfile.cpp - change free(x) to `delete x` (fixes #1556)<commit_after>#include <media/codecs/vorbis/VorbisFile.h>
#include <system/System.h>

namespace lime {

	typedef struct {

		unsigned char* data;
		ogg_int64_t size;
		ogg_int64_t pos;

	} VorbisFile_Buffer;

	static size_t VorbisFile_BufferRead (void* dest, size_t eltSize, size_t nelts, VorbisFile_Buffer* src) {

		size_t len = eltSize * nelts;

		if ((src->pos + len) > src->size) {

			len = src->size - src->pos;

		}

		if (len > 0) {

			memcpy (dest, (src->data + src->pos), len);
			src->pos += len;

		}

		return len;

	}

	static int VorbisFile_BufferSeek (VorbisFile_Buffer* src, ogg_int64_t pos, int whence) {

		switch (whence) {

			case SEEK_CUR:

				src->pos += pos;
				break;

			case SEEK_END:

				src->pos = src->size - pos;
				break;

			case SEEK_SET:

				src->pos = pos;
				break;

			default:

				return -1;

		}

		if (src->pos < 0) {

			src->pos = 0;
			return -1;

		}

		if (src->pos > src->size) {

			return -1;

		}

		return 0;

	}

	static int VorbisFile_BufferClose (VorbisFile_Buffer* src) {

		delete src;
		return 0;

	}

	static long VorbisFile_BufferTell (VorbisFile_Buffer* src) {

		return src->pos;

	}

	static ov_callbacks VORBIS_FILE_BUFFER_CALLBACKS = {

		(size_t (*)(void *, size_t, size_t, void *)) VorbisFile_BufferRead,
		(int (*)(void *, ogg_int64_t, int)) VorbisFile_BufferSeek,
		(int (*)(void *)) VorbisFile_BufferClose,
		(long (*)(void *)) VorbisFile_BufferTell

	};

	static size_t VorbisFile_FileRead (void* dest, size_t eltSize, size_t nelts, FILE_HANDLE* file) {

		return lime::fread (dest, eltSize, nelts, file);

	}

	static int VorbisFile_FileSeek (FILE_HANDLE* file, ogg_int64_t pos, int whence) {

		return lime::fseek (file, pos, whence);

	}

	static int VorbisFile_FileClose (FILE_HANDLE* file) {

		return lime::fclose (file);

	}

	static long VorbisFile_FileTell (FILE_HANDLE* file) {

		return lime::ftell (file);

	}

	static ov_callbacks VORBIS_FILE_FILE_CALLBACKS = {

		(size_t (*)(void *, size_t, size_t, void *)) VorbisFile_FileRead,
		(int (*)(void *, ogg_int64_t, int)) VorbisFile_FileSeek,
		(int (*)(void *)) VorbisFile_FileClose,
		(long (*)(void *)) VorbisFile_FileTell

	};

	OggVorbis_File* VorbisFile::FromBytes (Bytes* bytes) {

		OggVorbis_File* vorbisFile = new OggVorbis_File;
		memset (vorbisFile, 0, sizeof (OggVorbis_File));

		VorbisFile_Buffer* buffer = new VorbisFile_Buffer ();
		buffer->data = bytes->b;
		buffer->size = bytes->length;
		buffer->pos = 0;

		if (ov_open_callbacks (buffer, vorbisFile, NULL, 0, VORBIS_FILE_BUFFER_CALLBACKS) != 0) {

			delete buffer;
			delete vorbisFile;
			return 0;

		}

		return vorbisFile;

	}

	OggVorbis_File* VorbisFile::FromFile (const char* path) {

		if (path) {

			FILE_HANDLE *file = lime::fopen (path, "rb");

			if (file) {

				OggVorbis_File* vorbisFile = new OggVorbis_File;
				memset (vorbisFile, 0, sizeof (OggVorbis_File));

				if (ov_open_callbacks (file, vorbisFile, NULL, 0, VORBIS_FILE_FILE_CALLBACKS) != 0) {

					delete vorbisFile;
					lime::fclose (file);
					return 0;

				}

				return vorbisFile;

			}

		}

		return 0;

	}

}<|endoftext|>


<commit_before>#include "Model.hpp"
#ifdef SLIC3RXS
#include "perlglue.hpp"
#endif

namespace Slic3r {

Model::Model() {}

Model::Model(const Model &other)
{
    objects.reserve(other.objects.size());

    for (ModelMaterialMap::const_iterator i = other.materials.begin();
        i != other.materials.end(); ++i)
    {
        ModelMaterial *copy = new ModelMaterial(*i->second);
        copy->model = this;
        materials[i->first] = copy;

    }

    for (ModelObjectPtrs::const_iterator i = other.objects.begin();
        i != other.objects.end(); ++i)
    {
        ModelObject *copy = new ModelObject(**i);
        copy->model = this;
        objects.push_back(copy);
    }
}

Model::~Model()
{
    this->clear_objects();
    this->clear_materials();
}

ModelObject*
Model::add_object(const std::string &input_file, const DynamicPrintConfig &config,
    const t_layer_height_ranges &layer_height_ranges, const Pointf &origin_translation)
{
    ModelObject* object = new ModelObject(this, input_file, config,
        layer_height_ranges, origin_translation);
    this->objects.push_back(object);
    return object;
}

void
Model::delete_object(size_t idx)
{
    ModelObjectPtrs::iterator i = this->objects.begin() + idx;
    delete *i;
    this->objects.erase(i);
}

void
Model::clear_objects()
{
    for (size_t i = 0; i < this->objects.size(); ++i)
        this->delete_object(i);
}

void
Model::delete_material(t_model_material_id material_id)
{
    ModelMaterialMap::iterator i = this->materials.find(material_id);
    if (i != this->materials.end()) {
        delete i->second;
        this->materials.erase(i);
    }
}

void
Model::clear_materials()
{
    while (!this->materials.empty())
        this->delete_material( this->materials.begin()->first );
}

ModelMaterial *
Model::set_material(t_model_material_id material_id)
{
    ModelMaterialMap::iterator i = this->materials.find(material_id);

    ModelMaterial *mat;
    if (i == this->materials.end()) {
        mat = this->materials[material_id] = new ModelMaterial(this);
    } else {
        mat = i->second;
    }

    return mat;
}

/*
void
Model::duplicate_objects_grid(unsigned int x, unsigned int y, coordf_t distance)
{
    if (this->objects.size() > 1) throw "Grid duplication is not supported with multiple objects";
    if (this->objects.empty()) throw "No objects!";

    ModelObject* object = this->objects.front();
    object->clear_instances();

    BoundingBoxf3 bb;
    object->bounding_box(&bb);
    Sizef3 size = bb.size();

    for (unsigned int x_copy = 1; x_copy <= x; ++x_copy) {
        for (unsigned int y_copy = 1; y_copy <= y; ++y_copy) {
            ModelInstance* instance = object->add_instance();
            instance->offset.x = (size.x + distance) * (x_copy-1);
            instance->offset.y = (size.y + distance) * (y_copy-1);
        }
    }
}
*/

bool
Model::has_objects_with_no_instances() const
{
    for (ModelObjectPtrs::const_iterator i = this->objects.begin();
        i != this->objects.end(); ++i)
    {
        if ((*i)->instances.empty()) {
            return true;
        }
    }

    return false;
}

#ifdef SLIC3RXS
REGISTER_CLASS(Model, "Model");
#endif

ModelMaterial::ModelMaterial(Model *model) : model(model) {}

void
ModelMaterial::apply(const t_model_material_attributes &attributes)
{
    this->attributes.insert(attributes.begin(), attributes.end());
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelMaterial, "Model::Material");
#endif

ModelObject::ModelObject(Model *model, const std::string &input_file,
    const DynamicPrintConfig &config, const t_layer_height_ranges &layer_height_ranges,
    const Pointf &origin_translation)
:   model(model),
    input_file(input_file),
    config(config),
    layer_height_ranges(layer_height_ranges),
    origin_translation(origin_translation),
    _bounding_box_valid(false)
{
}

ModelObject::ModelObject(const ModelObject &other)
:   model(other.model),
    input_file(other.input_file),
    instances(),
    volumes(),
    config(other.config),
    layer_height_ranges(other.layer_height_ranges),
    origin_translation(other.origin_translation),
    _bounding_box(other._bounding_box),
    _bounding_box_valid(other._bounding_box_valid)
{
    volumes.reserve(other.volumes.size());
    instances.reserve(other.instances.size());

    for (ModelVolumePtrs::const_iterator i = other.volumes.begin();
        i != other.volumes.end(); ++i)
    {
        ModelVolume *v = new ModelVolume(**i);
        v->object = this;
        volumes.push_back(v);

    }

    for (ModelInstancePtrs::const_iterator i = other.instances.begin();
        i != other.instances.end(); ++i)
    {
        ModelInstance *in = new ModelInstance(**i);
        in->object = this;
        instances.push_back(in);
    }
}

ModelObject::~ModelObject()
{
    this->clear_volumes();
    this->clear_instances();
}

ModelVolume *
ModelObject::add_volume(const t_model_material_id &material_id,
        const TriangleMesh &mesh, bool modifier)
{
    ModelVolume *v = new ModelVolume(this, material_id, mesh, modifier);
    this->volumes.push_back(v);
    this->invalidate_bounding_box();
    return v;
}

void
ModelObject::delete_volume(size_t idx)
{
    ModelVolumePtrs::iterator i = this->volumes.begin() + idx;
    delete *i;
    this->volumes.erase(i);
    this->invalidate_bounding_box();
}

void
ModelObject::clear_volumes()
{
    for (size_t i = 0; i < this->volumes.size(); ++i)
        this->delete_volume(i);
}

ModelInstance *
ModelObject::add_instance(double rotation, double scaling_factor,
    Pointf offset)
{
    ModelInstance *i = new ModelInstance(
        this, rotation, scaling_factor, offset);
    this->instances.push_back(i);
    this->invalidate_bounding_box();
    return i;
}

void
ModelObject::delete_instance(size_t idx)
{
    ModelInstancePtrs::iterator i = this->instances.begin() + idx;
    delete *i;
    this->instances.erase(i);
    this->invalidate_bounding_box();
}

void
ModelObject::delete_last_instance()
{
    this->delete_instance(this->instances.size() - 1);
}

void
ModelObject::clear_instances()
{
    for (size_t i = 0; i < this->instances.size(); ++i)
        this->delete_instance(i);
}

void
ModelObject::invalidate_bounding_box()
{
    this->_bounding_box_valid = false;
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelObject, "Model::Object");

SV*
ModelObject::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

ModelVolume::ModelVolume(ModelObject* object, const t_model_material_id &material_id,
    const TriangleMesh &mesh, bool modifier)
:   object(object),
    material_id(material_id),
    mesh(mesh),
    modifier(modifier)
{
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelVolume, "Model::Volume");

SV*
ModelVolume::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

ModelInstance::ModelInstance(ModelObject *object, double rotation,
    double scaling_factor, const Pointf &offset)
:   object(object),
    rotation(rotation),
    scaling_factor(scaling_factor),
    offset(offset)
{
}

ModelInstance::~ModelInstance()
{
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelInstance, "Model::Instance");

SV*
ModelInstance::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

}
<commit_msg>Fix clear_objects() and clear_volumes()<commit_after>#include "Model.hpp"
#ifdef SLIC3RXS
#include "perlglue.hpp"
#endif

namespace Slic3r {

Model::Model() {}

Model::Model(const Model &other)
{
    objects.reserve(other.objects.size());

    for (ModelMaterialMap::const_iterator i = other.materials.begin();
        i != other.materials.end(); ++i)
    {
        ModelMaterial *copy = new ModelMaterial(*i->second);
        copy->model = this;
        materials[i->first] = copy;

    }

    for (ModelObjectPtrs::const_iterator i = other.objects.begin();
        i != other.objects.end(); ++i)
    {
        ModelObject *copy = new ModelObject(**i);
        copy->model = this;
        objects.push_back(copy);
    }
}

Model::~Model()
{
    this->clear_objects();
    this->clear_materials();
}

ModelObject*
Model::add_object(const std::string &input_file, const DynamicPrintConfig &config,
    const t_layer_height_ranges &layer_height_ranges, const Pointf &origin_translation)
{
    ModelObject* object = new ModelObject(this, input_file, config,
        layer_height_ranges, origin_translation);
    this->objects.push_back(object);
    return object;
}

void
Model::delete_object(size_t idx)
{
    ModelObjectPtrs::iterator i = this->objects.begin() + idx;
    delete *i;
    this->objects.erase(i);
}

void
Model::clear_objects()
{
    for (size_t i = this->objects.size()-1; i >= 0; --i)
        this->delete_object(i);
}

void
Model::delete_material(t_model_material_id material_id)
{
    ModelMaterialMap::iterator i = this->materials.find(material_id);
    if (i != this->materials.end()) {
        delete i->second;
        this->materials.erase(i);
    }
}

void
Model::clear_materials()
{
    while (!this->materials.empty())
        this->delete_material( this->materials.begin()->first );
}

ModelMaterial *
Model::set_material(t_model_material_id material_id)
{
    ModelMaterialMap::iterator i = this->materials.find(material_id);

    ModelMaterial *mat;
    if (i == this->materials.end()) {
        mat = this->materials[material_id] = new ModelMaterial(this);
    } else {
        mat = i->second;
    }

    return mat;
}

/*
void
Model::duplicate_objects_grid(unsigned int x, unsigned int y, coordf_t distance)
{
    if (this->objects.size() > 1) throw "Grid duplication is not supported with multiple objects";
    if (this->objects.empty()) throw "No objects!";

    ModelObject* object = this->objects.front();
    object->clear_instances();

    BoundingBoxf3 bb;
    object->bounding_box(&bb);
    Sizef3 size = bb.size();

    for (unsigned int x_copy = 1; x_copy <= x; ++x_copy) {
        for (unsigned int y_copy = 1; y_copy <= y; ++y_copy) {
            ModelInstance* instance = object->add_instance();
            instance->offset.x = (size.x + distance) * (x_copy-1);
            instance->offset.y = (size.y + distance) * (y_copy-1);
        }
    }
}
*/

bool
Model::has_objects_with_no_instances() const
{
    for (ModelObjectPtrs::const_iterator i = this->objects.begin();
        i != this->objects.end(); ++i)
    {
        if ((*i)->instances.empty()) {
            return true;
        }
    }

    return false;
}

#ifdef SLIC3RXS
REGISTER_CLASS(Model, "Model");
#endif

ModelMaterial::ModelMaterial(Model *model) : model(model) {}

void
ModelMaterial::apply(const t_model_material_attributes &attributes)
{
    this->attributes.insert(attributes.begin(), attributes.end());
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelMaterial, "Model::Material");
#endif

ModelObject::ModelObject(Model *model, const std::string &input_file,
    const DynamicPrintConfig &config, const t_layer_height_ranges &layer_height_ranges,
    const Pointf &origin_translation)
:   model(model),
    input_file(input_file),
    config(config),
    layer_height_ranges(layer_height_ranges),
    origin_translation(origin_translation),
    _bounding_box_valid(false)
{
}

ModelObject::ModelObject(const ModelObject &other)
:   model(other.model),
    input_file(other.input_file),
    instances(),
    volumes(),
    config(other.config),
    layer_height_ranges(other.layer_height_ranges),
    origin_translation(other.origin_translation),
    _bounding_box(other._bounding_box),
    _bounding_box_valid(other._bounding_box_valid)
{
    volumes.reserve(other.volumes.size());
    instances.reserve(other.instances.size());

    for (ModelVolumePtrs::const_iterator i = other.volumes.begin();
        i != other.volumes.end(); ++i)
    {
        ModelVolume *v = new ModelVolume(**i);
        v->object = this;
        volumes.push_back(v);

    }

    for (ModelInstancePtrs::const_iterator i = other.instances.begin();
        i != other.instances.end(); ++i)
    {
        ModelInstance *in = new ModelInstance(**i);
        in->object = this;
        instances.push_back(in);
    }
}

ModelObject::~ModelObject()
{
    this->clear_volumes();
    this->clear_instances();
}

ModelVolume *
ModelObject::add_volume(const t_model_material_id &material_id,
        const TriangleMesh &mesh, bool modifier)
{
    ModelVolume *v = new ModelVolume(this, material_id, mesh, modifier);
    this->volumes.push_back(v);
    this->invalidate_bounding_box();
    return v;
}

void
ModelObject::delete_volume(size_t idx)
{
    ModelVolumePtrs::iterator i = this->volumes.begin() + idx;
    delete *i;
    this->volumes.erase(i);
    this->invalidate_bounding_box();
}

void
ModelObject::clear_volumes()
{
    for (size_t i = this->volumes.size()-1; i >= 0; --i)
        this->delete_volume(i);
}

ModelInstance *
ModelObject::add_instance(double rotation, double scaling_factor,
    Pointf offset)
{
    ModelInstance *i = new ModelInstance(
        this, rotation, scaling_factor, offset);
    this->instances.push_back(i);
    this->invalidate_bounding_box();
    return i;
}

void
ModelObject::delete_instance(size_t idx)
{
    ModelInstancePtrs::iterator i = this->instances.begin() + idx;
    delete *i;
    this->instances.erase(i);
    this->invalidate_bounding_box();
}

void
ModelObject::delete_last_instance()
{
    this->delete_instance(this->instances.size() - 1);
}

void
ModelObject::clear_instances()
{
    for (size_t i = 0; i < this->instances.size(); ++i)
        this->delete_instance(i);
}

void
ModelObject::invalidate_bounding_box()
{
    this->_bounding_box_valid = false;
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelObject, "Model::Object");

SV*
ModelObject::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

ModelVolume::ModelVolume(ModelObject* object, const t_model_material_id &material_id,
    const TriangleMesh &mesh, bool modifier)
:   object(object),
    material_id(material_id),
    mesh(mesh),
    modifier(modifier)
{
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelVolume, "Model::Volume");

SV*
ModelVolume::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

ModelInstance::ModelInstance(ModelObject *object, double rotation,
    double scaling_factor, const Pointf &offset)
:   object(object),
    rotation(rotation),
    scaling_factor(scaling_factor),
    offset(offset)
{
}

ModelInstance::~ModelInstance()
{
}

#ifdef SLIC3RXS
REGISTER_CLASS(ModelInstance, "Model::Instance");

SV*
ModelInstance::to_SV_ref() {
    SV* sv = newSV(0);
    sv_setref_pv( sv, perl_class_name_ref(this), this );
    return sv;
}
#endif

}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtrackerrelationshipfetchrequest.h"

#include <QtTracker/Tracker>
using namespace SopranoLive;

// TODO better error handling when saving
QTrackerRelationshipFetchRequest::QTrackerRelationshipFetchRequest(QContactAbstractRequest* req, QContactManagerEngine* parent)
: QObject(parent), QTrackerContactAsyncRequest(req)
{
    Q_ASSERT(req);
    Q_ASSERT(req->type() == QContactAbstractRequest::RelationshipFetchRequest);
    Q_ASSERT(parent);

    QContactRelationshipFetchRequest* r = qobject_cast<QContactRelationshipFetchRequest*>(req);

    if( !r )
    {
        QList<QContactManager::Error> errors(QList<QContactManager::Error>()<<QContactManager::UnspecifiedError);
        QContactManagerEngine::updateRequest(req, QList<QContactRelationship>(), QContactManager::UnspecifiedError, errors, QContactAbstractRequest::Finished);
        return;
    }
    if (not r->relationshipType().isEmpty() && QContactRelationship::Is != r->relationshipType())
    {
        QList<QContactManager::Error> errors(QList<QContactManager::Error>()<<QContactManager::NotSupportedError);
        QContactManagerEngine::updateRequest(req, r->relationships(), QContactManager::NotSupportedError, errors, QContactAbstractRequest::Finished);
        return;
    }
    QList<QContactManager::Error> dummy;
    QContactManagerEngine::updateRequestStatus(req, QContactManager::NoError, dummy,
            QContactAbstractRequest::Active);

    RDFVariable RDFContact = RDFVariable::fromType<nco::PersonContact>();
    RDFVariable RDFContactThis = RDFVariable::fromType<nco::PersonContact>();

    RDFVariable RDFMetacontact;

    RDFContact.property<nco::metacontact>() = RDFMetacontact;
    RDFContactThis.property<nco::metacontact>() = RDFMetacontact;
    RDFVariable contactIdThis = RDFContactThis.property<nco::contactUID>();

    contactIdThis.equal(LiteralValue(QString::number(r->first().localId())));

    RDFSelect quer;
    quer.addColumn("contact_id", RDFContact.property<nco::contactUID>());
    quer.addColumn("contactthis_id", contactIdThis);
    query = ::tracker()->modelQuery(quer);

    QObject::connect(query.model(), SIGNAL(modelUpdated()), this, SLOT(modelUpdated()));

}

QTrackerRelationshipFetchRequest::~QTrackerRelationshipFetchRequest()
{
}

void QTrackerRelationshipFetchRequest::modelUpdated()
{
    QContactManagerEngine *engine = qobject_cast<QContactManagerEngine *> (parent());
    if( !engine )
    {
        QList<QContactManager::Error> errors(QList<QContactManager::Error>()<<QContactManager::UnspecifiedError);
        QContactManagerEngine::updateRequest(req, QList<QContactRelationship>(), QContactManager::UnspecifiedError, errors, QContactAbstractRequest::Finished);
        return;
    }

    QList<QContactRelationship> result;
    for(int i = 0; i < query->rowCount(); i++) {
        bool ok, ok1;
        QContactId idfirst;
        idfirst.setLocalId(query->index(i, 1).data().toUInt(&ok));
        QContactId idsecond;
        idsecond.setLocalId(query->index(i, 0).data().toUInt(&ok1));

        if (ok && ok1 ) {
            if (idfirst.localId() == idsecond.localId())
                continue;
            idfirst.setManagerUri(engine->managerUri());
            idsecond.setManagerUri(idfirst.managerUri());

            QContactRelationship rel;
            rel.setFirst(idfirst);
            rel.setSecond(idsecond);
            rel.setRelationshipType(QContactRelationship::Is);
            result.append(rel);
        }
    }

    QContactManagerEngine::updateRequest(req, result, QContactManager::NoError,
                              QList<QContactManager::Error> (),
                              QContactAbstractRequest::Finished,
                              false);
}

<commit_msg>Changes : Port reletion ship fetch request Rev-By : TrustMe<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtrackerrelationshipfetchrequest.h"

#include <QtTracker/Tracker>
using namespace SopranoLive;

// TODO better error handling when saving
QTrackerRelationshipFetchRequest::QTrackerRelationshipFetchRequest(QContactAbstractRequest* req, QContactManagerEngine* parent)
: QObject(parent), QTrackerContactAsyncRequest(req)
{
    Q_ASSERT(req);
    Q_ASSERT(req->type() == QContactAbstractRequest::RelationshipFetchRequest);
    Q_ASSERT(parent);

    QContactRelationshipFetchRequest* r = qobject_cast<QContactRelationshipFetchRequest*>(req);

    if( !r )
    {
        QContactManagerEngine::updateRelationshipFetchRequest(r, QList<QContactRelationship>(), QContactManager::UnspecifiedError);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
    if (not r->relationshipType().isEmpty() && QContactRelationship::Is != r->relationshipType())
    {
        QContactManagerEngine::updateRelationshipFetchRequest(r, r->relationships(), QContactManager::NotSupportedError);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }
    QList<QContactManager::Error> dummy;
    QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::ActiveState);

    RDFVariable RDFContact = RDFVariable::fromType<nco::PersonContact>();
    RDFVariable RDFContactThis = RDFVariable::fromType<nco::PersonContact>();

    RDFVariable RDFMetacontact;

    RDFContact.property<nco::metacontact>() = RDFMetacontact;
    RDFContactThis.property<nco::metacontact>() = RDFMetacontact;
    RDFVariable contactIdThis = RDFContactThis.property<nco::contactUID>();

    contactIdThis.equal(LiteralValue(QString::number(r->first().localId())));

    RDFSelect quer;
    quer.addColumn("contact_id", RDFContact.property<nco::contactUID>());
    quer.addColumn("contactthis_id", contactIdThis);
    query = ::tracker()->modelQuery(quer);

    QObject::connect(query.model(), SIGNAL(modelUpdated()), this, SLOT(modelUpdated()));

}

QTrackerRelationshipFetchRequest::~QTrackerRelationshipFetchRequest()
{
}

void QTrackerRelationshipFetchRequest::modelUpdated()
{
    QContactManagerEngine *engine = qobject_cast<QContactManagerEngine *> (parent());
    QContactRelationshipFetchRequest* r = qobject_cast<QContactRelationshipFetchRequest*>(req);
    if( !engine )
    {
        QContactManagerEngine::updateRelationshipFetchRequest(r, QList<QContactRelationship>(), QContactManager::UnspecifiedError);
        QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
        return;
    }

    QList<QContactRelationship> result;
    for(int i = 0; i < query->rowCount(); i++) {
        bool ok, ok1;
        QContactId idfirst;
        idfirst.setLocalId(query->index(i, 1).data().toUInt(&ok));
        QContactId idsecond;
        idsecond.setLocalId(query->index(i, 0).data().toUInt(&ok1));

        if (ok && ok1 ) {
            if (idfirst.localId() == idsecond.localId())
                continue;
            idfirst.setManagerUri(engine->managerUri());
            idsecond.setManagerUri(idfirst.managerUri());

            QContactRelationship rel;
            rel.setFirst(idfirst);
            rel.setSecond(idsecond);
            rel.setRelationshipType(QContactRelationship::Is);
            result.append(rel);
        }
    }

    QContactManagerEngine::updateRelationshipFetchRequest(r, result, QContactManager::NoError);
    QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::FinishedState);
}

<|endoftext|>