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

#include <limits>

#include "grpc/grpc.h"
#include "grpc/support/time.h"
#include "timeval.h"

namespace grpc {
namespace node {

gpr_timespec MillisecondsToTimespec(double millis) {
  if (millis == std::numeric_limits<double>::infinity()) {
    return gpr_inf_future(GPR_CLOCK_REALTIME);
  } else if (millis == -std::numeric_limits<double>::infinity()) {
    return gpr_inf_past(GPR_CLOCK_REALTIME);
  } else {
    return gpr_time_from_micros(static_cast<int64_t>(millis * 1000),
                                GPR_CLOCK_REALTIME);
  }
}

double TimespecToMilliseconds(gpr_timespec timespec) {
  if (gpr_time_cmp(timespec, gpr_inf_future(GPR_CLOCK_REALTIME)) == 0) {
    return std::numeric_limits<double>::infinity();
  } else if (gpr_time_cmp(timespec, gpr_inf_past(GPR_CLOCK_REALTIME)) == 0) {
    return -std::numeric_limits<double>::infinity();
  } else {
    return (static_cast<double>(timespec.tv_sec) * 1000 +
            static_cast<double>(timespec.tv_nsec) / 1000000);
  }
}

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

#include <limits>

#include "grpc/grpc.h"
#include "grpc/support/time.h"
#include "timeval.h"

namespace grpc {
namespace node {

gpr_timespec MillisecondsToTimespec(double millis) {
  if (millis == std::numeric_limits<double>::infinity()) {
    return gpr_inf_future(GPR_CLOCK_REALTIME);
  } else if (millis == -std::numeric_limits<double>::infinity()) {
    return gpr_inf_past(GPR_CLOCK_REALTIME);
  } else {
    return gpr_time_from_micros(static_cast<int64_t>(millis * 1000),
                                GPR_CLOCK_REALTIME);
  }
}

double TimespecToMilliseconds(gpr_timespec timespec) {
  timespec = gpr_convert_clock_type(timespec, GPR_CLOCK_REALTIME);
  if (gpr_time_cmp(timespec, gpr_inf_future(GPR_CLOCK_REALTIME)) == 0) {
    return std::numeric_limits<double>::infinity();
  } else if (gpr_time_cmp(timespec, gpr_inf_past(GPR_CLOCK_REALTIME)) == 0) {
    return -std::numeric_limits<double>::infinity();
  } else {
    return (static_cast<double>(timespec.tv_sec) * 1000 +
            static_cast<double>(timespec.tv_nsec) / 1000000);
  }
}

}  // namespace node
}  // namespace grpc
<|endoftext|>


<commit_before>#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include "COP_SCU.h"
#include "MIPS.h"
#include "Jitter.h"
#include "offsetof_def.h"

const char* CCOP_SCU::m_sRegName[] =
{
	"Index",
	"Random",
	"EntryLo0",
	"EntryLo1",
	"Context",
	"PageMask",
	"Wired",
	"*RESERVED*",
	"BadVAddr",
	"Count",
	"EntryHi",
	"Compare",
	"Status",
	"Cause",
	"EPC",
	"PrevID",
	"Config",
	"LLAddr",
	"WatchLo",
	"WatchHi",
	"XContext",
	"CPCOND0",
	"*RESERVED*",
	"*RESERVED*",
	"*RESERVED*",
	"*RESERVED*",
	"PErr",
	"CacheErr",
	"TagLo",
	"TagHi",
	"ErrorEPC",
	"*RESERVED*"
};

CCOP_SCU::CCOP_SCU(MIPS_REGSIZE nRegSize)
: CMIPSCoprocessor(nRegSize)
, m_nRT(0)
, m_nRD(0)
{
	SetupReflectionTables();
}

void CCOP_SCU::CompileInstruction(uint32 nAddress, CMipsJitter* codeGen, CMIPS* pCtx)
{
	SetupQuickVariables(nAddress, codeGen, pCtx);

	m_nRT	= (uint8)((m_nOpcode >> 16) & 0x1F);
	m_nRD	= (uint8)((m_nOpcode >> 11) & 0x1F);

	((this)->*(m_pOpGeneral[(m_nOpcode >> 21) & 0x1F]))();
}

//////////////////////////////////////////////////
//General Opcodes
//////////////////////////////////////////////////

//00
void CCOP_SCU::MFC0()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));

	if(m_regSize == MIPS_REGSIZE_64)
	{
		m_codeGen->PushTop();
		m_codeGen->SignExt();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
	}
    m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}

//04
void CCOP_SCU::MTC0()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));

	if(m_nRD == CCOP_SCU::STATUS)
	{
		//Keep the EXL bit
		//This is needed for Valkyrie Profile 2 which resets the EXL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));
		m_codeGen->PushCst(CMIPS::STATUS_EXL);
		m_codeGen->And();
		m_codeGen->Or();
	}

	m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));
}

//08
void CCOP_SCU::BC0()
{
	((this)->*(m_pOpBC0[m_nRT]))();
}

//10
void CCOP_SCU::C0()
{
	((this)->*(m_pOpC0[(m_nOpcode & 0x3F)]))();
}

//////////////////////////////////////////////////
//Branches
//////////////////////////////////////////////////

//00
void CCOP_SCU::BC0F()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[CPCOND0]));
	m_codeGen->PushCst(0);
	Branch(Jitter::CONDITION_EQ);
}

//01
void CCOP_SCU::BC0T()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[CPCOND0]));
	m_codeGen->PushCst(0);
	Branch(Jitter::CONDITION_NE);
}

//////////////////////////////////////////////////
//Coprocessor Specific Opcodes
//////////////////////////////////////////////////

//18
void CCOP_SCU::ERET()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	m_codeGen->PushCst(CMIPS::STATUS_ERL);
	m_codeGen->And();

	m_codeGen->PushCst(0);
	m_codeGen->BeginIf(Jitter::CONDITION_NE);
	{
		//ERL bit was set
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[ERROREPC]));
        m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));

		//Clear ERL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
		m_codeGen->PushCst(~CMIPS::STATUS_ERL);
		m_codeGen->And();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	}
	m_codeGen->Else();
	{
		//EXL bit was set
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[EPC]));
        m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));

		//Clear EXL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
		m_codeGen->PushCst(~CMIPS::STATUS_EXL);
		m_codeGen->And();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	}
	m_codeGen->EndIf();
}

//38
void CCOP_SCU::EI()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	m_codeGen->PushCst(0x00010001);
	m_codeGen->Or();
	m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));

	//Force the main loop to check for pending interrupts
	m_codeGen->PushCst(MIPS_EXCEPTION_CHECKPENDINGINT);
	m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}

//39
void CCOP_SCU::DI()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
    m_codeGen->PushCst(~0x00010001);
    m_codeGen->And();
    m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
}

//////////////////////////////////////////////////
//Opcode Tables
//////////////////////////////////////////////////

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpGeneral[0x20] =
{
	//0x00
	&CCOP_SCU::MFC0,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::MTC0,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::BC0,   		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::C0,			&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpBC0[0x20] =
{
	//0x00
	&CCOP_SCU::BC0F,		&CCOP_SCU::BC0T,  		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpC0[0x40] =
{
	//0x00
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::ERET,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x20
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x28
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x30
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x38
	&CCOP_SCU::EI,			&CCOP_SCU::DI,			&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};
<commit_msg>Cleanup.<commit_after>#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include "COP_SCU.h"
#include "MIPS.h"
#include "Jitter.h"
#include "offsetof_def.h"

const char* CCOP_SCU::m_sRegName[] =
{
	"Index",
	"Random",
	"EntryLo0",
	"EntryLo1",
	"Context",
	"PageMask",
	"Wired",
	"*RESERVED*",
	"BadVAddr",
	"Count",
	"EntryHi",
	"Compare",
	"Status",
	"Cause",
	"EPC",
	"PrevID",
	"Config",
	"LLAddr",
	"WatchLo",
	"WatchHi",
	"XContext",
	"CPCOND0",
	"*RESERVED*",
	"*RESERVED*",
	"*RESERVED*",
	"*RESERVED*",
	"PErr",
	"CacheErr",
	"TagLo",
	"TagHi",
	"ErrorEPC",
	"*RESERVED*"
};

CCOP_SCU::CCOP_SCU(MIPS_REGSIZE nRegSize)
: CMIPSCoprocessor(nRegSize)
, m_nRT(0)
, m_nRD(0)
{
	SetupReflectionTables();
}

void CCOP_SCU::CompileInstruction(uint32 nAddress, CMipsJitter* codeGen, CMIPS* pCtx)
{
	SetupQuickVariables(nAddress, codeGen, pCtx);

	m_nRT	= (uint8)((m_nOpcode >> 16) & 0x1F);
	m_nRD	= (uint8)((m_nOpcode >> 11) & 0x1F);

	((this)->*(m_pOpGeneral[(m_nOpcode >> 21) & 0x1F]))();
}

//////////////////////////////////////////////////
//General Opcodes
//////////////////////////////////////////////////

//00
void CCOP_SCU::MFC0()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));

	if(m_regSize == MIPS_REGSIZE_64)
	{
		m_codeGen->PushTop();
		m_codeGen->SignExt();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[1]));
	}
    m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));
}

//04
void CCOP_SCU::MTC0()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nRT].nV[0]));

	if(m_nRD == CCOP_SCU::STATUS)
	{
		//Keep the EXL bit
		//This is needed for Valkyrie Profile 2 which resets the EXL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));
		m_codeGen->PushCst(CMIPS::STATUS_EXL);
		m_codeGen->And();
		m_codeGen->Or();
	}

	m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[m_nRD]));
}

//08
void CCOP_SCU::BC0()
{
	((this)->*(m_pOpBC0[m_nRT]))();
}

//10
void CCOP_SCU::C0()
{
	((this)->*(m_pOpC0[(m_nOpcode & 0x3F)]))();
}

//////////////////////////////////////////////////
//Branches
//////////////////////////////////////////////////

//00
void CCOP_SCU::BC0F()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[CPCOND0]));
	m_codeGen->PushCst(0);
	Branch(Jitter::CONDITION_EQ);
}

//01
void CCOP_SCU::BC0T()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[CPCOND0]));
	m_codeGen->PushCst(0);
	Branch(Jitter::CONDITION_NE);
}

//////////////////////////////////////////////////
//Coprocessor Specific Opcodes
//////////////////////////////////////////////////

//18
void CCOP_SCU::ERET()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	m_codeGen->PushCst(CMIPS::STATUS_ERL);
	m_codeGen->And();

	m_codeGen->PushCst(0);
	m_codeGen->BeginIf(Jitter::CONDITION_NE);
	{
		//ERL bit was set
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[ERROREPC]));
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));

		//Clear ERL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
		m_codeGen->PushCst(~CMIPS::STATUS_ERL);
		m_codeGen->And();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	}
	m_codeGen->Else();
	{
		//EXL bit was set
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[EPC]));
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nDelayedJumpAddr));

		//Clear EXL bit
		m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
		m_codeGen->PushCst(~CMIPS::STATUS_EXL);
		m_codeGen->And();
		m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	}
	m_codeGen->EndIf();
}

//38
void CCOP_SCU::EI()
{
	m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
	m_codeGen->PushCst(0x00010001);
	m_codeGen->Or();
	m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));

	//Force the main loop to check for pending interrupts
	m_codeGen->PushCst(MIPS_EXCEPTION_CHECKPENDINGINT);
	m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}

//39
void CCOP_SCU::DI()
{
    m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
    m_codeGen->PushCst(~0x00010001);
    m_codeGen->And();
    m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP0[STATUS]));
}

//////////////////////////////////////////////////
//Opcode Tables
//////////////////////////////////////////////////

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpGeneral[0x20] =
{
	//0x00
	&CCOP_SCU::MFC0,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::MTC0,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::BC0,   		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::C0,			&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpBC0[0x20] =
{
	//0x00
	&CCOP_SCU::BC0F,		&CCOP_SCU::BC0T,  		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};

CCOP_SCU::InstructionFuncConstant CCOP_SCU::m_pOpC0[0x40] =
{
	//0x00
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x08
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x10
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x18
	&CCOP_SCU::ERET,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x20
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x28
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x30
	&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
	//0x38
	&CCOP_SCU::EI,			&CCOP_SCU::DI,			&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,		&CCOP_SCU::Illegal,
};
<|endoftext|>


<commit_before>#include "ExactDiagonalizationSolver.h"
#include "FockSpace.h"
#include "FileWriter.h"
#include "DOS.h"
#include "DiagonalizationSolver.h"
#include "DPropertyExtractor.h"
#include "SumRule.h"
#include "DifferenceRule.h"
#include "WrapperRule.h"
#include "Timer.h"

using namespace std;

namespace TBTK{

ExactDiagonalizationSolver::ExactDiagonalizationSolver(Model *model){
	this->model = model;
}

ExactDiagonalizationSolver::~ExactDiagonalizationSolver(){
}

unsigned int ExactDiagonalizationSolver::addSubspace(initializer_list<const FockStateRule::WrapperRule> rules){
	unsigned int numSubspaces = subspaceContexts.size();

	subspaceContexts.push_back(SubspaceContext(rules));

	return numSubspaces;
}

void ExactDiagonalizationSolver::run(unsigned int subspace){
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	if(subspaceContext.manyBodyModel == NULL){
		setupManyBodyModel(subspace);
		subspaceContext.dSolver = new DiagonalizationSolver();
		subspaceContext.dSolver->setModel(subspaceContext.manyBodyModel);
		subspaceContext.dSolver->run();

/*		DPropertyExtractor pe(subspaceContext.dSolver);
		pe.setEnergyWindow(-10., 10., 1000);
		Property::DOS *dos = pe.calculateDOS();
		FileWriter::writeDOS(dos);
		delete dos;*/
	}
}

template<>
void ExactDiagonalizationSolver::setupManyBodyModel<BitRegister>(unsigned int subspace){
//	FockSpace<BitRegister> *fockSpace = manyBodyContext.getFockSpaceBitRegister();
	FockSpace<BitRegister> *fockSpace = model->getManyBodyContext()->getFockSpaceBitRegister();
	LadderOperator<BitRegister> **operators = fockSpace->getOperators();
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	FockStateMap::FockStateMap<BitRegister> *fockStateMap = fockSpace->createFockStateMap(
		subspaceContext.rules
	);

	subspaceContext.manyBodyModel = new Model();
	for(unsigned int n = 0; n < fockStateMap->getBasisSize(); n++){
		HoppingAmplitudeSet::Iterator it = model->getHoppingAmplitudeSet()->getIterator();
		const HoppingAmplitude *ha;
		while((ha = it.getHA())){
			it.searchNextHA();

			FockState<BitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			operators[model->getBasisIndex(ha->fromIndex)][1]*fockState;
			if(fockState.isNull())
				continue;
			operators[model->getBasisIndex(ha->toIndex)][0]*fockState;
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ha->getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}

//		for(unsigned int c = 0; c < interactionAmplitudeSet->getNumInteractionAmplitudes(); c++){
		for(unsigned int c = 0; c < model->getManyBodyContext()->getInteractionAmplitudeSet()->getNumInteractionAmplitudes(); c++){
			FockState<BitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

//			InteractionAmplitude ia = interactionAmplitudeSet->getInteractionAmplitude(c);
			InteractionAmplitude ia = model->getManyBodyContext()->getInteractionAmplitudeSet()->getInteractionAmplitude(c);
			for(int k =  ia.getNumAnnihilationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getAnnihilationOperatorIndex(k))][1]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			for(int k =  ia.getNumCreationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getCreationOperatorIndex(k))][0]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ia.getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}
	}
	subspaceContext.manyBodyModel->construct();

	delete fockStateMap;
}

template<>
void ExactDiagonalizationSolver::setupManyBodyModel<ExtensiveBitRegister>(unsigned int subspace){
//	FockSpace<ExtensiveBitRegister> *fockSpace = manyBodyContext.getFockSpaceExtensiveBitRegister();
	FockSpace<ExtensiveBitRegister> *fockSpace = model->getManyBodyContext()->getFockSpaceExtensiveBitRegister();
	LadderOperator<ExtensiveBitRegister> **operators = fockSpace->getOperators();
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	FockStateMap::FockStateMap<ExtensiveBitRegister> *fockStateMap = fockSpace->createFockStateMap(
		subspaceContext.rules
	);

	subspaceContext.manyBodyModel = new Model();
	for(unsigned int n = 0; n < fockStateMap->getBasisSize(); n++){
		HoppingAmplitudeSet::Iterator it = model->getHoppingAmplitudeSet()->getIterator();
		const HoppingAmplitude *ha;
		while((ha = it.getHA())){
			it.searchNextHA();

			FockState<ExtensiveBitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			operators[model->getBasisIndex(ha->fromIndex)][1]*fockState;
			if(fockState.isNull())
				continue;
			operators[model->getBasisIndex(ha->toIndex)][0]*fockState;
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ha->getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}

//		for(unsigned int c = 0; c < interactionAmplitudeSet->getNumInteractionAmplitudes(); c++){
		for(unsigned int c = 0; c < model->getManyBodyContext()->getInteractionAmplitudeSet()->getNumInteractionAmplitudes(); c++){
			FockState<ExtensiveBitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

//			InteractionAmplitude ia = interactionAmplitudeSet->getInteractionAmplitude(c);
			InteractionAmplitude ia = model->getManyBodyContext()->getInteractionAmplitudeSet()->getInteractionAmplitude(c);
			for(int k =  ia.getNumAnnihilationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getAnnihilationOperatorIndex(k))][1]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			for(int k =  ia.getNumCreationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getCreationOperatorIndex(k))][0]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ia.getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}
	}
	subspaceContext.manyBodyModel->construct();

	delete fockStateMap;
}

void ExactDiagonalizationSolver::setupManyBodyModel(unsigned int subspace){
	model->getManyBodyContext();
//	if(manyBodyContext.wrapsBitRegister())
	if(model->getManyBodyContext()->wrapsBitRegister())
		setupManyBodyModel<BitRegister>(subspace);
	else
		setupManyBodyModel<ExtensiveBitRegister>(subspace);
}

ExactDiagonalizationSolver::SubspaceContext::SubspaceContext(
	initializer_list<const FockStateRule::WrapperRule> rules
){
	for(unsigned int n = 0; n < rules.size(); n++)
		this->rules.push_back(*(rules.begin()+n));

	manyBodyModel = NULL;
	dSolver = NULL;
}

ExactDiagonalizationSolver::SubspaceContext::~SubspaceContext(){
	if(manyBodyModel != NULL)
		delete manyBodyModel;
	if(dSolver != NULL)
		delete dSolver;
}

};	//End of namespace TBTK
<commit_msg>Removed commented out legacy code<commit_after>#include "ExactDiagonalizationSolver.h"
#include "FockSpace.h"
#include "FileWriter.h"
#include "DOS.h"
#include "DiagonalizationSolver.h"
#include "DPropertyExtractor.h"
#include "SumRule.h"
#include "DifferenceRule.h"
#include "WrapperRule.h"
#include "Timer.h"

using namespace std;

namespace TBTK{

ExactDiagonalizationSolver::ExactDiagonalizationSolver(Model *model){
	this->model = model;
}

ExactDiagonalizationSolver::~ExactDiagonalizationSolver(){
}

unsigned int ExactDiagonalizationSolver::addSubspace(initializer_list<const FockStateRule::WrapperRule> rules){
	unsigned int numSubspaces = subspaceContexts.size();

	subspaceContexts.push_back(SubspaceContext(rules));

	return numSubspaces;
}

void ExactDiagonalizationSolver::run(unsigned int subspace){
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	if(subspaceContext.manyBodyModel == NULL){
		setupManyBodyModel(subspace);
		subspaceContext.dSolver = new DiagonalizationSolver();
		subspaceContext.dSolver->setModel(subspaceContext.manyBodyModel);
		subspaceContext.dSolver->run();
	}
}

template<>
void ExactDiagonalizationSolver::setupManyBodyModel<BitRegister>(unsigned int subspace){
	FockSpace<BitRegister> *fockSpace = model->getManyBodyContext()->getFockSpaceBitRegister();
	LadderOperator<BitRegister> **operators = fockSpace->getOperators();
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	FockStateMap::FockStateMap<BitRegister> *fockStateMap = fockSpace->createFockStateMap(
		subspaceContext.rules
	);

	subspaceContext.manyBodyModel = new Model();
	for(unsigned int n = 0; n < fockStateMap->getBasisSize(); n++){
		HoppingAmplitudeSet::Iterator it = model->getHoppingAmplitudeSet()->getIterator();
		const HoppingAmplitude *ha;
		while((ha = it.getHA())){
			it.searchNextHA();

			FockState<BitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			operators[model->getBasisIndex(ha->fromIndex)][1]*fockState;
			if(fockState.isNull())
				continue;
			operators[model->getBasisIndex(ha->toIndex)][0]*fockState;
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ha->getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}

		for(unsigned int c = 0; c < model->getManyBodyContext()->getInteractionAmplitudeSet()->getNumInteractionAmplitudes(); c++){
			FockState<BitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			InteractionAmplitude ia = model->getManyBodyContext()->getInteractionAmplitudeSet()->getInteractionAmplitude(c);
			for(int k =  ia.getNumAnnihilationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getAnnihilationOperatorIndex(k))][1]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			for(int k =  ia.getNumCreationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getCreationOperatorIndex(k))][0]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ia.getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}
	}
	subspaceContext.manyBodyModel->construct();

	delete fockStateMap;
}

template<>
void ExactDiagonalizationSolver::setupManyBodyModel<ExtensiveBitRegister>(unsigned int subspace){
	FockSpace<ExtensiveBitRegister> *fockSpace = model->getManyBodyContext()->getFockSpaceExtensiveBitRegister();
	LadderOperator<ExtensiveBitRegister> **operators = fockSpace->getOperators();
	SubspaceContext &subspaceContext = subspaceContexts.at(subspace);
	FockStateMap::FockStateMap<ExtensiveBitRegister> *fockStateMap = fockSpace->createFockStateMap(
		subspaceContext.rules
	);

	subspaceContext.manyBodyModel = new Model();
	for(unsigned int n = 0; n < fockStateMap->getBasisSize(); n++){
		HoppingAmplitudeSet::Iterator it = model->getHoppingAmplitudeSet()->getIterator();
		const HoppingAmplitude *ha;
		while((ha = it.getHA())){
			it.searchNextHA();

			FockState<ExtensiveBitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			operators[model->getBasisIndex(ha->fromIndex)][1]*fockState;
			if(fockState.isNull())
				continue;
			operators[model->getBasisIndex(ha->toIndex)][0]*fockState;
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ha->getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}

		for(unsigned int c = 0; c < model->getManyBodyContext()->getInteractionAmplitudeSet()->getNumInteractionAmplitudes(); c++){
			FockState<ExtensiveBitRegister> fockState = fockStateMap->getFockState(n);

			int from = fockStateMap->getBasisIndex(fockState);

			InteractionAmplitude ia = model->getManyBodyContext()->getInteractionAmplitudeSet()->getInteractionAmplitude(c);
			for(int k =  ia.getNumAnnihilationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getAnnihilationOperatorIndex(k))][1]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			for(int k =  ia.getNumCreationOperators() - 1; k >= 0; k--){
				operators[model->getBasisIndex(ia.getCreationOperatorIndex(k))][0]*fockState;
				if(fockState.isNull())
					break;
			}
			if(fockState.isNull())
				continue;

			int to = fockStateMap->getBasisIndex(fockState);

			subspaceContext.manyBodyModel->addHA(HoppingAmplitude(
				ia.getAmplitude()*(double)fockState.getPrefactor(),
				{to},
				{from}
			));
		}
	}
	subspaceContext.manyBodyModel->construct();

	delete fockStateMap;
}

void ExactDiagonalizationSolver::setupManyBodyModel(unsigned int subspace){
	if(model->getManyBodyContext()->wrapsBitRegister())
		setupManyBodyModel<BitRegister>(subspace);
	else
		setupManyBodyModel<ExtensiveBitRegister>(subspace);
}

ExactDiagonalizationSolver::SubspaceContext::SubspaceContext(
	initializer_list<const FockStateRule::WrapperRule> rules
){
	for(unsigned int n = 0; n < rules.size(); n++)
		this->rules.push_back(*(rules.begin()+n));

	manyBodyModel = NULL;
	dSolver = NULL;
}

ExactDiagonalizationSolver::SubspaceContext::~SubspaceContext(){
	if(manyBodyModel != NULL)
		delete manyBodyModel;
	if(dSolver != NULL)
		delete dSolver;
}

};	//End of namespace TBTK
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: vclxdevice.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_VCLXDEVICE_HXX_
#define _TOOLKIT_AWT_VCLXDEVICE_HXX_

#include <toolkit/dllapi.h>
#include <com/sun/star/awt/XDevice.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <cppuhelper/weak.hxx>
#include <vos/mutex.hxx>

class OutputDevice;
class VirtualDevice;

//  ----------------------------------------------------
//  class VCLXDevice
//  ----------------------------------------------------

// For using nDummy, no incompatible update, add a BOOL bCreatedWithToolkitMember later...
#define FLAGS_CREATEDWITHTOOLKIT    0x00000001

class TOOLKIT_DLLPUBLIC VCLXDevice :    public ::com::sun::star::awt::XDevice,
                    public ::com::sun::star::lang::XTypeProvider,
                    public ::com::sun::star::lang::XUnoTunnel,
                    public ::cppu::OWeakObject
{
    friend class VCLXGraphics;

private:
    NAMESPACE_VOS(IMutex)&  mrMutex;    // Reference to SolarMutex
    OutputDevice*           mpOutputDevice;

public:
    void*                   pDummy;
    sal_uInt32              nFlags;

protected:
    NAMESPACE_VOS(IMutex)&  GetMutex() { return mrMutex; }
    void                    DestroyOutputDevice();

public:
                            VCLXDevice();
                            ~VCLXDevice();

    void                    SetOutputDevice( OutputDevice* pOutDev ) { mpOutputDevice = pOutDev; }
    OutputDevice*           GetOutputDevice() const { return mpOutputDevice; }

    void                    SetCreatedWithToolkit( sal_Bool bCreatedWithToolkit );
    sal_Bool                IsCreatedWithToolkit() const;

    // ::com::sun::star::uno::XInterface
    ::com::sun::star::uno::Any                  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    void                                        SAL_CALL acquire() throw()  { OWeakObject::acquire(); }
    void                                        SAL_CALL release() throw()  { OWeakObject::release(); }

    // ::com::sun::star::lang::XUnoTunnel
    static const ::com::sun::star::uno::Sequence< sal_Int8 >&   GetUnoTunnelId() throw();
    static VCLXDevice*                                          GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
    sal_Int64                                                   SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XTypeProvider
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type >  SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< sal_Int8 >                     SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XDevice,
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >    SAL_CALL createGraphics(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice >      SAL_CALL createDevice( sal_Int32 nWidth, sal_Int32 nHeight ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::DeviceInfo                                       SAL_CALL getInfo() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::awt::FontDescriptor > SAL_CALL getFontDescriptors(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >        SAL_CALL getFont( const ::com::sun::star::awt::FontDescriptor& aDescriptor ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >      SAL_CALL createBitmap( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDisplayBitmap > SAL_CALL createDisplayBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >& Bitmap ) throw(::com::sun::star::uno::RuntimeException);
};

//  ----------------------------------------------------
//  class VCLXVirtualDevice
//  ----------------------------------------------------

class VCLXVirtualDevice : public VCLXDevice
{
private:
    VirtualDevice*  mpVDev;

public:
                    ~VCLXVirtualDevice();

    void            SetVirtualDevice( VirtualDevice* pVDev ) { SetOutputDevice( (OutputDevice*)pVDev ); }
};

#endif // _TOOLKIT_AWT_VCLXDEVICE_HXX_

<commit_msg>INTEGRATION: CWS rptwizard01 (1.6.320); FILE MERGED 2008/05/21 10:11:51 lla 1.6.320.4: RESYNC: (1.6-1.7); FILE MERGED 2008/03/14 14:06:08 lla 1.6.320.3: #i86925# cleanup 2008/03/14 14:02:46 lla 1.6.320.2: #i86925# cleanup 2008/03/14 13:47:15 lla 1.6.320.1: #i86925# Unit Converter<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: vclxdevice.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_VCLXDEVICE_HXX_
#define _TOOLKIT_AWT_VCLXDEVICE_HXX_

#include <toolkit/dllapi.h>
#include <com/sun/star/awt/XDevice.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <cppuhelper/weak.hxx>
#include <vos/mutex.hxx>

// #include <com/sun/star/awt/XTextConstraints.hpp>
#include <com/sun/star/awt/XUnitConversion.hpp>

class OutputDevice;
class VirtualDevice;

//  ----------------------------------------------------
//  class VCLXDevice
//  ----------------------------------------------------

// For using nDummy, no incompatible update, add a BOOL bCreatedWithToolkitMember later...
#define FLAGS_CREATEDWITHTOOLKIT    0x00000001

class TOOLKIT_DLLPUBLIC VCLXDevice :    public ::com::sun::star::awt::XDevice,
                    public ::com::sun::star::lang::XTypeProvider,
                    public ::com::sun::star::lang::XUnoTunnel,
/* public ::com::sun::star::awt::XTextConstraints,*/
                    public ::com::sun::star::awt::XUnitConversion,
                    public ::cppu::OWeakObject
{
    friend class VCLXGraphics;

private:
    NAMESPACE_VOS(IMutex)&  mrMutex;    // Reference to SolarMutex
    OutputDevice*           mpOutputDevice;

public:
    void*                   pDummy;
    sal_uInt32              nFlags;

protected:
    NAMESPACE_VOS(IMutex)&  GetMutex() { return mrMutex; }
    void                    DestroyOutputDevice();

public:
                            VCLXDevice();
                            ~VCLXDevice();

    void                    SetOutputDevice( OutputDevice* pOutDev ) { mpOutputDevice = pOutDev; }
    OutputDevice*           GetOutputDevice() const { return mpOutputDevice; }

    void                    SetCreatedWithToolkit( sal_Bool bCreatedWithToolkit );
    sal_Bool                IsCreatedWithToolkit() const;

    // ::com::sun::star::uno::XInterface
    ::com::sun::star::uno::Any                  SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    void                                        SAL_CALL acquire() throw()  { OWeakObject::acquire(); }
    void                                        SAL_CALL release() throw()  { OWeakObject::release(); }

    // ::com::sun::star::lang::XUnoTunnel
    static const ::com::sun::star::uno::Sequence< sal_Int8 >&   GetUnoTunnelId() throw();
    static VCLXDevice*                                          GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
    sal_Int64                                                   SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::lang::XTypeProvider
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type >  SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< sal_Int8 >                     SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XDevice,
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >    SAL_CALL createGraphics(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice >      SAL_CALL createDevice( sal_Int32 nWidth, sal_Int32 nHeight ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::DeviceInfo                                       SAL_CALL getInfo() throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Sequence< ::com::sun::star::awt::FontDescriptor > SAL_CALL getFontDescriptors(  ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >        SAL_CALL getFont( const ::com::sun::star::awt::FontDescriptor& aDescriptor ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >      SAL_CALL createBitmap( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight ) throw(::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDisplayBitmap > SAL_CALL createDisplayBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >& Bitmap ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XTextConstraints
    // ::sal_Int32 SAL_CALL getTextWidth( const ::rtl::OUString& Text ) throw (::com::sun::star::uno::RuntimeException);
    // ::sal_Int32 SAL_CALL getTextHeight(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::awt::XUnitConversion
    ::com::sun::star::awt::Point SAL_CALL convertPointToLogic( const ::com::sun::star::awt::Point& aPoint, ::sal_Int16 TargetUnit ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL convertPointToPixel( const ::com::sun::star::awt::Point& aPoint, ::sal_Int16 SourceUnit ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Size SAL_CALL convertSizeToLogic( const ::com::sun::star::awt::Size& aSize, ::sal_Int16 TargetUnit ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Size SAL_CALL convertSizeToPixel( const ::com::sun::star::awt::Size& aSize, ::sal_Int16 SourceUnit ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

};

//  ----------------------------------------------------
//  class VCLXVirtualDevice
//  ----------------------------------------------------

class VCLXVirtualDevice : public VCLXDevice
{
private:
    VirtualDevice*  mpVDev;

public:
                    ~VCLXVirtualDevice();

    void            SetVirtualDevice( VirtualDevice* pVDev ) { SetOutputDevice( (OutputDevice*)pVDev ); }
};

#endif // _TOOLKIT_AWT_VCLXDEVICE_HXX_

<|endoftext|>


<commit_before><commit_msg>Make AliDataFile ignore AliPhysics version tags<commit_after><|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "mitkSegmentationTaskList.h"

#include <mitkIOUtil.h>
#include <mitkProperties.h>

mitk::SegmentationTaskList::Task::Task()
  : m_Defaults(nullptr)
{
}

mitk::SegmentationTaskList::Task::~Task()
{
}

void mitk::SegmentationTaskList::Task::SetDefaults(const Task* defaults)
{
  m_Defaults = defaults;
}

mitk::SegmentationTaskList::SegmentationTaskList()
{
  // A base data cannot be serialized if empty. To be not considered empty its
  // geometry must consist of at least one time step. However, a segmentation
  // task would then appear as invisible spacial object in a scene. This can
  // be prevented by excluding it from the scene's bounding box calculations.
  this->GetTimeGeometry()->Expand(1);
  this->SetProperty("includeInBoundingBox", BoolProperty::New(false));
}

mitk::SegmentationTaskList::SegmentationTaskList(const Self& other)
  : BaseData(other)
{
}

mitk::SegmentationTaskList::~SegmentationTaskList()
{
}

size_t mitk::SegmentationTaskList::GetNumberOfTasks() const
{
  return m_Tasks.size();
}

size_t mitk::SegmentationTaskList::AddTask(const Task& subtask)
{
  m_Tasks.push_back(subtask);
  m_Tasks.back().SetDefaults(&m_Defaults);
  return m_Tasks.size() - 1;
}

const mitk::SegmentationTaskList::Task* mitk::SegmentationTaskList::GetTask(size_t index) const
{
  return &m_Tasks.at(index);
}

mitk::SegmentationTaskList::Task* mitk::SegmentationTaskList::GetTask(size_t index)
{
  return &m_Tasks.at(index);
}

const mitk::SegmentationTaskList::Task& mitk::SegmentationTaskList::GetDefaults() const
{
  return m_Defaults;
}

void mitk::SegmentationTaskList::SetDefaults(const Task& defaults)
{
  m_Defaults = defaults;

  for (auto& subtask : m_Tasks)
    subtask.SetDefaults(&m_Defaults);
}

bool mitk::SegmentationTaskList::IsDone() const
{
  for (size_t i = 0; i < m_Tasks.size(); ++i)
  {
    if (!this->IsDone(i))
      return false;
  }

  return true;
}

bool mitk::SegmentationTaskList::IsDone(size_t index) const
{
  return fs::exists(this->GetAbsolutePath(m_Tasks.at(index).GetResult()));
}

fs::path mitk::SegmentationTaskList::GetInputLocation() const
{
  std::string inputLocation;
  this->GetPropertyList()->GetStringProperty("MITK.IO.reader.inputlocation", inputLocation);

  return !inputLocation.empty()
    ? fs::path(inputLocation).lexically_normal()
    : fs::path();
}

fs::path mitk::SegmentationTaskList::GetBasePath() const
{
  return this->GetInputLocation().remove_filename();
}

fs::path mitk::SegmentationTaskList::GetAbsolutePath(const fs::path& path) const
{
  if (path.empty())
    return path;

  auto normalizedPath = path.lexically_normal();

  return !normalizedPath.is_absolute()
    ? this->GetBasePath() / normalizedPath
    : normalizedPath;
}

void mitk::SegmentationTaskList::SaveTask(size_t index, const BaseData* segmentation)
{
  if (segmentation == nullptr)
    return;

  auto path = this->GetAbsolutePath(this->GetResult(index));
  IOUtil::Save(segmentation, path.string());
}

std::vector<mitk::SegmentationTaskList::Task>::const_iterator mitk::SegmentationTaskList::begin() const
{
  return m_Tasks.begin();
}

std::vector<mitk::SegmentationTaskList::Task>::const_iterator mitk::SegmentationTaskList::end() const
{
  return m_Tasks.end();
}

std::vector<mitk::SegmentationTaskList::Task>::iterator mitk::SegmentationTaskList::begin()
{
  return m_Tasks.begin();
}

std::vector<mitk::SegmentationTaskList::Task>::iterator mitk::SegmentationTaskList::end()
{
  return m_Tasks.end();
}

void mitk::SegmentationTaskList::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::SegmentationTaskList::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::SegmentationTaskList::VerifyRequestedRegion()
{
  return true;
}

void mitk::SegmentationTaskList::SetRequestedRegion(const itk::DataObject*)
{
}
<commit_msg>Remove calls to lexically_normal()<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "mitkSegmentationTaskList.h"

#include <mitkIOUtil.h>
#include <mitkProperties.h>

mitk::SegmentationTaskList::Task::Task()
  : m_Defaults(nullptr)
{
}

mitk::SegmentationTaskList::Task::~Task()
{
}

void mitk::SegmentationTaskList::Task::SetDefaults(const Task* defaults)
{
  m_Defaults = defaults;
}

mitk::SegmentationTaskList::SegmentationTaskList()
{
  // A base data cannot be serialized if empty. To be not considered empty its
  // geometry must consist of at least one time step. However, a segmentation
  // task would then appear as invisible spacial object in a scene. This can
  // be prevented by excluding it from the scene's bounding box calculations.
  this->GetTimeGeometry()->Expand(1);
  this->SetProperty("includeInBoundingBox", BoolProperty::New(false));
}

mitk::SegmentationTaskList::SegmentationTaskList(const Self& other)
  : BaseData(other)
{
}

mitk::SegmentationTaskList::~SegmentationTaskList()
{
}

size_t mitk::SegmentationTaskList::GetNumberOfTasks() const
{
  return m_Tasks.size();
}

size_t mitk::SegmentationTaskList::AddTask(const Task& subtask)
{
  m_Tasks.push_back(subtask);
  m_Tasks.back().SetDefaults(&m_Defaults);
  return m_Tasks.size() - 1;
}

const mitk::SegmentationTaskList::Task* mitk::SegmentationTaskList::GetTask(size_t index) const
{
  return &m_Tasks.at(index);
}

mitk::SegmentationTaskList::Task* mitk::SegmentationTaskList::GetTask(size_t index)
{
  return &m_Tasks.at(index);
}

const mitk::SegmentationTaskList::Task& mitk::SegmentationTaskList::GetDefaults() const
{
  return m_Defaults;
}

void mitk::SegmentationTaskList::SetDefaults(const Task& defaults)
{
  m_Defaults = defaults;

  for (auto& subtask : m_Tasks)
    subtask.SetDefaults(&m_Defaults);
}

bool mitk::SegmentationTaskList::IsDone() const
{
  for (size_t i = 0; i < m_Tasks.size(); ++i)
  {
    if (!this->IsDone(i))
      return false;
  }

  return true;
}

bool mitk::SegmentationTaskList::IsDone(size_t index) const
{
  return fs::exists(this->GetAbsolutePath(m_Tasks.at(index).GetResult()));
}

fs::path mitk::SegmentationTaskList::GetInputLocation() const
{
  std::string inputLocation;
  this->GetPropertyList()->GetStringProperty("MITK.IO.reader.inputlocation", inputLocation);

  return !inputLocation.empty()
    ? fs::path(inputLocation)/*.lexically_normal()*/ // See T29246
    : fs::path();
}

fs::path mitk::SegmentationTaskList::GetBasePath() const
{
  return this->GetInputLocation().remove_filename();
}

fs::path mitk::SegmentationTaskList::GetAbsolutePath(const fs::path& path) const
{
  if (path.empty())
    return path;

  auto normalizedPath = path/*.lexically_normal()*/; // See T29246

  return !normalizedPath.is_absolute()
    ? this->GetBasePath() / normalizedPath
    : normalizedPath;
}

void mitk::SegmentationTaskList::SaveTask(size_t index, const BaseData* segmentation)
{
  if (segmentation == nullptr)
    return;

  auto path = this->GetAbsolutePath(this->GetResult(index));
  IOUtil::Save(segmentation, path.string());
}

std::vector<mitk::SegmentationTaskList::Task>::const_iterator mitk::SegmentationTaskList::begin() const
{
  return m_Tasks.begin();
}

std::vector<mitk::SegmentationTaskList::Task>::const_iterator mitk::SegmentationTaskList::end() const
{
  return m_Tasks.end();
}

std::vector<mitk::SegmentationTaskList::Task>::iterator mitk::SegmentationTaskList::begin()
{
  return m_Tasks.begin();
}

std::vector<mitk::SegmentationTaskList::Task>::iterator mitk::SegmentationTaskList::end()
{
  return m_Tasks.end();
}

void mitk::SegmentationTaskList::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::SegmentationTaskList::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::SegmentationTaskList::VerifyRequestedRegion()
{
  return true;
}

void mitk::SegmentationTaskList::SetRequestedRegion(const itk::DataObject*)
{
}
<|endoftext|>


<commit_before>//  Natron
//
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
 * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
 * contact: immarespond at gmail dot com
 *
 */

#include "BaseTest.h"

#include "Engine/Node.h"
#include "Engine/Project.h"
#include "Engine/AppManager.h"
#include "Engine/AppInstance.h"
#include "Engine/EffectInstance.h"
#include "Engine/Plugin.h"
using namespace Natron;

BaseTest::BaseTest()
    : testing::Test()
      , _app(0)
{
}

BaseTest::~BaseTest()
{
}

void
BaseTest::registerTestPlugins()
{
    _allTestPluginIDs.clear();

    _dotGeneratorPluginID = PLUGINID_OFX_DOTEXAMPLE;
    _allTestPluginIDs.push_back(_dotGeneratorPluginID);

    _readOIIOPluginID = PLUGINID_OFX_READOIIO;
    _allTestPluginIDs.push_back(_readOIIOPluginID);

    _writeOIIOPluginID = PLUGINID_OFX_WRITEOIIO;
    _allTestPluginIDs.push_back(_writeOIIOPluginID);

    for (unsigned int i = 0; i < _allTestPluginIDs.size(); ++i) {
        ///make sure the generic test plugin is present
        Natron::LibraryBinary* bin = NULL;
        try {
            Natron::Plugin* p = appPTR->getPluginBinary(_allTestPluginIDs[i], -1, -1);
            if (p) {
                bin = p->getLibraryBinary();
            }

        } catch (const std::exception & e) {
            std::cout << e.what() << std::endl;
        }

        ASSERT_TRUE(bin != NULL);
    }
}

void
BaseTest::SetUp()
{
    AppManager* manager = new AppManager;
    int argc = 0;

    manager->load(argc,NULL,QString(),QStringList(),std::list<std::pair<int,int> >(),QString());

    _app = manager->getTopLevelInstance();

    registerTestPlugins();
}

void
BaseTest::TearDown()
{
    _app->quit();
    _app = 0;
    appPTR->setNumberOfThreads(0);
    delete appPTR;
}

boost::shared_ptr<Natron::Node> BaseTest::createNode(const QString & pluginID,
                                                     int majorVersion,
                                                     int minorVersion)
{
    boost::shared_ptr<Node> ret =  _app->createNode( CreateNodeArgs(pluginID,
                                                                    "",
                                                                    majorVersion,minorVersion,-1,true,INT_MIN,INT_MIN,true,true,
                                                                    QString(),CreateNodeArgs::DefaultValuesList()) );

    EXPECT_NE(ret.get(),(Natron::Node*)NULL);

    return ret;
}

void
BaseTest::connectNodes(boost::shared_ptr<Natron::Node> input,
                       boost::shared_ptr<Natron::Node> output,
                       int inputNumber,
                       bool expectedReturnValue)
{
    if (expectedReturnValue) {
        ///check that the connections are internally all set as "expected"

        EXPECT_EQ( (Natron::Node*)NULL,output->getInput(inputNumber).get() );
        EXPECT_FALSE( output->isInputConnected(inputNumber) );
    } else {
        ///the call can only fail for those 2 reasons
        EXPECT_TRUE(inputNumber > output->getMaxInputCount() || //< inputNumber is greater than the maximum input number
                    output->getInput(inputNumber).get() != (Natron::Node*)NULL); //< input slot is already filled with another node
    }

    bool ret = _app->getProject()->connectNodes(inputNumber,input,output.get());
    EXPECT_EQ(expectedReturnValue,ret);

    if (expectedReturnValue) {
        EXPECT_TRUE( input->hasOutputConnected() );
        EXPECT_EQ(output->getInput(inputNumber),input);
        EXPECT_TRUE( output->isInputConnected(inputNumber) );
    }
}

void
BaseTest::disconnectNodes(boost::shared_ptr<Natron::Node> input,
                          boost::shared_ptr<Natron::Node> output,
                          bool expectedReturnvalue)
{
    if (expectedReturnvalue) {
        ///check that the connections are internally all set as "expected"

        ///the input must have in its output the node 'output'
        EXPECT_TRUE( input->hasOutputConnected() );
        const std::list<Natron::Node*> & outputs = input->getOutputs();
        bool foundOutput = false;
        for (std::list<Natron::Node* >::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if ( *it == output.get() ) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<boost::shared_ptr<Natron::Node> > & inputs = output->getInputs_mt_safe();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i] == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_TRUE(foundInput);
        EXPECT_TRUE(foundOutput);
        EXPECT_EQ(output->getInput(inputIndex),input);
        EXPECT_TRUE( output->isInputConnected(inputIndex) );
    }

    ///call disconnect
    bool ret = _app->getProject()->disconnectNodes(input.get(),output.get());
    EXPECT_EQ(expectedReturnvalue,ret);

    if (expectedReturnvalue) {
        ///check that the disconnection went OK

        const std::list<Natron::Node*> & outputs = input->getOutputs();
        bool foundOutput = false;
        for (std::list<Natron::Node* >::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if ( (*it) == output.get() ) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<boost::shared_ptr<Natron::Node> > & inputs = output->getInputs_mt_safe();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i] == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_FALSE(foundOutput);
        EXPECT_FALSE(foundInput);
        EXPECT_EQ( (Natron::Node*)NULL,output->getInput(inputIndex).get() );
        EXPECT_FALSE( output->isInputConnected(inputIndex) );
    }
} // disconnectNodes

///High level test: render 1 frame of dot generator
TEST_F(BaseTest,GenerateDot)
{
    ///create the generator
    boost::shared_ptr<Node> generator = createNode(_dotGeneratorPluginID);

    ///create the writer and set its output filename
    boost::shared_ptr<Node> writer = createNode(_writeOIIOPluginID);

    writer->setOutputFilesForWriter("test_dot_generator#.jpg");

    ///attempt to connect the 2 nodes together
    connectNodes(generator, writer, 0, true);

    ///and start rendering. This call is blocking.
    std::list<AppInstance::RenderWork> works;
    AppInstance::RenderWork w;
    w.writer = dynamic_cast<Natron::OutputEffectInstance*>(writer->getLiveInstance());
    assert(w.writer);
    w.firstFrame = INT_MIN;
    w.lastFrame = INT_MAX;
    works.push_back(w);
    _app->startWritersRendering(works);
}

///High level test: simple node connections test
TEST_F(BaseTest,SimpleNodeConnections) {
    ///create the generator
    boost::shared_ptr<Node> generator = createNode(_dotGeneratorPluginID);

    ///create the writer and set its output filename
    boost::shared_ptr<Node> writer = createNode(_writeOIIOPluginID);

    connectNodes(generator, writer, 0, true);
    connectNodes(generator, writer, 0, false); //< expect it to fail
    disconnectNodes(generator, writer, true);
    disconnectNodes(generator, writer, false);
    connectNodes(generator, writer, 0, true);
}
<commit_msg>Fix unit test<commit_after>//  Natron
//
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
 * Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
 * contact: immarespond at gmail dot com
 *
 */

#include "BaseTest.h"

#include "Engine/Node.h"
#include "Engine/Project.h"
#include "Engine/AppManager.h"
#include "Engine/AppInstance.h"
#include "Engine/EffectInstance.h"
#include "Engine/Plugin.h"
using namespace Natron;

BaseTest::BaseTest()
    : testing::Test()
      , _app(0)
{
}

BaseTest::~BaseTest()
{
}

void
BaseTest::registerTestPlugins()
{
    _allTestPluginIDs.clear();

    _dotGeneratorPluginID = PLUGINID_OFX_DOTEXAMPLE;
    _allTestPluginIDs.push_back(_dotGeneratorPluginID);

    _readOIIOPluginID = PLUGINID_OFX_READOIIO;
    _allTestPluginIDs.push_back(_readOIIOPluginID);

    _writeOIIOPluginID = PLUGINID_OFX_WRITEOIIO;
    _allTestPluginIDs.push_back(_writeOIIOPluginID);

    for (unsigned int i = 0; i < _allTestPluginIDs.size(); ++i) {
        ///make sure the generic test plugin is present
        Natron::LibraryBinary* bin = NULL;
        try {
            Natron::Plugin* p = appPTR->getPluginBinary(_allTestPluginIDs[i], -1, -1, false);
            if (p) {
                bin = p->getLibraryBinary();
            }

        } catch (const std::exception & e) {
            std::cout << e.what() << std::endl;
        }

        ASSERT_TRUE(bin != NULL);
    }
}

void
BaseTest::SetUp()
{
    AppManager* manager = new AppManager;
    int argc = 0;

    manager->load(argc,NULL,QString(),QStringList(),std::list<std::pair<int,int> >(),QString());

    _app = manager->getTopLevelInstance();

    registerTestPlugins();
}

void
BaseTest::TearDown()
{
    _app->quit();
    _app = 0;
    appPTR->setNumberOfThreads(0);
    delete appPTR;
}

boost::shared_ptr<Natron::Node> BaseTest::createNode(const QString & pluginID,
                                                     int majorVersion,
                                                     int minorVersion)
{
    boost::shared_ptr<Node> ret =  _app->createNode( CreateNodeArgs(pluginID,
                                                                    "",
                                                                    majorVersion,minorVersion,-1,true,INT_MIN,INT_MIN,true,true,
                                                                    QString(),CreateNodeArgs::DefaultValuesList()) );

    EXPECT_NE(ret.get(),(Natron::Node*)NULL);

    return ret;
}

void
BaseTest::connectNodes(boost::shared_ptr<Natron::Node> input,
                       boost::shared_ptr<Natron::Node> output,
                       int inputNumber,
                       bool expectedReturnValue)
{
    if (expectedReturnValue) {
        ///check that the connections are internally all set as "expected"

        EXPECT_EQ( (Natron::Node*)NULL,output->getInput(inputNumber).get() );
        EXPECT_FALSE( output->isInputConnected(inputNumber) );
    } else {
        ///the call can only fail for those 2 reasons
        EXPECT_TRUE(inputNumber > output->getMaxInputCount() || //< inputNumber is greater than the maximum input number
                    output->getInput(inputNumber).get() != (Natron::Node*)NULL); //< input slot is already filled with another node
    }

    bool ret = _app->getProject()->connectNodes(inputNumber,input,output.get());
    EXPECT_EQ(expectedReturnValue,ret);

    if (expectedReturnValue) {
        EXPECT_TRUE( input->hasOutputConnected() );
        EXPECT_EQ(output->getInput(inputNumber),input);
        EXPECT_TRUE( output->isInputConnected(inputNumber) );
    }
}

void
BaseTest::disconnectNodes(boost::shared_ptr<Natron::Node> input,
                          boost::shared_ptr<Natron::Node> output,
                          bool expectedReturnvalue)
{
    if (expectedReturnvalue) {
        ///check that the connections are internally all set as "expected"

        ///the input must have in its output the node 'output'
        EXPECT_TRUE( input->hasOutputConnected() );
        const std::list<Natron::Node*> & outputs = input->getOutputs();
        bool foundOutput = false;
        for (std::list<Natron::Node* >::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if ( *it == output.get() ) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<boost::shared_ptr<Natron::Node> > & inputs = output->getInputs_mt_safe();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i] == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_TRUE(foundInput);
        EXPECT_TRUE(foundOutput);
        EXPECT_EQ(output->getInput(inputIndex),input);
        EXPECT_TRUE( output->isInputConnected(inputIndex) );
    }

    ///call disconnect
    bool ret = _app->getProject()->disconnectNodes(input.get(),output.get());
    EXPECT_EQ(expectedReturnvalue,ret);

    if (expectedReturnvalue) {
        ///check that the disconnection went OK

        const std::list<Natron::Node*> & outputs = input->getOutputs();
        bool foundOutput = false;
        for (std::list<Natron::Node* >::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if ( (*it) == output.get() ) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<boost::shared_ptr<Natron::Node> > & inputs = output->getInputs_mt_safe();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i] == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_FALSE(foundOutput);
        EXPECT_FALSE(foundInput);
        EXPECT_EQ( (Natron::Node*)NULL,output->getInput(inputIndex).get() );
        EXPECT_FALSE( output->isInputConnected(inputIndex) );
    }
} // disconnectNodes

///High level test: render 1 frame of dot generator
TEST_F(BaseTest,GenerateDot)
{
    ///create the generator
    boost::shared_ptr<Node> generator = createNode(_dotGeneratorPluginID);

    ///create the writer and set its output filename
    boost::shared_ptr<Node> writer = createNode(_writeOIIOPluginID);

    writer->setOutputFilesForWriter("test_dot_generator#.jpg");

    ///attempt to connect the 2 nodes together
    connectNodes(generator, writer, 0, true);

    ///and start rendering. This call is blocking.
    std::list<AppInstance::RenderWork> works;
    AppInstance::RenderWork w;
    w.writer = dynamic_cast<Natron::OutputEffectInstance*>(writer->getLiveInstance());
    assert(w.writer);
    w.firstFrame = INT_MIN;
    w.lastFrame = INT_MAX;
    works.push_back(w);
    _app->startWritersRendering(works);
}

///High level test: simple node connections test
TEST_F(BaseTest,SimpleNodeConnections) {
    ///create the generator
    boost::shared_ptr<Node> generator = createNode(_dotGeneratorPluginID);

    ///create the writer and set its output filename
    boost::shared_ptr<Node> writer = createNode(_writeOIIOPluginID);

    connectNodes(generator, writer, 0, true);
    connectNodes(generator, writer, 0, false); //< expect it to fail
    disconnectNodes(generator, writer, true);
    disconnectNodes(generator, writer, false);
    connectNodes(generator, writer, 0, true);
}
<|endoftext|>


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

/* Author: Robert Haschke */

#include "collision_linear_model.h"
#include "collision_matrix_model.h"

#include <QItemSelection>
#include <QPainter>

using namespace moveit_setup_assistant;

CollisionLinearModel::CollisionLinearModel(CollisionMatrixModel* src, QObject* parent) : QAbstractProxyModel(parent)
{
  setSourceModel(src);
}
CollisionLinearModel::~CollisionLinearModel()
{
  delete sourceModel();
}

QModelIndex CollisionLinearModel::mapFromSource(const QModelIndex& sourceIndex) const
{
  // map (row,column) index to linear index k
  // http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
  int r = sourceIndex.row(), c = sourceIndex.column();
  int n = this->sourceModel()->columnCount();
  if (r == c)
    return QModelIndex();  // main diagonal elements are invalid
  if (r > c)               // only consider upper triagonal matrix
    std::swap(r, c);       // swap r,c if below diagonal

  int k = (n * (n - 1) / 2) - (n - r) * ((n - r) - 1) / 2 + c - r - 1;
  return index(k, 2);
}

QModelIndex CollisionLinearModel::mapToSource(const QModelIndex& proxyIndex) const
{
  // map linear index k to (row, column)
  // http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
  int n = sourceModel()->columnCount();
  int k = proxyIndex.row();  // linear (row) index
  int r = n - 2 - (int)(sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
  int c = k + r + 1 - n * (n - 1) / 2 + (n - r) * ((n - r) - 1) / 2;
  return sourceModel()->index(r, c);
}

int CollisionLinearModel::rowCount(const QModelIndex& parent) const
{
  int n = this->sourceModel()->rowCount();
  return (n * (n - 1) / 2);
}

int CollisionLinearModel::columnCount(const QModelIndex& parent) const
{
  return 4;
}

QModelIndex CollisionLinearModel::index(int row, int column, const QModelIndex& parent) const
{
  return createIndex(row, column);
}

QModelIndex CollisionLinearModel::parent(const QModelIndex& child) const
{
  return QModelIndex();
}

QVariant CollisionLinearModel::data(const QModelIndex& index, int role) const
{
  QModelIndex srcIndex = this->mapToSource(index);
  switch (index.column())
  {
    case 0:  // link name 1
      if (role != Qt::DisplayRole)
        return QVariant();
      else
        return this->sourceModel()->headerData(srcIndex.row(), Qt::Horizontal, Qt::DisplayRole);
    case 1:  // link name 2
      if (role != Qt::DisplayRole)
        return QVariant();
      return this->sourceModel()->headerData(srcIndex.column(), Qt::Vertical, Qt::DisplayRole);
    case 2:  // checkbox
      if (role != Qt::CheckStateRole)
        return QVariant();
      else
        return this->sourceModel()->data(srcIndex, Qt::CheckStateRole);
    case 3:  // reason
      if (role != Qt::DisplayRole)
        return QVariant();
      else
        return this->sourceModel()->data(srcIndex, Qt::ToolTipRole);
  }
  return QVariant();
}

DisabledReason CollisionLinearModel::reason(int row) const
{
  QModelIndex srcIndex = this->mapToSource(index(row, 0));
  return qobject_cast<CollisionMatrixModel*>(sourceModel())->reason(srcIndex);
}

bool CollisionLinearModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
  QModelIndex srcIndex = this->mapToSource(index);

  if (role == Qt::CheckStateRole)
  {
    sourceModel()->setData(srcIndex, value, role);
    int r = index.row();
    Q_EMIT dataChanged(this->index(r, 2), this->index(r, 3));  // reason changed too
    return true;
  }
  return false;  // reject all other changes
}

void CollisionLinearModel::setEnabled(const QItemSelection& selection, bool value)
{
  for (const auto idx : selection.indexes())
  {
    if (idx.column() != 2)  // only consider checkbox indexes
      continue;
    setData(idx, value ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
  }
}

Qt::ItemFlags CollisionLinearModel::flags(const QModelIndex& index) const
{
  if (index.column() == 2)
    return Qt::ItemIsUserCheckable | QAbstractItemModel::flags(index);
  else
    return QAbstractItemModel::flags(index);
}

QVariant CollisionLinearModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (role != Qt::DisplayRole)
    return QVariant();

  if (orientation == Qt::Horizontal)
  {
    switch (section)
    {
      case 0:
        return "Link A";
      case 1:
        return "Link B";
      case 2:
        return "Disabled";
      case 3:
        return "Reason to Disable";
    }
  }
  else if (orientation == Qt::Vertical)
  {
    return section + 1;
  }
  return QVariant();
}

SortFilterProxyModel::SortFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent), show_all_(false)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  connect(this, SIGNAL(sourceModelChanged()), this, SLOT(initSorting()));
#endif

  // by default: sort by link A (col 0), then link B (col 1)
  sort_columns_ << 0 << 1;
  sort_orders_ << Qt::AscendingOrder << Qt::AscendingOrder;
}

QVariant SortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (role == Qt::DisplayRole && orientation == Qt::Vertical)
    return section + 1;  // simply enumerate rows
  else
    return QSortFilterProxyModel::headerData(section, orientation, role);
}

void SortFilterProxyModel::setEnabled(const QItemSelection& selection, bool value)
{
  static_cast<CollisionLinearModel*>(sourceModel())->setEnabled(mapSelectionToSource(selection), value);
}

void SortFilterProxyModel::initSorting()
{
  int cols = sourceModel()->columnCount();
  int prev_size = sort_columns_.size();
  sort_columns_.resize(cols);
  sort_orders_.resize(cols);

  // initialize new entries to -1
  for (int i = prev_size, end = sort_columns_.size(); i < end; ++i)
    sort_columns_[i] = -1;
}

void SortFilterProxyModel::setShowAll(bool show_all)
{
  if (show_all_ == show_all)
    return;

  show_all_ = show_all;
  invalidateFilter();
}

bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
  CollisionLinearModel* m = qobject_cast<CollisionLinearModel*>(sourceModel());
  if (!(show_all_ || m->reason(source_row) <= moveit_setup_assistant::ALWAYS ||
        m->data(m->index(source_row, 2), Qt::CheckStateRole) == Qt::Checked))
    return false;  // not accepted due to check state

  const QRegExp regexp = this->filterRegExp();
  if (regexp.isEmpty())
    return true;

  return m->data(m->index(source_row, 0, source_parent), Qt::DisplayRole).toString().contains(regexp) ||
         m->data(m->index(source_row, 1, source_parent), Qt::DisplayRole).toString().contains(regexp);
}

// define a fallback comparison operator for QVariants
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
namespace {
bool operator<(const QVariant& left, const QVariant& right) {
  if (left.userType() == QVariant::Type::Int)
    return left.toInt() < right.toInt();
  else
    return left.toString() < right.toString();
}
}
#endif

bool SortFilterProxyModel::lessThan(const QModelIndex& src_left, const QModelIndex& src_right) const
{
  int row_left = src_left.row();
  int row_right = src_right.row();
  QAbstractItemModel* m = sourceModel();

  for (int i = 0, end = sort_columns_.size(); i < end && sort_columns_[i] >= 0; ++i)
  {
    QVariant value_left = m->data(m->index(row_left, sort_columns_[i]));
    QVariant value_right = m->data(m->index(row_right, sort_columns_[i]));

    if (value_left == value_right)
      continue;

    bool smaller = (value_left < value_right);
    if (sort_orders_[i] == Qt::DescendingOrder)
      smaller = !smaller;
    return smaller;
  }
  return false;
}

void SortFilterProxyModel::sort(int column, Qt::SortOrder order)
{
  beginResetModel();
  if (column < 0)
    initSorting();
  else
  {
    // remember sorting history
    int prev_idx = sort_columns_.indexOf(column);
    if (prev_idx < 0)
      prev_idx = sort_columns_.size() - 1;
    // remove old entries
    sort_columns_.takeAt(prev_idx);
    sort_orders_.remove(prev_idx);
    // add new entries at front
    sort_columns_.insert(0, column);
    sort_orders_.insert(0, order);
  }
  QSortFilterProxyModel::sort(column, Qt::AscendingOrder);
  endResetModel();
}
<commit_msg>fix sort role for checkbox column<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2016, CITEC, Bielefeld University
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Robert Haschke */

#include "collision_linear_model.h"
#include "collision_matrix_model.h"

#include <QItemSelection>
#include <QPainter>

using namespace moveit_setup_assistant;

CollisionLinearModel::CollisionLinearModel(CollisionMatrixModel* src, QObject* parent) : QAbstractProxyModel(parent)
{
  setSourceModel(src);
}
CollisionLinearModel::~CollisionLinearModel()
{
  delete sourceModel();
}

QModelIndex CollisionLinearModel::mapFromSource(const QModelIndex& sourceIndex) const
{
  // map (row,column) index to linear index k
  // http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
  int r = sourceIndex.row(), c = sourceIndex.column();
  int n = this->sourceModel()->columnCount();
  if (r == c)
    return QModelIndex();  // main diagonal elements are invalid
  if (r > c)               // only consider upper triagonal matrix
    std::swap(r, c);       // swap r,c if below diagonal

  int k = (n * (n - 1) / 2) - (n - r) * ((n - r) - 1) / 2 + c - r - 1;
  return index(k, 2);
}

QModelIndex CollisionLinearModel::mapToSource(const QModelIndex& proxyIndex) const
{
  // map linear index k to (row, column)
  // http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
  int n = sourceModel()->columnCount();
  int k = proxyIndex.row();  // linear (row) index
  int r = n - 2 - (int)(sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
  int c = k + r + 1 - n * (n - 1) / 2 + (n - r) * ((n - r) - 1) / 2;
  return sourceModel()->index(r, c);
}

int CollisionLinearModel::rowCount(const QModelIndex& parent) const
{
  int n = this->sourceModel()->rowCount();
  return (n * (n - 1) / 2);
}

int CollisionLinearModel::columnCount(const QModelIndex& parent) const
{
  return 4;
}

QModelIndex CollisionLinearModel::index(int row, int column, const QModelIndex& parent) const
{
  return createIndex(row, column);
}

QModelIndex CollisionLinearModel::parent(const QModelIndex& child) const
{
  return QModelIndex();
}

QVariant CollisionLinearModel::data(const QModelIndex& index, int role) const
{
  QModelIndex srcIndex = this->mapToSource(index);
  switch (index.column())
  {
    case 0:  // link name 1
      if (role != Qt::DisplayRole)
        return QVariant();
      else
        return this->sourceModel()->headerData(srcIndex.row(), Qt::Horizontal, Qt::DisplayRole);
    case 1:  // link name 2
      if (role != Qt::DisplayRole)
        return QVariant();
      return this->sourceModel()->headerData(srcIndex.column(), Qt::Vertical, Qt::DisplayRole);
    case 2:  // checkbox
      if (role != Qt::CheckStateRole)
        return QVariant();
      else
        return this->sourceModel()->data(srcIndex, Qt::CheckStateRole);
    case 3:  // reason
      if (role != Qt::DisplayRole)
        return QVariant();
      else
        return this->sourceModel()->data(srcIndex, Qt::ToolTipRole);
  }
  return QVariant();
}

DisabledReason CollisionLinearModel::reason(int row) const
{
  QModelIndex srcIndex = this->mapToSource(index(row, 0));
  return qobject_cast<CollisionMatrixModel*>(sourceModel())->reason(srcIndex);
}

bool CollisionLinearModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
  QModelIndex srcIndex = this->mapToSource(index);

  if (role == Qt::CheckStateRole)
  {
    sourceModel()->setData(srcIndex, value, role);
    int r = index.row();
    Q_EMIT dataChanged(this->index(r, 2), this->index(r, 3));  // reason changed too
    return true;
  }
  return false;  // reject all other changes
}

void CollisionLinearModel::setEnabled(const QItemSelection& selection, bool value)
{
  for (const auto idx : selection.indexes())
  {
    if (idx.column() != 2)  // only consider checkbox indexes
      continue;
    setData(idx, value ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
  }
}

Qt::ItemFlags CollisionLinearModel::flags(const QModelIndex& index) const
{
  if (index.column() == 2)
    return Qt::ItemIsUserCheckable | QAbstractItemModel::flags(index);
  else
    return QAbstractItemModel::flags(index);
}

QVariant CollisionLinearModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (role != Qt::DisplayRole)
    return QVariant();

  if (orientation == Qt::Horizontal)
  {
    switch (section)
    {
      case 0:
        return "Link A";
      case 1:
        return "Link B";
      case 2:
        return "Disabled";
      case 3:
        return "Reason to Disable";
    }
  }
  else if (orientation == Qt::Vertical)
  {
    return section + 1;
  }
  return QVariant();
}

SortFilterProxyModel::SortFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent), show_all_(false)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  connect(this, SIGNAL(sourceModelChanged()), this, SLOT(initSorting()));
#endif

  // by default: sort by link A (col 0), then link B (col 1)
  sort_columns_ << 0 << 1;
  sort_orders_ << Qt::AscendingOrder << Qt::AscendingOrder;
}

QVariant SortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (role == Qt::DisplayRole && orientation == Qt::Vertical)
    return section + 1;  // simply enumerate rows
  else
    return QSortFilterProxyModel::headerData(section, orientation, role);
}

void SortFilterProxyModel::setEnabled(const QItemSelection& selection, bool value)
{
  static_cast<CollisionLinearModel*>(sourceModel())->setEnabled(mapSelectionToSource(selection), value);
}

void SortFilterProxyModel::initSorting()
{
  int cols = sourceModel()->columnCount();
  int prev_size = sort_columns_.size();
  sort_columns_.resize(cols);
  sort_orders_.resize(cols);

  // initialize new entries to -1
  for (int i = prev_size, end = sort_columns_.size(); i < end; ++i)
    sort_columns_[i] = -1;
}

void SortFilterProxyModel::setShowAll(bool show_all)
{
  if (show_all_ == show_all)
    return;

  show_all_ = show_all;
  invalidateFilter();
}

bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
  CollisionLinearModel* m = qobject_cast<CollisionLinearModel*>(sourceModel());
  if (!(show_all_ || m->reason(source_row) <= moveit_setup_assistant::ALWAYS ||
        m->data(m->index(source_row, 2), Qt::CheckStateRole) == Qt::Checked))
    return false;  // not accepted due to check state

  const QRegExp regexp = this->filterRegExp();
  if (regexp.isEmpty())
    return true;

  return m->data(m->index(source_row, 0, source_parent), Qt::DisplayRole).toString().contains(regexp) ||
         m->data(m->index(source_row, 1, source_parent), Qt::DisplayRole).toString().contains(regexp);
}

// define a fallback comparison operator for QVariants
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
namespace {
bool operator<(const QVariant& left, const QVariant& right) {
  if (left.userType() == QVariant::Type::Int)
    return left.toInt() < right.toInt();
  else
    return left.toString() < right.toString();
}
}
#endif

bool SortFilterProxyModel::lessThan(const QModelIndex& src_left, const QModelIndex& src_right) const
{
  int row_left = src_left.row();
  int row_right = src_right.row();
  QAbstractItemModel* m = sourceModel();

  for (int i = 0, end = sort_columns_.size(); i < end && sort_columns_[i] >= 0; ++i)
  {
    int sc = sort_columns_[i];
    int role = sc == 2 ? Qt::CheckStateRole : Qt::DisplayRole;
    QVariant value_left = m->data(m->index(row_left, sc), role);
    QVariant value_right = m->data(m->index(row_right, sc), role);

    if (value_left == value_right)
      continue;

    bool smaller = (value_left < value_right);
    if (sort_orders_[i] == Qt::DescendingOrder)
      smaller = !smaller;
    return smaller;
  }
  return false;
}

void SortFilterProxyModel::sort(int column, Qt::SortOrder order)
{
  beginResetModel();
  if (column < 0)
    initSorting();
  else
  {
    // remember sorting history
    int prev_idx = sort_columns_.indexOf(column);
    if (prev_idx < 0)
      prev_idx = sort_columns_.size() - 1;
    // remove old entries
    sort_columns_.takeAt(prev_idx);
    sort_orders_.remove(prev_idx);
    // add new entries at front
    sort_columns_.insert(0, column);
    sort_orders_.insert(0, order);
  }
  QSortFilterProxyModel::sort(column, Qt::AscendingOrder);
  endResetModel();
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.20.12); FILE MERGED 2008/04/01 15:11:00 thb 1.20.12.2: #i85898# Stripping all external header guards 2008/03/31 07:23:37 rt 1.20.12.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before>#include "MetaImageStreamer.hpp"
#include "MetaImageImporter.hpp"
#include "DeviceManager.hpp"
#include "Exception.hpp"
using namespace fast;

/**
 * Dummy function to get into the class again
 */
void stubStreamThread(MetaImageStreamer * streamer) {
    streamer->producerStream();
}

DynamicImage::pointer MetaImageStreamer::getOutput() {
    if(mOutput.isValid()) {
        mOutput->setParent(mPtr.lock());

        DynamicImage::pointer newSmartPtr;
        newSmartPtr.swap(mOutput);

        return newSmartPtr;
    } else {
        return mOutput2.lock();
    }
}

MetaImageStreamer::MetaImageStreamer() {
    mOutput = DynamicImage::New();
    mOutput2 = mOutput;
    mStreamIsStarted = false;
    mIsModified = true;
    thread = NULL;
    mFirstFrameIsInserted = false;
    mDevice = DeviceManager::getInstance().getDefaultComputationDevice();
}

inline void MetaImageStreamer::execute() {
    if(!mStreamIsStarted) {
        mStreamIsStarted = true;
        thread = new boost::thread(&stubStreamThread, this);
    }

    // Wait here for first frame
    // TODO use condition variable instead
    while(!mFirstFrameIsInserted);
}

void MetaImageStreamer::setFilenameFormat(std::string str) {
    mFilenameFormat = str;
}

void MetaImageStreamer::setDevice(ExecutionDevice::pointer device) {
    mDevice = device;
}

inline std::string intToString(int number) {
    std::stringstream ss;//create a stringstream
    ss << number;//add number to the stream
    return ss.str();//return a string with the contents of the stream
}

void MetaImageStreamer::producerStream() {
    int i = 0;
    while(true) {
        std::string filename = mFilenameFormat;
        filename.replace(
                filename.find("#"),
                1,
                intToString(i));
        try {
            MetaImageImporter::pointer importer = MetaImageImporter::New();
            importer->setFilename(filename);
            importer->setDevice(mDevice);
            Image::pointer image = importer->getOutput();
            image->update();
            DynamicImage::pointer ptr = mOutput2.lock();
            if(ptr.isValid()) {
                ptr->addFrame(image);
                mFirstFrameIsInserted = true;
            } else {
                std::cout << "DynamicImage object destroyed, stream can stop." << std::endl;
                break;
            }
            i++;
        } catch(FileNotFoundException &e) {
            if(i > 0) {
                std::cout << "Reached end of stream" << std::endl;
                // Reached end of stream
                break;
            } else {
                throw e;
            }
        }
    }
}

MetaImageStreamer::~MetaImageStreamer() {
    std::cout << "Joining the thread" << std::endl;
    // TODO stop thread as well
    thread->join();
    delete thread;
}
<commit_msg>copy the streaming mode to the output dynamic image in MetaImageStreamer<commit_after>#include "MetaImageStreamer.hpp"
#include "MetaImageImporter.hpp"
#include "DeviceManager.hpp"
#include "Exception.hpp"
using namespace fast;

/**
 * Dummy function to get into the class again
 */
void stubStreamThread(MetaImageStreamer * streamer) {
    streamer->producerStream();
}

DynamicImage::pointer MetaImageStreamer::getOutput() {
    if(mOutput.isValid()) {
        mOutput->setParent(mPtr.lock());
        mOutput->setStreamingMode(this->getStreamingMode());

        DynamicImage::pointer newSmartPtr;
        newSmartPtr.swap(mOutput);

        return newSmartPtr;
    } else {
        return mOutput2.lock();
    }
}

MetaImageStreamer::MetaImageStreamer() {
    mOutput = DynamicImage::New();
    mOutput2 = mOutput;
    mStreamIsStarted = false;
    mIsModified = true;
    thread = NULL;
    mFirstFrameIsInserted = false;
    mDevice = DeviceManager::getInstance().getDefaultComputationDevice();
}

inline void MetaImageStreamer::execute() {
    if(!mStreamIsStarted) {
        mStreamIsStarted = true;
        thread = new boost::thread(&stubStreamThread, this);
    }

    // Wait here for first frame
    // TODO use condition variable instead
    while(!mFirstFrameIsInserted);
}

void MetaImageStreamer::setFilenameFormat(std::string str) {
    mFilenameFormat = str;
}

void MetaImageStreamer::setDevice(ExecutionDevice::pointer device) {
    mDevice = device;
}

inline std::string intToString(int number) {
    std::stringstream ss;//create a stringstream
    ss << number;//add number to the stream
    return ss.str();//return a string with the contents of the stream
}

void MetaImageStreamer::producerStream() {
    int i = 0;
    while(true) {
        std::string filename = mFilenameFormat;
        filename.replace(
                filename.find("#"),
                1,
                intToString(i));
        try {
            MetaImageImporter::pointer importer = MetaImageImporter::New();
            importer->setFilename(filename);
            importer->setDevice(mDevice);
            Image::pointer image = importer->getOutput();
            image->update();
            DynamicImage::pointer ptr = mOutput2.lock();
            ptr->setStreamingMode(this->getStreamingMode());
            if(ptr.isValid()) {
                ptr->addFrame(image);
                mFirstFrameIsInserted = true;
            } else {
                std::cout << "DynamicImage object destroyed, stream can stop." << std::endl;
                break;
            }
            i++;
        } catch(FileNotFoundException &e) {
            if(i > 0) {
                std::cout << "Reached end of stream" << std::endl;
                // Reached end of stream
                break;
            } else {
                throw e;
            }
        }
    }
}

MetaImageStreamer::~MetaImageStreamer() {
    std::cout << "Joining the thread" << std::endl;
    // TODO stop thread as well
    thread->join();
    delete thread;
}
<|endoftext|>