<commit_before>
#include "../../Flare.h"
#include "FlarePartInfo.h"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlarePartInfo::Construct(const FArguments& InArgs)
{
	ShowOwnershipInfo = InArgs._ShowOwnershipInfo;

	// Create the layout
	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Fill)
	[
		SNew(SHorizontalBox)

		// Part icon
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage).Image(&InArgs._Description->MeshPreviewBrush)
		]

		// Content box
		+ SHorizontalBox::Slot()
		[
			SAssignNew(Details, SVerticalBox)

			// Title and cost
			+ SVerticalBox::Slot()
			.VAlign(VAlign_Top)
			.Padding(FMargin(10))
			.AutoHeight()
			[
				SNew(SHorizontalBox)

				// Title
				+ SHorizontalBox::Slot()
				[
					SNew(STextBlock)
					.Text(InArgs._Description->Name)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Title3")
				]

				// Cost icon
				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				.AutoWidth()
				[
					SAssignNew(CostImage, SImage)
				]

				// Cost label
				+ SHorizontalBox::Slot()
				.Padding(10, 0)
				.HAlign(HAlign_Right)
				.VAlign(VAlign_Center)
				.AutoWidth()
				[
					SAssignNew(CostLabel, STextBlock)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Text")
				]
			]

			// Characteristics
			+ SVerticalBox::Slot()
			.Padding(FMargin(10, 2, 10, 2))
			.AutoHeight()
			[
				SAssignNew(InfoBox, SHorizontalBox)
			]
		]
	];

	BuildInfoBlock(InfoBox, InArgs._Description, false);

	// Toggle cost
	PartCost = InArgs._Description->Cost;
	SetOwned(InArgs._IsOwned);
}

/*----------------------------------------------------
	Content
----------------------------------------------------*/

void SFlarePartInfo::SetOwned(bool State)
{
	IsOwned = State;
	if (ShowOwnershipInfo)
	{
		if (IsOwned)
		{
			CostLabel->SetVisibility(EVisibility::Collapsed);
			CostImage->SetImage(FFlareStyleSet::GetIcon("Owned"));
		}
		else
		{
			CostLabel->SetText(FString::FromInt(PartCost));
			CostLabel->SetVisibility(EVisibility::Visible);
			CostImage->SetImage(FFlareStyleSet::GetIcon("Cost"));
		}
	}
	else
	{
		CostLabel->SetVisibility(EVisibility::Collapsed);
		CostImage->SetVisibility(EVisibility::Collapsed);
	}
}

/*----------------------------------------------------
	Helpers
----------------------------------------------------*/

void SFlarePartInfo::BuildInfoBlock(TSharedPtr<SHorizontalBox>& Box, const FFlareShipComponentDescription* Desc, bool ShowHelpers)
{
	Box->ClearChildren();

	// Armor
	AddCharacteristicToBlock(Box,
		"Armor",
		FString::FromInt(Desc->ArmorHitPoints + Desc->HitPoints),
		FFlareStyleSet::GetIcon("Armor"),
		ShowHelpers);

	// Fill in the characteristics structure for dynamic values
	for (int32 i = 0; i < Desc->Characteristics.Num(); i++)
	{
		const FFlareShipComponentCharacteristic& Characteristic = Desc->Characteristics[i];

		AddCharacteristicToBlock(Box,
			GetCharacteristicLabel(Characteristic.CharacteristicType),
			GetCharacteristicInfo(Characteristic),
			GetCharacteristicBrush(Characteristic),
			ShowHelpers);
	}
}

void SFlarePartInfo::AddCharacteristicToBlock(TSharedPtr<SHorizontalBox>& Box, FString Label, FString Value, const FSlateBrush* Icon, bool ShowHelpers)
{
	TSharedPtr<SVerticalBox> TempBox;

	Box->AddSlot().HAlign(HAlign_Fill)
		[
			SNew(SHorizontalBox)

			// Icon
			+ SHorizontalBox::Slot()
			.VAlign(VAlign_Center)
			.AutoWidth()
			[
				SNew(SImage).Image(Icon)
			]

			// Text
			+ SHorizontalBox::Slot()
			.Padding(FMargin(5, 0))
			.VAlign(VAlign_Center)
			.AutoWidth()
			[
				SAssignNew(TempBox, SVerticalBox)

				// Value
				+ SVerticalBox::Slot()
				.VAlign(VAlign_Top)
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(Value)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Title3")
				]
			]
		];

	// Helpers
	if (ShowHelpers)
	{
		TempBox->AddSlot()
			.AutoHeight()
			[
				SNew(STextBlock)
				.Text(Label)
				.TextStyle(FFlareStyleSet::Get(), "Flare.SmallText")
			];
	}
}

FString SFlarePartInfo::GetCharacteristicInfo(const FFlareShipComponentDescription* Desc, EFlarePartCharacteristicType::Type Type)
{
	for (int32 i = 0; i < Desc->Characteristics.Num(); i++)
	{
		const FFlareShipComponentCharacteristic& Characteristic = Desc->Characteristics[i];

		if (Characteristic.CharacteristicType == Type)
		{
			return GetCharacteristicInfo(Characteristic);
		}
	}

	return "";
}

FString SFlarePartInfo::GetCharacteristicInfo(const FFlareShipComponentCharacteristic& Characteristic)
{
	FString Unit;

	switch (Characteristic.CharacteristicType)
	{
		case EFlarePartCharacteristicType::AmmoRate:
			Unit += "rpm";
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Unit += "kN";
			break;
		case EFlarePartCharacteristicType::AmmoPower:
		case EFlarePartCharacteristicType::AmmoCapacity:
		case EFlarePartCharacteristicType::EngineTankDrain:
		case EFlarePartCharacteristicType::RCSAccelerationRating:
		default: break;
	}

	return FString::FromInt(Characteristic.CharacteristicValue) + " " + Unit;
}

FString SFlarePartInfo::GetCharacteristicLabel(EFlarePartCharacteristicType::Type Type)
{
	FString Label;

	switch (Type)
	{
		case EFlarePartCharacteristicType::AmmoPower:
			Label = "Power";
			break;
		case EFlarePartCharacteristicType::AmmoRate:
			Label += "Rate of fire";
			break;
		case EFlarePartCharacteristicType::AmmoCapacity:
			Label = "Magazine";
			break;
		case EFlarePartCharacteristicType::EngineTankDrain:
			Label = "Consumption";
			break;
		case EFlarePartCharacteristicType::RCSAccelerationRating:
			Label = "Turn rating";
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Label = "Thrust";
			break;

		default: break;
	}

	return Label;
}

const FSlateBrush* SFlarePartInfo::GetCharacteristicBrush(const FFlareShipComponentCharacteristic& Characteristic)
{
	const FSlateBrush* Result = NULL;

	switch (Characteristic.CharacteristicType)
	{
		case EFlarePartCharacteristicType::AmmoPower:
			Result = FFlareStyleSet::GetIcon("Shell");
			break;
		case EFlarePartCharacteristicType::AmmoRate:
			Result = FFlareStyleSet::GetIcon("Rate");
			break;
		case EFlarePartCharacteristicType::AmmoCapacity:
			Result = FFlareStyleSet::GetIcon("Ammo");
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Result = FFlareStyleSet::GetIcon("Propulsion");
			break;
		case EFlarePartCharacteristicType::RCSAccelerationRating:
			Result = FFlareStyleSet::GetIcon("RCS");
			break;
		case EFlarePartCharacteristicType::EngineTankDrain:
			Result = FFlareStyleSet::GetIcon("Tank");
			break;

		default: break;
	}

	return Result;
}
<commit_msg>Mask inappropriate characteristics<commit_after>
#include "../../Flare.h"
#include "FlarePartInfo.h"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlarePartInfo::Construct(const FArguments& InArgs)
{
	ShowOwnershipInfo = InArgs._ShowOwnershipInfo;

	// Create the layout
	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Fill)
	[
		SNew(SHorizontalBox)

		// Part icon
		+ SHorizontalBox::Slot()
		.AutoWidth()
		[
			SNew(SImage).Image(&InArgs._Description->MeshPreviewBrush)
		]

		// Content box
		+ SHorizontalBox::Slot()
		[
			SAssignNew(Details, SVerticalBox)

			// Title and cost
			+ SVerticalBox::Slot()
			.VAlign(VAlign_Top)
			.Padding(FMargin(10))
			.AutoHeight()
			[
				SNew(SHorizontalBox)

				// Title
				+ SHorizontalBox::Slot()
				[
					SNew(STextBlock)
					.Text(InArgs._Description->Name)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Title3")
				]

				// Cost icon
				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				.AutoWidth()
				[
					SAssignNew(CostImage, SImage)
				]

				// Cost label
				+ SHorizontalBox::Slot()
				.Padding(10, 0)
				.HAlign(HAlign_Right)
				.VAlign(VAlign_Center)
				.AutoWidth()
				[
					SAssignNew(CostLabel, STextBlock)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Text")
				]
			]

			// Characteristics
			+ SVerticalBox::Slot()
			.Padding(FMargin(10, 2, 10, 2))
			.AutoHeight()
			[
				SAssignNew(InfoBox, SHorizontalBox)
			]
		]
	];

	BuildInfoBlock(InfoBox, InArgs._Description, false);

	// Toggle cost
	PartCost = InArgs._Description->Cost;
	SetOwned(InArgs._IsOwned);
}

/*----------------------------------------------------
	Content
----------------------------------------------------*/

void SFlarePartInfo::SetOwned(bool State)
{
	IsOwned = State;
	if (ShowOwnershipInfo)
	{
		if (IsOwned)
		{
			CostLabel->SetVisibility(EVisibility::Collapsed);
			CostImage->SetImage(FFlareStyleSet::GetIcon("Owned"));
		}
		else
		{
			CostLabel->SetText(FString::FromInt(PartCost));
			CostLabel->SetVisibility(EVisibility::Visible);
			CostImage->SetImage(FFlareStyleSet::GetIcon("Cost"));
		}
	}
	else
	{
		CostLabel->SetVisibility(EVisibility::Collapsed);
		CostImage->SetVisibility(EVisibility::Collapsed);
	}
}

/*----------------------------------------------------
	Helpers
----------------------------------------------------*/

void SFlarePartInfo::BuildInfoBlock(TSharedPtr<SHorizontalBox>& Box, const FFlareShipComponentDescription* Desc, bool ShowHelpers)
{
	Box->ClearChildren();

	// Armor
	AddCharacteristicToBlock(Box,
		"Armor",
		FString::FromInt(Desc->ArmorHitPoints + Desc->HitPoints),
		FFlareStyleSet::GetIcon("Armor"),
		ShowHelpers);

	// Fill in the characteristics structure for dynamic values
	for (int32 i = 0; i < Desc->Characteristics.Num(); i++)
	{
		const FFlareShipComponentCharacteristic& Characteristic = Desc->Characteristics[i];

		if (Characteristic.CharacteristicType <= EFlarePartCharacteristicType::RCSAccelerationRating)
		{
			AddCharacteristicToBlock(Box,
				GetCharacteristicLabel(Characteristic.CharacteristicType),
				GetCharacteristicInfo(Characteristic),
				GetCharacteristicBrush(Characteristic),
				ShowHelpers);
		}
	}
}

void SFlarePartInfo::AddCharacteristicToBlock(TSharedPtr<SHorizontalBox>& Box, FString Label, FString Value, const FSlateBrush* Icon, bool ShowHelpers)
{
	TSharedPtr<SVerticalBox> TempBox;

	Box->AddSlot().HAlign(HAlign_Fill)
		[
			SNew(SHorizontalBox)

			// Icon
			+ SHorizontalBox::Slot()
			.VAlign(VAlign_Center)
			.AutoWidth()
			[
				SNew(SImage).Image(Icon)
			]

			// Text
			+ SHorizontalBox::Slot()
			.Padding(FMargin(5, 0))
			.VAlign(VAlign_Center)
			.AutoWidth()
			[
				SAssignNew(TempBox, SVerticalBox)

				// Value
				+ SVerticalBox::Slot()
				.VAlign(VAlign_Top)
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(Value)
					.TextStyle(FFlareStyleSet::Get(), "Flare.Title3")
				]
			]
		];

	// Helpers
	if (ShowHelpers)
	{
		TempBox->AddSlot()
			.AutoHeight()
			[
				SNew(STextBlock)
				.Text(Label)
				.TextStyle(FFlareStyleSet::Get(), "Flare.SmallText")
			];
	}
}

FString SFlarePartInfo::GetCharacteristicInfo(const FFlareShipComponentDescription* Desc, EFlarePartCharacteristicType::Type Type)
{
	for (int32 i = 0; i < Desc->Characteristics.Num(); i++)
	{
		const FFlareShipComponentCharacteristic& Characteristic = Desc->Characteristics[i];

		if (Characteristic.CharacteristicType == Type)
		{
			return GetCharacteristicInfo(Characteristic);
		}
	}

	return "";
}

FString SFlarePartInfo::GetCharacteristicInfo(const FFlareShipComponentCharacteristic& Characteristic)
{
	FString Unit;

	switch (Characteristic.CharacteristicType)
	{
		case EFlarePartCharacteristicType::AmmoRate:
			Unit += "rpm";
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Unit += "kN";
			break;
		case EFlarePartCharacteristicType::AmmoPower:
		case EFlarePartCharacteristicType::AmmoCapacity:
		case EFlarePartCharacteristicType::EngineTankDrain:
		case EFlarePartCharacteristicType::RCSAccelerationRating:
		default: break;
	}

	return FString::FromInt(Characteristic.CharacteristicValue) + " " + Unit;
}

FString SFlarePartInfo::GetCharacteristicLabel(EFlarePartCharacteristicType::Type Type)
{
	FString Label;

	switch (Type)
	{
		case EFlarePartCharacteristicType::AmmoPower:
			Label = "Power";
			break;
		case EFlarePartCharacteristicType::AmmoRate:
			Label += "Rate of fire";
			break;
		case EFlarePartCharacteristicType::AmmoCapacity:
			Label = "Magazine";
			break;
		case EFlarePartCharacteristicType::EngineTankDrain:
			Label = "Consumption";
			break;
		case EFlarePartCharacteristicType::RCSAccelerationRating:
			Label = "Turn rating";
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Label = "Thrust";
			break;

		default: break;
	}

	return Label;
}

const FSlateBrush* SFlarePartInfo::GetCharacteristicBrush(const FFlareShipComponentCharacteristic& Characteristic)
{
	const FSlateBrush* Result = NULL;

	switch (Characteristic.CharacteristicType)
	{
		case EFlarePartCharacteristicType::AmmoPower:
			Result = FFlareStyleSet::GetIcon("Shell");
			break;
		case EFlarePartCharacteristicType::AmmoRate:
			Result = FFlareStyleSet::GetIcon("Rate");
			break;
		case EFlarePartCharacteristicType::AmmoCapacity:
			Result = FFlareStyleSet::GetIcon("Ammo");
			break;
		case EFlarePartCharacteristicType::EnginePower:
			Result = FFlareStyleSet::GetIcon("Propulsion");
			break;
		case EFlarePartCharacteristicType::RCSAccelerationRating:
			Result = FFlareStyleSet::GetIcon("RCS");
			break;
		case EFlarePartCharacteristicType::EngineTankDrain:
			Result = FFlareStyleSet::GetIcon("Tank");
			break;

		default: break;
	}

	return Result;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DriverManager.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:10:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_
#include "java/sql/DriverManager.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
//**************************************************************
//************ Class: java.sql.DriverManager
//**************************************************************

jclass java_sql_DriverManager::theClass = 0;

java_sql_DriverManager::~java_sql_DriverManager()
{}

jclass java_sql_DriverManager::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
        if( !t.pEnv ) return (jclass)0;
        jclass tempClass = t.pEnv->FindClass("java/sql/DriverManager"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_DriverManager::saveClassRef( jclass pClass )
{
    if( pClass==0  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

jobject java_sql_DriverManager::getDriver(const ::rtl::OUString &url)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jvalue args[1];
        // Parameter konvertieren
        args[0].l = convertwchar_tToJavaString(t.pEnv,url);
        // temporaere Variable initialisieren
        static char * cSignature = "(Ljava/lang/String;)Ljava/sql/Driver;";
        static char * cMethodName = "getDriver";
        // Java-Call absetzen
        static jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
            // und aufraeumen

        } //mID
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        return t.pEnv->NewGlobalRef( out );
    } //t.pEnv

    return out;
}

void java_sql_DriverManager::setLoginTimeout(sal_Int32 _par0)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    jobject out(0);
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "(I)V";
        static char * cMethodName = "setLoginTimeout";
        // Java-Call absetzen
        static jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
            t.pEnv->CallStaticVoidMethod(getMyClass(), mID, _par0);
            ThrowSQLException(t.pEnv,0);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}

<commit_msg>INTEGRATION: CWS warnings01 (1.9.30); FILE MERGED 2005/11/21 10:07:47 fs 1.9.30.2: #i57457# warning-free code on unx* 2005/11/07 14:43:41 fs 1.9.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DriverManager.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:34:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_
#include "java/sql/DriverManager.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif

using namespace connectivity;
//**************************************************************
//************ Class: java.sql.DriverManager
//**************************************************************

jclass java_sql_DriverManager::theClass = 0;

java_sql_DriverManager::~java_sql_DriverManager()
{}

jclass java_sql_DriverManager::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
        if( !t.pEnv ) return (jclass)0;
        jclass tempClass = t.pEnv->FindClass("java/sql/DriverManager"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_DriverManager::saveClassRef( jclass pClass )
{
    if( pClass==0  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

jobject java_sql_DriverManager::getDriver(const ::rtl::OUString &url)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jvalue args[1];
        // Parameter konvertieren
        args[0].l = convertwchar_tToJavaString(t.pEnv,url);
        // temporaere Variable initialisieren
        static const char * cSignature = "(Ljava/lang/String;)Ljava/sql/Driver;";
        static const char * cMethodName = "getDriver";
        // Java-Call absetzen
        static jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
        {
            out = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
            // und aufraeumen

        } //mID
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        return t.pEnv->NewGlobalRef( out );
    } //t.pEnv

    return out;
}

void java_sql_DriverManager::setLoginTimeout(sal_Int32 _par0)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static const char * cSignature = "(I)V";
        static const char * cMethodName = "setLoginTimeout";
        // Java-Call absetzen
        static jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID )
            t.pEnv->CallStaticVoidMethod(getMyClass(), mID, _par0);
            ThrowSQLException(t.pEnv,0);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
}

<|endoftext|>


<commit_before>//
//  ADB.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 31/10/2020.
//  Copyright © 2020 Thomas Harte. All rights reserved.
//

#include "ADB.hpp"

#include <cassert>
#include <cstdio>
#include <iostream>

// TEST.
#include "../../../InstructionSets/M50740/Parser.hpp"
#include "../../../InstructionSets/Disassembler.hpp"

#define LOG_PREFIX "[ADB GLU] "
#include "../../../Outputs/Log.hpp"

using namespace Apple::IIgs::ADB;

namespace {

// Flags affecting the CPU-visible status register.
enum class CPUFlags: uint8_t {
	MouseDataFull = 0x80,
	MouseInterruptEnabled = 0x40,
	CommandDataIsValid = 0x20,
	CommandDataInterruptEnabled = 0x10,
	KeyboardDataFull = 0x08,
	KeyboardDataInterruptEnabled = 0x04,
	MouseXIsAvailable = 0x02,
	CommandRegisterFull = 0x01,
};

// Flags affecting the microcontroller-visible register.
enum class MicrocontrollerFlags: uint8_t {
	CommandRegisterFull = 0x40,
};

}

GLU::GLU() :
	executor_(*this),
	bus_(HalfCycles(1'789'772)),
	controller_id_(bus_.add_device()),
	mouse_(bus_),
	keyboard_(bus_) {}

// MARK: - External interface.

uint8_t GLU::get_keyboard_data() {
	// The classic Apple II serial keyboard register:
	// b7:		key strobe.
	// b6–b0:	ASCII code.
	return (registers_[0] & 0x7f) | ((status_ & uint8_t(CPUFlags::KeyboardDataFull)) ? 0x80 : 0x00);
}

void GLU::clear_key_strobe() {
	// Clears the key strobe of the classic Apple II serial keyboard register.
	status_ &= ~uint8_t(CPUFlags::KeyboardDataFull);
}

uint8_t GLU::get_any_key_down() {
	// The Apple IIe check-for-any-key-down bit.
	return registers_[5];
}

uint8_t GLU::get_mouse_data() {
	// Alternates between returning x and y values.
	//
	// b7: 		1 = button is up; 0 = button is down.
	// b6:		delta sign bit; 1 = negative.
	// b5–b0:	mouse delta.
	return 0x80;	// TODO. Should alternate between registers 2 and 3.
}

uint8_t GLU::get_modifier_status() {
	// b7:		1 = command key pressed; 0 = not.
	// b6:		option key.
	// b5:		1 = modifier key latch has been updated, no key has been pressed; 0 = not.
	// b4:		any numeric keypad key.
	// b3:		a key is down.
	// b2:		caps lock is pressed.
	// b1:		control key.
	// b0:		shift key.
	return registers_[6];
}

uint8_t GLU::get_data() {
	// b0–2:	number of data bytes to be returned.
	// b3:		1 = a valid service request is pending; 0 = no request pending.
	// b4:		1 = control, command and delete keys have been pressed simultaneously; 0 = they haven't.
	// b5:		1 = control, command and reset have all been pressed together; 0 = they haven't.
	// b6:		1 = ADB controller encountered an error and reset itself; 0 = no error.
	// b7:		1 = ADB has received a response from the addressed ADB device; 0 = no respone.
//	status_ &= ~(CPUFlags::CommandDataIsValid | CPUFlags::CommandRegisterFull);
	return registers_[7];
}

uint8_t GLU::get_status() {
	// b7:	1 = mouse data register is full; 0 = empty.
	// b6:	1 = mouse interrupt is enabled.
	// b5:	1 = command/data has valid data.
	// b4:	1 = command/data interrupt is enabled.
	// b3:	1 = keyboard data is full.
	// b2:	1 = keyboard data interrupt is enabled.
	// b1:	1 = mouse x-data is available; 0 = y.
	// b0:	1 = command register is full (set when command is written); 0 = empty (cleared when data is read).
	return status_;
}

void GLU::set_status(uint8_t status) {
	// This permits only the interrupt flags to be set.
	constexpr uint8_t interrupt_flags =
		uint8_t(CPUFlags::MouseInterruptEnabled) |
		uint8_t(CPUFlags::CommandDataInterruptEnabled) |
		uint8_t(CPUFlags::KeyboardDataInterruptEnabled);
	status_ = (status_ & ~interrupt_flags) | (status & interrupt_flags);
}

void GLU::set_command(uint8_t command) {
	registers_[1] = command;
	registers_[4] |= uint8_t(MicrocontrollerFlags::CommandRegisterFull);
	status_ |= uint8_t(CPUFlags::CommandRegisterFull);
}

// MARK: - Setup and run.

void GLU::set_microcontroller_rom(const std::vector<uint8_t> &rom) {
	executor_.set_rom(rom);

	// TEST invocation.
/*	InstructionSet::Disassembler<InstructionSet::M50740::Parser, 0x1fff, InstructionSet::M50740::Instruction, uint8_t, uint16_t> disassembler;
	disassembler.disassemble(rom.data(), 0x1000, uint16_t(rom.size()), 0x1000);

	const auto instructions = disassembler.instructions();
	const auto entry_points = disassembler.entry_points();
	for(const auto &pair : instructions) {
		std::cout << std::hex << pair.first << "\t\t";
		if(entry_points.find(pair.first) != entry_points.end()) {
			std::cout << "L" << pair.first << "\t";
		} else {
			std::cout << "\t\t";
		}
		std::cout << operation_name(pair.second.operation) << " ";
		std::cout << address(pair.second.addressing_mode, &rom[pair.first - 0x1000], pair.first);

		std::cout << std::endl;
	}*/
}

void GLU::run_for(Cycles cycles) {
	executor_.run_for(cycles);
}

// MARK: - M50470 port handler

void GLU::set_port_output(int port, uint8_t value) {
	switch(port) {
		case 0:
			register_latch_ = value;
		break;
		case 1:
//			printf("Keyboard write: %02x???\n", value);
		break;
		case 2: {
//			printf("ADB data line input: %d???\n", value >> 7);
//			printf("IIe keyboard reset line: %d\n", (value >> 6)&1);
//			printf("IIgs reset line: %d\n", (value >> 5)&1);
//			printf("GLU strobe: %d\n", (value >> 4)&1);
//			printf("Select GLU register: %d [%02x]\n", value & 0xf, value);

			register_address_ = value & 0xf;

			// This is an ugly hack, I think. Per Neil Parker's Inside the Apple IIGS ADB Controller
			// http://nparker.llx.com/a2/adb.html#external:
			//
			// The protocol for reading an ADB GLU register is as follows:
			//
			// 1. Put the register number of the ADB GLU register in port P2 bits 0-3.
			// 2. Clear bit 4 of port P2, read the data from P0, and set bit 4 of P0.
			//
			// The protocol for writing a GLU register is similar:
			//
			// 1. Write the register number to port P2 bits 0-3.
			// 2. Write the data to port P0.
			// 3. Configure port P0 for output by writing $FF to $E1.
			// 4. Clear bit 4 of P2, and immediately set it again.
			// 5. Configure port P0 for input by writing 0 to $E1.
			//
			// ---
			//
			// I tried: linking a read or write to rising or falling edges of the strobe.
			// Including with hysteresis as per the "immediately" (which, in practice, seems
			// to mean "in the very next instruction", i.e. 5 cycles later). That didn't seem
			// properly to differentiate.
			//
			// So I'm focussing on the "configure port P0 for output" bit. Which I don't see
			// would be visible here unless it is actually an exposed signal, which is unlikely.
			//
			// Ergo: ugly. HACK.
			const bool strobe = value & 0x10;
			if(strobe != register_strobe_) {
				register_strobe_ = strobe;

				if(!register_strobe_) {
					if(executor_.get_output_mask(0)) {
						registers_[register_address_] = register_latch_;
						switch(register_address_) {
							default: break;
							case 0:		status_ |= uint8_t(CPUFlags::KeyboardDataFull);		break;
							case 7:		status_ |= uint8_t(CPUFlags::CommandDataIsValid);	break;
						}
					} else {
						register_latch_ = registers_[register_address_];
						switch(register_address_) {
							default: break;
							case 1:
								registers_[4] &= ~uint8_t(MicrocontrollerFlags::CommandRegisterFull);
								status_ &= ~uint8_t(CPUFlags::CommandRegisterFull);
							break;
						}
					}
				}
			}
		} break;
		case 3:
			if(modifier_state_ != (value & 0x30)) {
				modifier_state_ = value & 0x30;
				LOG("Modifier state: " << int(value & 0x30));
			}

			// Output is inverted respective to input; the microcontroller
			// sets a value of '1' in order to pull the ADB bus low.
			bus_.set_device_output(controller_id_, !(value & 0x08));
		break;

		default: assert(false);
	}
}

bool GLU::get_command_button() const {
	return modifier_state_ & 0x20;
}

bool GLU::get_option_button() const {
	return modifier_state_ & 0x10;
}

uint8_t GLU::get_port_input(int port) {
	switch(port) {
		case 0:	return register_latch_;
		case 1:
//			printf("IIe keyboard read\n");
		return 0x06;
		case 2:
//			printf("ADB data line input, etc\n");
		return bus_.get_state() ? 0x80 : 0x00;
		case 3:
//			printf("ADB data line output, etc\n");
		return 0x00;

		default: assert(false);
	}
	return 0xff;
}

void GLU::run_ports_for(Cycles cycles) {
	bus_.run_for(cycles);
}

void GLU::set_vertical_blank(bool is_blank) {
	executor_.set_interrupt_line(is_blank);
}
<commit_msg>Takes a further stab at ::CommandDataIsValid.<commit_after>//
//  ADB.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 31/10/2020.
//  Copyright © 2020 Thomas Harte. All rights reserved.
//

#include "ADB.hpp"

#include <cassert>
#include <cstdio>
#include <iostream>

// TEST.
#include "../../../InstructionSets/M50740/Parser.hpp"
#include "../../../InstructionSets/Disassembler.hpp"

#define LOG_PREFIX "[ADB GLU] "
#include "../../../Outputs/Log.hpp"

using namespace Apple::IIgs::ADB;

namespace {

// Flags affecting the CPU-visible status register.
enum class CPUFlags: uint8_t {
	MouseDataFull = 0x80,
	MouseInterruptEnabled = 0x40,
	CommandDataIsValid = 0x20,
	CommandDataInterruptEnabled = 0x10,
	KeyboardDataFull = 0x08,
	KeyboardDataInterruptEnabled = 0x04,
	MouseXIsAvailable = 0x02,
	CommandRegisterFull = 0x01,
};

// Flags affecting the microcontroller-visible register.
enum class MicrocontrollerFlags: uint8_t {
	CommandRegisterFull = 0x40,
};

}

GLU::GLU() :
	executor_(*this),
	bus_(HalfCycles(1'789'772)),
	controller_id_(bus_.add_device()),
	mouse_(bus_),
	keyboard_(bus_) {}

// MARK: - External interface.

uint8_t GLU::get_keyboard_data() {
	// The classic Apple II serial keyboard register:
	// b7:		key strobe.
	// b6–b0:	ASCII code.
	return (registers_[0] & 0x7f) | ((status_ & uint8_t(CPUFlags::KeyboardDataFull)) ? 0x80 : 0x00);
}

void GLU::clear_key_strobe() {
	// Clears the key strobe of the classic Apple II serial keyboard register.
	status_ &= ~uint8_t(CPUFlags::KeyboardDataFull);
}

uint8_t GLU::get_any_key_down() {
	// The Apple IIe check-for-any-key-down bit.
	return registers_[5];
}

uint8_t GLU::get_mouse_data() {
	// Alternates between returning x and y values.
	//
	// b7: 		1 = button is up; 0 = button is down.
	// b6:		delta sign bit; 1 = negative.
	// b5–b0:	mouse delta.
	return 0x80;	// TODO. Should alternate between registers 2 and 3.
}

uint8_t GLU::get_modifier_status() {
	// b7:		1 = command key pressed; 0 = not.
	// b6:		option key.
	// b5:		1 = modifier key latch has been updated, no key has been pressed; 0 = not.
	// b4:		any numeric keypad key.
	// b3:		a key is down.
	// b2:		caps lock is pressed.
	// b1:		control key.
	// b0:		shift key.
	return registers_[6];
}

uint8_t GLU::get_data() {
	// b0–2:	number of data bytes to be returned.
	// b3:		1 = a valid service request is pending; 0 = no request pending.
	// b4:		1 = control, command and delete keys have been pressed simultaneously; 0 = they haven't.
	// b5:		1 = control, command and reset have all been pressed together; 0 = they haven't.
	// b6:		1 = ADB controller encountered an error and reset itself; 0 = no error.
	// b7:		1 = ADB has received a response from the addressed ADB device; 0 = no respone.
	status_ &= ~uint8_t(CPUFlags::CommandDataIsValid);
	return registers_[7];
}

uint8_t GLU::get_status() {
	// b7:	1 = mouse data register is full; 0 = empty.
	// b6:	1 = mouse interrupt is enabled.
	// b5:	1 = command/data has valid data.
	// b4:	1 = command/data interrupt is enabled.
	// b3:	1 = keyboard data is full.
	// b2:	1 = keyboard data interrupt is enabled.
	// b1:	1 = mouse x-data is available; 0 = y.
	// b0:	1 = command register is full (set when command is written); 0 = empty (cleared when data is read).
	return status_;
}

void GLU::set_status(uint8_t status) {
	// This permits only the interrupt flags to be set.
	constexpr uint8_t interrupt_flags =
		uint8_t(CPUFlags::MouseInterruptEnabled) |
		uint8_t(CPUFlags::CommandDataInterruptEnabled) |
		uint8_t(CPUFlags::KeyboardDataInterruptEnabled);
	status_ = (status_ & ~interrupt_flags) | (status & interrupt_flags);
}

void GLU::set_command(uint8_t command) {
	registers_[1] = command;
	registers_[4] |= uint8_t(MicrocontrollerFlags::CommandRegisterFull);
	status_ |= uint8_t(CPUFlags::CommandRegisterFull);
}

// MARK: - Setup and run.

void GLU::set_microcontroller_rom(const std::vector<uint8_t> &rom) {
	executor_.set_rom(rom);

	// TEST invocation.
/*	InstructionSet::Disassembler<InstructionSet::M50740::Parser, 0x1fff, InstructionSet::M50740::Instruction, uint8_t, uint16_t> disassembler;
	disassembler.disassemble(rom.data(), 0x1000, uint16_t(rom.size()), 0x1000);

	const auto instructions = disassembler.instructions();
	const auto entry_points = disassembler.entry_points();
	for(const auto &pair : instructions) {
		std::cout << std::hex << pair.first << "\t\t";
		if(entry_points.find(pair.first) != entry_points.end()) {
			std::cout << "L" << pair.first << "\t";
		} else {
			std::cout << "\t\t";
		}
		std::cout << operation_name(pair.second.operation) << " ";
		std::cout << address(pair.second.addressing_mode, &rom[pair.first - 0x1000], pair.first);

		std::cout << std::endl;
	}*/
}

void GLU::run_for(Cycles cycles) {
	executor_.run_for(cycles);
}

// MARK: - M50470 port handler

void GLU::set_port_output(int port, uint8_t value) {
	switch(port) {
		case 0:
			register_latch_ = value;
		break;
		case 1:
//			printf("Keyboard write: %02x???\n", value);
		break;
		case 2: {
//			printf("ADB data line input: %d???\n", value >> 7);
//			printf("IIe keyboard reset line: %d\n", (value >> 6)&1);
//			printf("IIgs reset line: %d\n", (value >> 5)&1);
//			printf("GLU strobe: %d\n", (value >> 4)&1);
//			printf("Select GLU register: %d [%02x]\n", value & 0xf, value);

			register_address_ = value & 0xf;

			// This is an ugly hack, I think. Per Neil Parker's Inside the Apple IIGS ADB Controller
			// http://nparker.llx.com/a2/adb.html#external:
			//
			// The protocol for reading an ADB GLU register is as follows:
			//
			// 1. Put the register number of the ADB GLU register in port P2 bits 0-3.
			// 2. Clear bit 4 of port P2, read the data from P0, and set bit 4 of P0.
			//
			// The protocol for writing a GLU register is similar:
			//
			// 1. Write the register number to port P2 bits 0-3.
			// 2. Write the data to port P0.
			// 3. Configure port P0 for output by writing $FF to $E1.
			// 4. Clear bit 4 of P2, and immediately set it again.
			// 5. Configure port P0 for input by writing 0 to $E1.
			//
			// ---
			//
			// I tried: linking a read or write to rising or falling edges of the strobe.
			// Including with hysteresis as per the "immediately" (which, in practice, seems
			// to mean "in the very next instruction", i.e. 5 cycles later). That didn't seem
			// properly to differentiate.
			//
			// So I'm focussing on the "configure port P0 for output" bit. Which I don't see
			// would be visible here unless it is actually an exposed signal, which is unlikely.
			//
			// Ergo: ugly. HACK.
			const bool strobe = value & 0x10;
			if(strobe != register_strobe_) {
				register_strobe_ = strobe;

				if(!register_strobe_) {
					if(executor_.get_output_mask(0)) {
						registers_[register_address_] = register_latch_;
						switch(register_address_) {
							default: break;
							case 0:		status_ |= uint8_t(CPUFlags::KeyboardDataFull);		break;
							case 7:		status_ |= uint8_t(CPUFlags::CommandDataIsValid);	break;
						}
					} else {
						register_latch_ = registers_[register_address_];
						switch(register_address_) {
							default: break;
							case 1:
								registers_[4] &= ~uint8_t(MicrocontrollerFlags::CommandRegisterFull);
								status_ &= ~uint8_t(CPUFlags::CommandRegisterFull);
							break;
						}
					}
				}
			}
		} break;
		case 3:
			if(modifier_state_ != (value & 0x30)) {
				modifier_state_ = value & 0x30;
				LOG("Modifier state: " << int(value & 0x30));
			}

			// Output is inverted respective to input; the microcontroller
			// sets a value of '1' in order to pull the ADB bus low.
			bus_.set_device_output(controller_id_, !(value & 0x08));
		break;

		default: assert(false);
	}
}

bool GLU::get_command_button() const {
	return modifier_state_ & 0x20;
}

bool GLU::get_option_button() const {
	return modifier_state_ & 0x10;
}

uint8_t GLU::get_port_input(int port) {
	switch(port) {
		case 0:	return register_latch_;
		case 1:
//			printf("IIe keyboard read\n");
		return 0x06;
		case 2:
//			printf("ADB data line input, etc\n");
		return bus_.get_state() ? 0x80 : 0x00;
		case 3:
//			printf("ADB data line output, etc\n");
		return 0x00;

		default: assert(false);
	}
	return 0xff;
}

void GLU::run_ports_for(Cycles cycles) {
	bus_.run_for(cycles);
}

void GLU::set_vertical_blank(bool is_blank) {
	executor_.set_interrupt_line(is_blank);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AResultSetMetaData.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:53:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif

#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ARESULTSET_HXX_
#include "ado/AResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif

namespace connectivity
{
    namespace ado
    {

        //**************************************************************
        //************ Class: ResultSetMetaData
        //**************************************************************
                typedef ::cppu::WeakImplHelper1<        ::com::sun::star::sdbc::XResultSetMetaData>   OResultSetMetaData_BASE;

        class OResultSetMetaData :  public  OResultSetMetaData_BASE
        {
            friend class OResultSet;

            ADORecordset*   m_pRecordSet;
            sal_Int32       m_nColCount;

            sal_Int32 MapADOType2Jdbc(DataTypeEnum eType);
        private:
            OResultSetMetaData( const OResultSetMetaData& );            // never implemented
            OResultSetMetaData& operator=( const OResultSetMetaData& ); // never implemented

        public:
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OResultSetMetaData( ADORecordset* _pRecordSet)
                    :   m_pRecordSet(_pRecordSet),
                        m_nColCount(-1){m_pRecordSet->AddRef();}
            ~OResultSetMetaData();

            virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_

<commit_msg>INTEGRATION: CWS dba21fini (1.4.196); FILE MERGED 2006/10/27 08:14:34 oj 1.4.196.1: #142400# check recordset<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AResultSetMetaData.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 14:35:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif

#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ARESULTSET_HXX_
#include "ado/AResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif

namespace connectivity
{
    namespace ado
    {

        //**************************************************************
        //************ Class: ResultSetMetaData
        //**************************************************************
                typedef ::cppu::WeakImplHelper1<        ::com::sun::star::sdbc::XResultSetMetaData>   OResultSetMetaData_BASE;

        class OResultSetMetaData :  public  OResultSetMetaData_BASE
        {
            friend class OResultSet;

            ADORecordset*   m_pRecordSet;
            sal_Int32       m_nColCount;

            sal_Int32 MapADOType2Jdbc(DataTypeEnum eType);
        private:
            OResultSetMetaData( const OResultSetMetaData& );            // never implemented
            OResultSetMetaData& operator=( const OResultSetMetaData& ); // never implemented

        protected:
            virtual ~OResultSetMetaData();
        public:
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OResultSetMetaData( ADORecordset* _pRecordSet);

            virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include "icmswriter.h"

using namespace google::protobuf::io;

ICMSWriter::ICMSWriter()
{
	m_enabled = false;
}

ICMSWriter::~ICMSWriter()
{
	if (m_enabled)
		close();
}

bool ICMSWriter::open(const char *fn)
{

	m_os.open(fn, std::ofstream::binary | std::ofstream::trunc);
	if (m_os.fail())
		return false;

	m_w = 0;
	m_r = 0;

	fprintf(stdout,"ICMSWriter: started logging to %s.\n",fn);

	m_enabled = true;

	return true;
}

bool ICMSWriter::close()
{
	if (!write())
		return false;
	m_enabled = false;

	m_os.flush();
	if (m_os.fail())
		return false;
	m_os.close();

	m_w = 0;
	m_r = 0;
	return true;
}

bool ICMSWriter::add(ICMS *o)
{
	if (!m_enabled)
		return true;

	long w = m_w; // atomic;

	unsigned int tmp = ICMS_MAGIC;
	memcpy(&m_buf[w & ICMS_MASK], &tmp, sizeof(tmp));
	w += sizeof(tmp);

	unsigned int sz = o->ByteSize();
	memcpy(&m_buf[w & ICMS_MASK], &sz, sizeof(sz));
	w += sizeof(sz);

	//printf("packet sz: %d\n",sz);
	o->SerializeToArray(&m_buf[w & ICMS_MASK], sz);
	w += sz;

	m_w = w; // atomic

	return true;
}

bool ICMSWriter::write()   // call from one and only one thread
{
	if (!m_enabled)
		return true;

	long w = m_w;   // atomic
	if (w-m_r <= 0)
		return true;

	// we can write multiple packets at once,
	// but we need to be aligned on magic
	unsigned int magic;
	memcpy(&magic, &m_buf[m_r & ICMS_MASK], sizeof(magic));

	if (magic != ICMS_MAGIC) {
		printf("magic problem!\n");
		return false;
	}

	m_os.write(&m_buf[m_r & ICMS_MASK], w-m_r);
	if (m_os.fail()) {
		fprintf(stderr,"ERROR: ICMSWriter write failed!\n");
		return false;
	}
	m_r = w;    // atomic

	return true;
}

bool ICMSWriter::enabled()
{
	return m_enabled;
}

float ICMSWriter::capacity()
{
	return (float)(m_w-m_r)/ICMS_BUF_SIZE;
}

long ICMSWriter::bytes()
{
	return m_r * sizeof(char);
}<commit_msg>several bugfixes/optimizations for icmswriter (v2) from tim<commit_after>#include <iostream>
#include <fstream>
#include "icmswriter.h"

using namespace google::protobuf::io;

ICMSWriter::ICMSWriter()
{
	m_enabled = false;
}

ICMSWriter::~ICMSWriter()
{
	if (m_enabled)
		close();
}

bool ICMSWriter::open(const char *fn)
{

	m_os.open(fn, std::ofstream::binary | std::ofstream::trunc);
	if (m_os.fail())
		return false;

	m_w = 0;
	m_r = 0;

	fprintf(stdout,"ICMSWriter: started logging to %s.\n",fn);

	m_enabled = true;

	return true;
}

bool ICMSWriter::close()
{
	if (!write())
		return false;
	m_enabled = false;

	m_os.flush();
	if (m_os.fail())
		return false;
	m_os.close();

	m_w = 0;
	m_r = 0;
	return true;
}

bool ICMSWriter::add(ICMS *o)
{
	if (!m_enabled)
		return true;

	long w = m_w; // atomic;

	unsigned int magic = ICMS_MAGIC;
	unsigned int sz = o->ByteSize();

	unsigned int *tmp = (unsigned int*)malloc(sizeof(magic)+sizeof(sz)+sz);
	unsigned int* u = tmp;
	*u++ = magic;
	*u++ = sz;
	o->SerializeToArray((void*)u, sz);
	char* cp = (char*)tmp;
	for (int i=0; i<sz+8; i++) {
		m_buf[w & ICMS_MASK] = cp[i];
		w++;
	}

	m_w = w; // atomic

	free(tmp);

	return true;
}

bool ICMSWriter::write()   // call from one and only one thread
{
	if (!m_enabled)
		return true;

	long w = m_w;   // atomic

	while(m_r<w) {
		m_os.write(&(m_buf[m_r & ICMS_MASK]), 1);
		if (m_os.fail()) {
			fprintf(stderr,"ERROR: ICMSWriter write failed!\n");
			return false;
		}
		m_r++; // atomic
	}
	return true;
}

bool ICMSWriter::enabled()
{
	return m_enabled;
}

float ICMSWriter::capacity()
{
	return (float)(m_w-m_r)/ICMS_BUF_SIZE;
}

long ICMSWriter::bytes()
{
	return m_r * sizeof(char);
}<|endoftext|>


<commit_before>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "../Core/Context.h"
#include "../Resource/ResourceCache.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneEvents.h"
#include "../Urho2D/AnimatedSprite2D.h"
#include "../Urho2D/Animation2D.h"
#include "../Urho2D/AnimationSet2D.h"
#include "../Urho2D/Sprite2D.h"
#include "../Urho2D/StaticSprite2D.h"

#include "../DebugNew.h"

namespace Urho3D
{

extern const char* URHO2D_CATEGORY;
extern const char* blendModeNames[];

const char* loopModeNames[] =
{
    "Default",
    "ForceLooped",
    "ForceClamped",
    0
};

AnimatedSprite2D::AnimatedSprite2D(Context* context) :
    StaticSprite2D(context),
    speed_(1.0f),
    loopMode_(LM_DEFAULT),
    looped_(false),
    currentTime_(0.0f),
    numTracks_(0)
{
}

AnimatedSprite2D::~AnimatedSprite2D()
{
}

void AnimatedSprite2D::RegisterObject(Context* context)
{
    context->RegisterFactory<AnimatedSprite2D>(URHO2D_CATEGORY);

    COPY_BASE_ATTRIBUTES(StaticSprite2D);
    REMOVE_ATTRIBUTE("Sprite");
    ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
    MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef, ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
    ACCESSOR_ATTRIBUTE("Animation", GetAnimation, SetAnimationAttr, String, String::EMPTY, AM_DEFAULT);
    ENUM_ACCESSOR_ATTRIBUTE("Loop Mode", GetLoopMode, SetLoopMode, LoopMode2D, loopModeNames, LM_DEFAULT, AM_DEFAULT);
}

void AnimatedSprite2D::OnSetEnabled()
{
    StaticSprite2D::OnSetEnabled();

    bool enabled = IsEnabledEffective();

    Scene* scene = GetScene();
    if (scene)
    {
        if (enabled)
            SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
        else
            UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
    }

    for (unsigned i = 0; i < trackNodes_.Size(); ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetEnabled(enabled);
    }
}

void AnimatedSprite2D::SetSpeed(float speed)
{
    speed_ = speed;
    MarkNetworkUpdate();
}

void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name, LoopMode2D loopMode)
{
    animationSet_ = animationSet;

    SetAnimation(name, loopMode);
}

void AnimatedSprite2D::SetAnimation(const String& name, LoopMode2D loopMode)
{
    animationName_ = name;

    if (animationSet_)
        SetAnimation(animationSet_->GetAnimation(animationName_), loopMode);
}

void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
{
    if (animationSet == animationSet_)
        return;

    animationSet_ = animationSet;

    SetAnimation(animationName_, loopMode_);
}

void AnimatedSprite2D::SetLoopMode(LoopMode2D loopMode)
{
    if (!animation_)
        return;

    loopMode_ = loopMode;

    switch (loopMode_)
    {
    case LM_FORCE_LOOPED:
        looped_ = true;
        break;

    case LM_FORCE_CLAMPED:
        looped_ = false;
        break;

    default:
        looped_ = animation_->IsLooped();
        break;
    }
}

AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
{
    return animationSet_;
}

Node* AnimatedSprite2D::GetRootNode() const
{
    return rootNode_;
}

void AnimatedSprite2D::SetAnimationSetAttr(const ResourceRef& value)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
}

ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
{
    return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
}

void AnimatedSprite2D::OnNodeSet(Node* node)
{
    StaticSprite2D::OnNodeSet(node);

    if (node)
    {
        Scene* scene = GetScene();
        if (scene && IsEnabledEffective())
            SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
    }
    else
    {
        if (rootNode_)
            rootNode_->Remove();

        rootNode_ = 0;
        numTracks_ = 0;
        trackNodes_.Clear();
        trackNodeInfos_.Clear();
    }
}

void AnimatedSprite2D::SetAnimationAttr(const String& name)
{
    animationName_ = name;

    if (animationSet_)
        SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
}

void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
{
    boundingBox_.Clear();
    worldBoundingBox_.Clear();

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
    }

    boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
}

void AnimatedSprite2D::OnDrawOrderChanged()
{
    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetLayer(layer_);
    }
}

void AnimatedSprite2D::OnFlipChanged()
{
    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        staticSprite->SetFlip(flipX_, flipY_);
    }

    // For editor paused mode
    UpdateAnimation(0.0f);
}

void AnimatedSprite2D::UpdateSourceBatches()
{
    sourceBatchesDirty_ = false;
}

void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
{
    if (animation == animation_)
    {
        SetLoopMode(loopMode_);

        currentTime_ = 0.0f;
        UpdateAnimation(0.0f);
        return;
    }

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (trackNodes_[i])
            trackNodes_[i]->SetEnabled(false);
    }

    numTracks_ = 0;
    trackNodes_.Clear();
    trackNodeInfos_.Clear();

    animation_ = animation;

    if (!animation_)
        return;

    currentTime_ = 0.0f;

    if (!rootNode_)
    {
        rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
        rootNode_->SetTemporary(true);
    }

    numTracks_ = animation_->GetNumTracks();
    trackNodes_.Resize(numTracks_);
    trackNodeInfos_.Resize(numTracks_);

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        const AnimationTrack2D& track = animation->GetTrack(i);
        SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));

        StaticSprite2D* staticSprite = 0;
        if (trackNode)
        {
            // Enable track node
            trackNode->SetEnabled(true);

            // Get StaticSprite2D component
            if (track.hasSprite_)
                staticSprite = trackNode->GetComponent<StaticSprite2D>();
        }
        else
        {
            // Create new track node
            trackNode = rootNode_->CreateChild(track.name_, LOCAL);
            trackNode->SetTemporary(true);

            // Create StaticSprite2D component
            if (track.hasSprite_)
            {
                staticSprite = trackNode->CreateComponent<StaticSprite2D>();
                staticSprite->SetEnabled(IsEnabledEffective());
            }
        }

        if (staticSprite)
        {
            staticSprite->SetLayer(layer_);
            staticSprite->SetBlendMode(blendMode_);
            staticSprite->SetFlip(flipX_, flipY_);
            staticSprite->SetUseHotSpot(true);
        }

        trackNodes_[i] = trackNode;

        trackNodeInfos_[i].hasSprite = track.hasSprite_;
    }

    SetLoopMode(loopMode);
    UpdateAnimation(0.0f);

    MarkNetworkUpdate();
}

void AnimatedSprite2D::UpdateAnimation(float timeStep)
{
    if (!animation_)
        return;

    currentTime_ += timeStep * speed_;

    float time;
    float animationLength = animation_->GetLength();

    if (looped_)
    {
        time = fmodf(currentTime_, animationLength);
        if (time < 0.0f)
            time += animation_->GetLength();
    }
    else
        time = Clamp(currentTime_, 0.0f, animationLength);

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        trackNodeInfos_[i].worldSpace = false;

        const AnimationTrack2D& track = animation_->GetTrack(i);
        const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;

        // Time out of range
        if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
            trackNodeInfos_[i].value.enabled_ = false;
        else
        {
            unsigned index = keyFrames.Size() - 1;
            for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
            {
                if (time <= keyFrames[j + 1].time_)
                {
                    index = j;
                    break;
                }
            }

            const AnimationKeyFrame2D& currKey = keyFrames[index];
            AnimationKeyFrame2D& value = trackNodeInfos_[i].value;

            value.enabled_ = currKey.enabled_;
            value.parent_ = currKey.parent_;

            if (index < keyFrames.Size() - 1)
            {
                const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
                float t = (time - currKey.time_)  / (nextKey.time_ - currKey.time_);
                value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);

                if (trackNodeInfos_[i].hasSprite)
                    value.alpha_ = Urho3D::Lerp(currKey.alpha_, nextKey.alpha_, t);
            }
            else
            {
                value.transform_ = currKey.transform_;

                if (trackNodeInfos_[i].hasSprite)
                    value.alpha_ = currKey.alpha_;
            }

            if (trackNodeInfos_[i].hasSprite)
            {
                value.zIndex_ = currKey.zIndex_;
                value.sprite_ = currKey.sprite_;
                value.useHotSpot_ = currKey.useHotSpot_;
                value.hotSpot_ = currKey.hotSpot_;
            }
        }
    }

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        Node* node = trackNodes_[i];
        TrackNodeInfo& nodeInfo = trackNodeInfos_[i];

        if (!nodeInfo.value.enabled_)
            node->SetEnabled(false);
        else
        {
            node->SetEnabled(true);

            // Calculate world transform.
            CalculateTimelineWorldTransform(i);

            // Update node's transform
            Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
            if (flipX_)
                position.x_ = -position.x_;
            if (flipY_)
                position.y_ = -position.y_;
            node->SetPosition(position);

            float angle = nodeInfo.value.transform_.angle_;
            if (flipX_ != flipY_)
                angle = -angle;
            node->SetRotation(angle);
            node->SetScale(nodeInfo.value.transform_.scale_);

            if (nodeInfo.hasSprite)
            {
                StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
                if (staticSprite)
                {
                    staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
                    staticSprite->SetSprite(nodeInfo.value.sprite_);
                    staticSprite->SetAlpha(nodeInfo.value.alpha_);
                    staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
                    staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
                }
            }
        }
    }
}

void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
{
    TrackNodeInfo& info = trackNodeInfos_[index];
    if (info.worldSpace)
        return;

    info.worldSpace = true;

    int parent = info.value.parent_;
    if (parent != -1)
    {
        CalculateTimelineWorldTransform(parent);
        info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
    }
}

void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
{
    using namespace ScenePostUpdate;
    float timeStep = eventData[P_TIMESTEP].GetFloat();
    UpdateAnimation(timeStep);
}

}
<commit_msg>Readded nullcheck to AnimatedSprite2D::OnFlipChanged().<commit_after>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "../Core/Context.h"
#include "../Resource/ResourceCache.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneEvents.h"
#include "../Urho2D/AnimatedSprite2D.h"
#include "../Urho2D/Animation2D.h"
#include "../Urho2D/AnimationSet2D.h"
#include "../Urho2D/Sprite2D.h"
#include "../Urho2D/StaticSprite2D.h"

#include "../DebugNew.h"

namespace Urho3D
{

extern const char* URHO2D_CATEGORY;
extern const char* blendModeNames[];

const char* loopModeNames[] =
{
    "Default",
    "ForceLooped",
    "ForceClamped",
    0
};

AnimatedSprite2D::AnimatedSprite2D(Context* context) :
    StaticSprite2D(context),
    speed_(1.0f),
    loopMode_(LM_DEFAULT),
    looped_(false),
    currentTime_(0.0f),
    numTracks_(0)
{
}

AnimatedSprite2D::~AnimatedSprite2D()
{
}

void AnimatedSprite2D::RegisterObject(Context* context)
{
    context->RegisterFactory<AnimatedSprite2D>(URHO2D_CATEGORY);

    COPY_BASE_ATTRIBUTES(StaticSprite2D);
    REMOVE_ATTRIBUTE("Sprite");
    ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
    MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef, ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
    ACCESSOR_ATTRIBUTE("Animation", GetAnimation, SetAnimationAttr, String, String::EMPTY, AM_DEFAULT);
    ENUM_ACCESSOR_ATTRIBUTE("Loop Mode", GetLoopMode, SetLoopMode, LoopMode2D, loopModeNames, LM_DEFAULT, AM_DEFAULT);
}

void AnimatedSprite2D::OnSetEnabled()
{
    StaticSprite2D::OnSetEnabled();

    bool enabled = IsEnabledEffective();

    Scene* scene = GetScene();
    if (scene)
    {
        if (enabled)
            SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
        else
            UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
    }

    for (unsigned i = 0; i < trackNodes_.Size(); ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetEnabled(enabled);
    }
}

void AnimatedSprite2D::SetSpeed(float speed)
{
    speed_ = speed;
    MarkNetworkUpdate();
}

void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name, LoopMode2D loopMode)
{
    animationSet_ = animationSet;

    SetAnimation(name, loopMode);
}

void AnimatedSprite2D::SetAnimation(const String& name, LoopMode2D loopMode)
{
    animationName_ = name;

    if (animationSet_)
        SetAnimation(animationSet_->GetAnimation(animationName_), loopMode);
}

void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
{
    if (animationSet == animationSet_)
        return;

    animationSet_ = animationSet;

    SetAnimation(animationName_, loopMode_);
}

void AnimatedSprite2D::SetLoopMode(LoopMode2D loopMode)
{
    if (!animation_)
        return;

    loopMode_ = loopMode;

    switch (loopMode_)
    {
    case LM_FORCE_LOOPED:
        looped_ = true;
        break;

    case LM_FORCE_CLAMPED:
        looped_ = false;
        break;

    default:
        looped_ = animation_->IsLooped();
        break;
    }
}

AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
{
    return animationSet_;
}

Node* AnimatedSprite2D::GetRootNode() const
{
    return rootNode_;
}

void AnimatedSprite2D::SetAnimationSetAttr(const ResourceRef& value)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
}

ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
{
    return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
}

void AnimatedSprite2D::OnNodeSet(Node* node)
{
    StaticSprite2D::OnNodeSet(node);

    if (node)
    {
        Scene* scene = GetScene();
        if (scene && IsEnabledEffective())
            SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
    }
    else
    {
        if (rootNode_)
            rootNode_->Remove();

        rootNode_ = 0;
        numTracks_ = 0;
        trackNodes_.Clear();
        trackNodeInfos_.Clear();
    }
}

void AnimatedSprite2D::SetAnimationAttr(const String& name)
{
    animationName_ = name;

    if (animationSet_)
        SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
}

void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
{
    boundingBox_.Clear();
    worldBoundingBox_.Clear();

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
    }

    boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
}

void AnimatedSprite2D::OnDrawOrderChanged()
{
    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetLayer(layer_);
    }
}

void AnimatedSprite2D::OnFlipChanged()
{
    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetFlip(flipX_, flipY_);
    }

    // For editor paused mode
    UpdateAnimation(0.0f);
}

void AnimatedSprite2D::UpdateSourceBatches()
{
    sourceBatchesDirty_ = false;
}

void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
{
    if (animation == animation_)
    {
        SetLoopMode(loopMode_);

        currentTime_ = 0.0f;
        UpdateAnimation(0.0f);
        return;
    }

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (trackNodes_[i])
            trackNodes_[i]->SetEnabled(false);
    }

    numTracks_ = 0;
    trackNodes_.Clear();
    trackNodeInfos_.Clear();

    animation_ = animation;

    if (!animation_)
        return;

    currentTime_ = 0.0f;

    if (!rootNode_)
    {
        rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
        rootNode_->SetTemporary(true);
    }

    numTracks_ = animation_->GetNumTracks();
    trackNodes_.Resize(numTracks_);
    trackNodeInfos_.Resize(numTracks_);

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        const AnimationTrack2D& track = animation->GetTrack(i);
        SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));

        StaticSprite2D* staticSprite = 0;
        if (trackNode)
        {
            // Enable track node
            trackNode->SetEnabled(true);

            // Get StaticSprite2D component
            if (track.hasSprite_)
                staticSprite = trackNode->GetComponent<StaticSprite2D>();
        }
        else
        {
            // Create new track node
            trackNode = rootNode_->CreateChild(track.name_, LOCAL);
            trackNode->SetTemporary(true);

            // Create StaticSprite2D component
            if (track.hasSprite_)
            {
                staticSprite = trackNode->CreateComponent<StaticSprite2D>();
                staticSprite->SetEnabled(IsEnabledEffective());
            }
        }

        if (staticSprite)
        {
            staticSprite->SetLayer(layer_);
            staticSprite->SetBlendMode(blendMode_);
            staticSprite->SetFlip(flipX_, flipY_);
            staticSprite->SetUseHotSpot(true);
        }

        trackNodes_[i] = trackNode;

        trackNodeInfos_[i].hasSprite = track.hasSprite_;
    }

    SetLoopMode(loopMode);
    UpdateAnimation(0.0f);

    MarkNetworkUpdate();
}

void AnimatedSprite2D::UpdateAnimation(float timeStep)
{
    if (!animation_)
        return;

    currentTime_ += timeStep * speed_;

    float time;
    float animationLength = animation_->GetLength();

    if (looped_)
    {
        time = fmodf(currentTime_, animationLength);
        if (time < 0.0f)
            time += animation_->GetLength();
    }
    else
        time = Clamp(currentTime_, 0.0f, animationLength);

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        trackNodeInfos_[i].worldSpace = false;

        const AnimationTrack2D& track = animation_->GetTrack(i);
        const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;

        // Time out of range
        if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
            trackNodeInfos_[i].value.enabled_ = false;
        else
        {
            unsigned index = keyFrames.Size() - 1;
            for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
            {
                if (time <= keyFrames[j + 1].time_)
                {
                    index = j;
                    break;
                }
            }

            const AnimationKeyFrame2D& currKey = keyFrames[index];
            AnimationKeyFrame2D& value = trackNodeInfos_[i].value;

            value.enabled_ = currKey.enabled_;
            value.parent_ = currKey.parent_;

            if (index < keyFrames.Size() - 1)
            {
                const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
                float t = (time - currKey.time_)  / (nextKey.time_ - currKey.time_);
                value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);

                if (trackNodeInfos_[i].hasSprite)
                    value.alpha_ = Urho3D::Lerp(currKey.alpha_, nextKey.alpha_, t);
            }
            else
            {
                value.transform_ = currKey.transform_;

                if (trackNodeInfos_[i].hasSprite)
                    value.alpha_ = currKey.alpha_;
            }

            if (trackNodeInfos_[i].hasSprite)
            {
                value.zIndex_ = currKey.zIndex_;
                value.sprite_ = currKey.sprite_;
                value.useHotSpot_ = currKey.useHotSpot_;
                value.hotSpot_ = currKey.hotSpot_;
            }
        }
    }

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        Node* node = trackNodes_[i];
        TrackNodeInfo& nodeInfo = trackNodeInfos_[i];

        if (!nodeInfo.value.enabled_)
            node->SetEnabled(false);
        else
        {
            node->SetEnabled(true);

            // Calculate world transform.
            CalculateTimelineWorldTransform(i);

            // Update node's transform
            Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
            if (flipX_)
                position.x_ = -position.x_;
            if (flipY_)
                position.y_ = -position.y_;
            node->SetPosition(position);

            float angle = nodeInfo.value.transform_.angle_;
            if (flipX_ != flipY_)
                angle = -angle;
            node->SetRotation(angle);
            node->SetScale(nodeInfo.value.transform_.scale_);

            if (nodeInfo.hasSprite)
            {
                StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
                if (staticSprite)
                {
                    staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
                    staticSprite->SetSprite(nodeInfo.value.sprite_);
                    staticSprite->SetAlpha(nodeInfo.value.alpha_);
                    staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
                    staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
                }
            }
        }
    }
}

void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
{
    TrackNodeInfo& info = trackNodeInfos_[index];
    if (info.worldSpace)
        return;

    info.worldSpace = true;

    int parent = info.value.parent_;
    if (parent != -1)
    {
        CalculateTimelineWorldTransform(parent);
        info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
    }
}

void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
{
    using namespace ScenePostUpdate;
    float timeStep = eventData[P_TIMESTEP].GetFloat();
    UpdateAnimation(timeStep);
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005, 2008 Apple 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:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "core/editing/RemoveNodeCommand.h"

#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"

namespace WebCore {

RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
    : SimpleEditCommand(node->document())
    , m_node(node)
    , m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
    ASSERT(m_node);
    ASSERT(m_node->parentNode());
}

void RemoveNodeCommand::doApply()
{
    ContainerNode* parent = m_node->parentNode();
    if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
        && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->confusingAndOftenMisusedAttached()))
        return;
    ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->confusingAndOftenMisusedAttached());

    m_parent = parent;
    m_refChild = m_node->nextSibling();

    m_node->remove(IGNORE_EXCEPTION);
}

void RemoveNodeCommand::doUnapply()
{
    RefPtr<ContainerNode> parent = m_parent.release();
    RefPtr<Node> refChild = m_refChild.release();
    if (!parent || !parent->rendererIsEditable())
        return;

    parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
}

}
<commit_msg>RemoveNodeCommand shouldn't use confusingAndOftenMisusedAttached()<commit_after>/*
 * Copyright (C) 2005, 2008 Apple 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:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "core/editing/RemoveNodeCommand.h"

#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"

namespace WebCore {

RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
    : SimpleEditCommand(node->document())
    , m_node(node)
    , m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
    ASSERT(m_node);
    ASSERT(m_node->parentNode());
}

void RemoveNodeCommand::doApply()
{
    ContainerNode* parent = m_node->parentNode();
    if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
        && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->inActiveDocument()))
        return;
    ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->inActiveDocument());

    m_parent = parent;
    m_refChild = m_node->nextSibling();

    m_node->remove(IGNORE_EXCEPTION);
}

void RemoveNodeCommand::doUnapply()
{
    RefPtr<ContainerNode> parent = m_parent.release();
    RefPtr<Node> refChild = m_refChild.release();
    if (!parent || !parent->rendererIsEditable())
        return;

    parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
}

}
<|endoftext|>


<commit_before>// The PassMess Message-Passing Parallelism Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Local includes
#include "passmess/passmess_init.h"

// PassMess includes
#include "passmess/communicator.h"
#include "passmess/passmess_assert.h"

#ifdef PASSMESS_HAVE_MPI
void PassMess_MPI_Handler (MPI_Comm *, int *, ...)
{
  passmess_not_implemented();
}
#endif

namespace PassMess
{

#ifdef PASSMESS_HAVE_MPI
PassMessInit::PassMessInit (int argc, const char * const * argv,
                            bool using_threads,
                            bool handle_mpi_errors,
                            MPI_Comm COMM_WORLD_IN) :
  i_initialized_mpi(false),
  err_handler_set(false)
{
  // Check whether the calling program has already initialized
  // MPI, and avoid duplicate Init/Finalize
  int flag;
  passmess_call_mpi(MPI_Initialized (&flag));

  if (!flag)
    {
      int mpi_thread_provided;
      const int mpi_thread_requested = using_threads ?
        MPI_THREAD_FUNNELED :
        MPI_THREAD_SINGLE;

      passmess_call_mpi
        (MPI_Init_thread (&argc, const_cast<char ***>(&argv),
                          mpi_thread_requested, &mpi_thread_provided));

      if (using_threads &&
          (mpi_thread_provided < MPI_THREAD_FUNNELED))
        {
          // Ideally, if an MPI stack tells us it's unsafe for us
          // to use threads, we should scream and die or at least
          // disable threads.
          //
          // In practice, we've encountered one MPI stack (an mvapich2
          // configuration) that returned MPI_THREAD_SINGLE as a
          // proper warning, two stacks that handle
          // MPI_THREAD_FUNNELED properly, and two current stacks plus
          // a couple old stacks that return MPI_THREAD_SINGLE but
          // support threaded runs anyway, so we just emit a warning.
          //
          passmess_warning("Warning: MPI failed to guarantee MPI_THREAD_FUNNELED\n"
                           << "for a threaded run.\n"
                           << "Be sure your library is funneled-thread-safe..."
                           << std::endl);
        }
      this->i_initialized_mpi = true;
    }

  // Duplicate the input communicator for internal use
  // And get a Communicator copy too, to use
  // as a default for that API
  this->_comm = new Communicator(COMM_WORLD_IN);

  // Set up an MPI error handler if requested.  This helps us get
  // into a debugger with a proper stack when an MPI error occurs.
  if (handle_mpi_errors)
    {
      passmess_call_mpi
        (MPI_Comm_create_errhandler(PassMess_MPI_Handler, &my_errhandler));
      passmess_call_mpi
        (MPI_Comm_set_errhandler(COMM_WORLD_IN, my_errhandler));
      passmess_call_mpi
        (MPI_Comm_set_errhandler(MPI_COMM_WORLD, my_errhandler));
      err_handler_set = true;
    }
}
#else
PassMessInit::PassMessInit (int /* argc */, const char * const * /* argv */,
                            bool /* handle_mpi_errors */,
                            bool /* using_threads */) :
  i_initialized_mpi(false)
{
  this->_comm = new Communicator(); // So comm() doesn't dereference null
}
#endif

PassMessInit::~PassMessInit()
{
  // Every processor had better be ready to exit at the same time.
  // This would be a passmess_parallel_only() function, except that
  // passmess_parallel_only() uses passmess_assert() which throws an
  // exception which causes compilers to scream about exceptions
  // inside destructors.

  // Even if we're not doing parallel_only debugging, we don't want
  // one processor to try to exit until all others are done working.
  this->comm().barrier();

#ifdef PASSMESS_HAVE_MPI
  if (err_handler_set)
    {
      passmess_call_mpi
        (MPI_Errhandler_free(&my_errhandler));
    }

  this->comm().clear();
  delete this->_comm;

  if (this->i_initialized_mpi)
    {
      // We can't just passmess_assert here because destructor,
      // but we ought to report any errors
      unsigned int error_code = MPI_Finalize();
      if (error_code != MPI_SUCCESS)
        {
          char error_string[MPI_MAX_ERROR_STRING+1];
          int error_string_len;
          MPI_Error_string(error_code, error_string,
                           &error_string_len);
          std::cerr << "Failure from MPI_Finalize():\n"
                    << error_string << std::endl;
        }
    }
#else
  delete this->_comm;
#endif
}

} // namespace PassMess
<commit_msg>Avoid throwing exceptions in ~PassMessInit<commit_after>// The PassMess Message-Passing Parallelism Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// Local includes
#include "passmess/passmess_init.h"

// PassMess includes
#include "passmess/communicator.h"
#include "passmess/passmess_assert.h"

#ifdef PASSMESS_HAVE_MPI
void PassMess_MPI_Handler (MPI_Comm *, int *, ...)
{
  passmess_not_implemented();
}
#endif

namespace PassMess
{

#ifdef PASSMESS_HAVE_MPI
PassMessInit::PassMessInit (int argc, const char * const * argv,
                            bool using_threads,
                            bool handle_mpi_errors,
                            MPI_Comm COMM_WORLD_IN) :
  i_initialized_mpi(false),
  err_handler_set(false)
{
  // Check whether the calling program has already initialized
  // MPI, and avoid duplicate Init/Finalize
  int flag;
  passmess_call_mpi(MPI_Initialized (&flag));

  if (!flag)
    {
      int mpi_thread_provided;
      const int mpi_thread_requested = using_threads ?
        MPI_THREAD_FUNNELED :
        MPI_THREAD_SINGLE;

      passmess_call_mpi
        (MPI_Init_thread (&argc, const_cast<char ***>(&argv),
                          mpi_thread_requested, &mpi_thread_provided));

      if (using_threads &&
          (mpi_thread_provided < MPI_THREAD_FUNNELED))
        {
          // Ideally, if an MPI stack tells us it's unsafe for us
          // to use threads, we should scream and die or at least
          // disable threads.
          //
          // In practice, we've encountered one MPI stack (an mvapich2
          // configuration) that returned MPI_THREAD_SINGLE as a
          // proper warning, two stacks that handle
          // MPI_THREAD_FUNNELED properly, and two current stacks plus
          // a couple old stacks that return MPI_THREAD_SINGLE but
          // support threaded runs anyway, so we just emit a warning.
          //
          passmess_warning("Warning: MPI failed to guarantee MPI_THREAD_FUNNELED\n"
                           << "for a threaded run.\n"
                           << "Be sure your library is funneled-thread-safe..."
                           << std::endl);
        }
      this->i_initialized_mpi = true;
    }

  // Duplicate the input communicator for internal use
  // And get a Communicator copy too, to use
  // as a default for that API
  this->_comm = new Communicator(COMM_WORLD_IN);

  // Set up an MPI error handler if requested.  This helps us get
  // into a debugger with a proper stack when an MPI error occurs.
  if (handle_mpi_errors)
    {
      passmess_call_mpi
        (MPI_Comm_create_errhandler(PassMess_MPI_Handler, &my_errhandler));
      passmess_call_mpi
        (MPI_Comm_set_errhandler(COMM_WORLD_IN, my_errhandler));
      passmess_call_mpi
        (MPI_Comm_set_errhandler(MPI_COMM_WORLD, my_errhandler));
      err_handler_set = true;
    }
}
#else
PassMessInit::PassMessInit (int /* argc */, const char * const * /* argv */,
                            bool /* handle_mpi_errors */,
                            bool /* using_threads */) :
  i_initialized_mpi(false)
{
  this->_comm = new Communicator(); // So comm() doesn't dereference null
}
#endif

PassMessInit::~PassMessInit()
{
  // Every processor had better be ready to exit at the same time.
  // This would be a passmess_parallel_only() function, except that
  // passmess_parallel_only() uses passmess_assert() which throws an
  // exception which causes compilers to scream about exceptions
  // inside destructors.

  // Even if we're not doing parallel_only debugging, we don't want
  // one processor to try to exit until all others are done working.
  this->comm().barrier();

#ifdef PASSMESS_HAVE_MPI
  if (err_handler_set)
    {
      unsigned int error_code =
        MPI_Errhandler_free(&my_errhandler);
      if (error_code != MPI_SUCCESS)
        {
          std::cerr <<
            "Failure when freeing MPI_Errhandler! Continuing..." <<
            std::endl;
        }
    }

  this->comm().clear();
  delete this->_comm;

  if (this->i_initialized_mpi)
    {
      // We can't just passmess_assert here because destructor,
      // but we ought to report any errors
      unsigned int error_code = MPI_Finalize();
      if (error_code != MPI_SUCCESS)
        {
          char error_string[MPI_MAX_ERROR_STRING+1];
          int error_string_len;
          MPI_Error_string(error_code, error_string,
                           &error_string_len);
          std::cerr << "Failure from MPI_Finalize():\n"
                    << error_string << std::endl;
        }
    }
#else
  delete this->_comm;
#endif
}

} // namespace PassMess
<|endoftext|>