<commit_before>/**
* Copyright (c) 2014 Sonora Games
*
*/

#include <d3dx11async.h>
#include <iostream>
#include <fstream>

#include "D3D11SpriteMaterial.h"

using namespace Monsoon::Renderer;

D3D11SpriteMaterial::D3D11SpriteMaterial()
{
	mVertexShader = nullptr;
	mPixelShader = nullptr;
	mLayout = nullptr;
	mMatrixBuffer = nullptr;
}

D3D11SpriteMaterial::~D3D11SpriteMaterial()
{

}

bool D3D11SpriteMaterial::Load(ID3D11Device* device, HWND windowHandle)
{
	HRESULT result;
	ID3D10Blob* errorMessage;
	ID3D10Blob* vertexShaderBuffer;
	ID3D10Blob* pixelShaderBuffer;
	D3D11_INPUT_ELEMENT_DESC layoutDescription[2];
	unsigned int numElements;
	D3D11_BUFFER_DESC matrixBufferDescription;
	D3D11_BUFFER_DESC spriteSheetBufferDescription;
	D3D11_SAMPLER_DESC samplerDesc;

	errorMessage = nullptr;
	vertexShaderBuffer = nullptr;
	pixelShaderBuffer = nullptr;

	//
	// Compile Vertex Shader
	//
	result = D3DX11CompileFromFile("sprite.vs", NULL, NULL, "SpriteVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
		&vertexShaderBuffer, &errorMessage, NULL);

	if (FAILED(result))
	{
		MessageBox(windowHandle, "Error Compiling Shader", "sprite.vs", MB_OK);
		return false;
	}

	//
	// Compile Pixel Shader
	//
	result = D3DX11CompileFromFile("sprite.ps", NULL, NULL, "SpritePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
		&pixelShaderBuffer, &errorMessage, NULL);

	if (FAILED(result))
	{
		MessageBox(windowHandle, "Error Compiling Shader", "sprite.ps", MB_OK);
		return false;
	}

	//
	// Create Shader Objects
	//

	result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &mVertexShader);
	if (FAILED(result))
		return false;

	result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &mPixelShader);
	if (FAILED(result))
		return false;

	//
	// Describe input layout and create shader objects.
	//
	layoutDescription[0].SemanticName = "POSITION";
	layoutDescription[0].SemanticIndex = 0;
	layoutDescription[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
	layoutDescription[0].InputSlot = 0;
	layoutDescription[0].AlignedByteOffset = 0;
	layoutDescription[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	layoutDescription[0].InstanceDataStepRate = 0;

	layoutDescription[1].SemanticName = "TEXCOORD";
	layoutDescription[1].SemanticIndex = 0;
	layoutDescription[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	layoutDescription[1].InputSlot = 0;
	layoutDescription[1].AlignedByteOffset = sizeof(D3DXVECTOR3) + sizeof(D3DXCOLOR);
	layoutDescription[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	layoutDescription[1].InstanceDataStepRate = 0;

	numElements = sizeof(layoutDescription) / sizeof(layoutDescription[0]);

	result = device->CreateInputLayout(layoutDescription, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &mLayout);
	if (FAILED(result))
		return false;

	//
	// Describe and create cbuffer.
	//
	matrixBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDescription.ByteWidth = sizeof(MatrixBufferType);
	matrixBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	matrixBufferDescription.MiscFlags = 0;
	matrixBufferDescription.StructureByteStride = 0;

	result = device->CreateBuffer(&matrixBufferDescription, NULL, &mMatrixBuffer);
	if (FAILED(result))
		return false;

	spriteSheetBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
	spriteSheetBufferDescription.ByteWidth = sizeof(SpriteSheetType);
	spriteSheetBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	spriteSheetBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	spriteSheetBufferDescription.MiscFlags = 0;
	spriteSheetBufferDescription.StructureByteStride = 0;

	result = device->CreateBuffer(&spriteSheetBufferDescription, NULL, &mSpriteSheetBuffer);
	if (FAILED(result))
		return false;

	//
	// Describe and create sampler.
	//
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	result = device->CreateSamplerState(&samplerDesc, &mSamplerState);
	if (FAILED(result))
		return false;

	//
	// Clean Up
	//
	vertexShaderBuffer->Release();
	vertexShaderBuffer = 0;

	pixelShaderBuffer->Release();
	pixelShaderBuffer = 0;

	return true;
}

void D3D11SpriteMaterial::Release()
{
	if (mSamplerState)
		mSamplerState->Release();

	if (mSpriteSheetBuffer)
		mSpriteSheetBuffer->Release();

	if (mMatrixBuffer)
		mMatrixBuffer->Release();

	if (mLayout)
		mLayout->Release();

	if (mPixelShader)
		mPixelShader->Release();

	if (mVertexShader)
		mVertexShader->Release();
}

void D3D11SpriteMaterial::Render(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix,
	D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, int index, int sliceSizeX, int sliceSizeY, int sheetWidth, int sheetHeight)
{
	//
	// Map Material Inputs
	//
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	D3D11_MAPPED_SUBRESOURCE spriteSheetMappedResource;
	MatrixBufferType* dataPtr;
	SpriteSheetType* spriteSheetDataPtr;

	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock Matrix cBuffer
	deviceContext->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

	dataPtr = (MatrixBufferType*)mappedResource.pData;

	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock Matrix cBuffer
	deviceContext->Unmap(mMatrixBuffer, 0);

	// Lock SpriteSheet cBuffer
	deviceContext->Map(mSpriteSheetBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &spriteSheetMappedResource);

	spriteSheetDataPtr = (SpriteSheetType*)spriteSheetMappedResource.pData;

	spriteSheetDataPtr->index = index;
	spriteSheetDataPtr->sliceSizeX = sliceSizeX;
	spriteSheetDataPtr->sliceSizeY = sliceSizeY;
	spriteSheetDataPtr->sheetWidth = sheetWidth;
	spriteSheetDataPtr->sheetHeight = sheetHeight;

	// Unload SpriteSheet cBuffer
	deviceContext->Unmap(mSpriteSheetBuffer, 0);

	deviceContext->VSSetConstantBuffers(0, 1, &mMatrixBuffer);
	deviceContext->VSSetConstantBuffers(1, 1, &mSpriteSheetBuffer);
	deviceContext->PSSetShaderResources(0, 1, &texture);

	//
	// Render the material.
	//

	deviceContext->IASetInputLayout(mLayout);
	deviceContext->VSSetShader(mVertexShader, NULL, 0);
	deviceContext->PSSetShader(mPixelShader, NULL, 0);
	deviceContext->PSSetSamplers(0, 1, &mSamplerState);
}<commit_msg>Set UV addressing mode to CLAMP for sprites.<commit_after>/**
* Copyright (c) 2014 Sonora Games
*
*/

#include <d3dx11async.h>
#include <iostream>
#include <fstream>

#include "D3D11SpriteMaterial.h"

using namespace Monsoon::Renderer;

D3D11SpriteMaterial::D3D11SpriteMaterial()
{
	mVertexShader = nullptr;
	mPixelShader = nullptr;
	mLayout = nullptr;
	mMatrixBuffer = nullptr;
}

D3D11SpriteMaterial::~D3D11SpriteMaterial()
{

}

bool D3D11SpriteMaterial::Load(ID3D11Device* device, HWND windowHandle)
{
	HRESULT result;
	ID3D10Blob* errorMessage;
	ID3D10Blob* vertexShaderBuffer;
	ID3D10Blob* pixelShaderBuffer;
	D3D11_INPUT_ELEMENT_DESC layoutDescription[2];
	unsigned int numElements;
	D3D11_BUFFER_DESC matrixBufferDescription;
	D3D11_BUFFER_DESC spriteSheetBufferDescription;
	D3D11_SAMPLER_DESC samplerDesc;

	errorMessage = nullptr;
	vertexShaderBuffer = nullptr;
	pixelShaderBuffer = nullptr;

	//
	// Compile Vertex Shader
	//
	result = D3DX11CompileFromFile("sprite.vs", NULL, NULL, "SpriteVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
		&vertexShaderBuffer, &errorMessage, NULL);

	if (FAILED(result))
	{
		MessageBox(windowHandle, "Error Compiling Shader", "sprite.vs", MB_OK);
		return false;
	}

	//
	// Compile Pixel Shader
	//
	result = D3DX11CompileFromFile("sprite.ps", NULL, NULL, "SpritePixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
		&pixelShaderBuffer, &errorMessage, NULL);

	if (FAILED(result))
	{
		MessageBox(windowHandle, "Error Compiling Shader", "sprite.ps", MB_OK);
		return false;
	}

	//
	// Create Shader Objects
	//

	result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &mVertexShader);
	if (FAILED(result))
		return false;

	result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &mPixelShader);
	if (FAILED(result))
		return false;

	//
	// Describe input layout and create shader objects.
	//
	layoutDescription[0].SemanticName = "POSITION";
	layoutDescription[0].SemanticIndex = 0;
	layoutDescription[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
	layoutDescription[0].InputSlot = 0;
	layoutDescription[0].AlignedByteOffset = 0;
	layoutDescription[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	layoutDescription[0].InstanceDataStepRate = 0;

	layoutDescription[1].SemanticName = "TEXCOORD";
	layoutDescription[1].SemanticIndex = 0;
	layoutDescription[1].Format = DXGI_FORMAT_R32G32_FLOAT;
	layoutDescription[1].InputSlot = 0;
	layoutDescription[1].AlignedByteOffset = sizeof(D3DXVECTOR3) + sizeof(D3DXCOLOR);
	layoutDescription[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
	layoutDescription[1].InstanceDataStepRate = 0;

	numElements = sizeof(layoutDescription) / sizeof(layoutDescription[0]);

	result = device->CreateInputLayout(layoutDescription, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &mLayout);
	if (FAILED(result))
		return false;

	//
	// Describe and create cbuffer.
	//
	matrixBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
	matrixBufferDescription.ByteWidth = sizeof(MatrixBufferType);
	matrixBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	matrixBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	matrixBufferDescription.MiscFlags = 0;
	matrixBufferDescription.StructureByteStride = 0;

	result = device->CreateBuffer(&matrixBufferDescription, NULL, &mMatrixBuffer);
	if (FAILED(result))
		return false;

	spriteSheetBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
	spriteSheetBufferDescription.ByteWidth = sizeof(SpriteSheetType);
	spriteSheetBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	spriteSheetBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	spriteSheetBufferDescription.MiscFlags = 0;
	spriteSheetBufferDescription.StructureByteStride = 0;

	result = device->CreateBuffer(&spriteSheetBufferDescription, NULL, &mSpriteSheetBuffer);
	if (FAILED(result))
		return false;

	//
	// Describe and create sampler.
	//
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 1;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
	samplerDesc.BorderColor[0] = 0;
	samplerDesc.BorderColor[1] = 0;
	samplerDesc.BorderColor[2] = 0;
	samplerDesc.BorderColor[3] = 0;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	result = device->CreateSamplerState(&samplerDesc, &mSamplerState);
	if (FAILED(result))
		return false;

	//
	// Clean Up
	//
	vertexShaderBuffer->Release();
	vertexShaderBuffer = 0;

	pixelShaderBuffer->Release();
	pixelShaderBuffer = 0;

	return true;
}

void D3D11SpriteMaterial::Release()
{
	if (mSamplerState)
		mSamplerState->Release();

	if (mSpriteSheetBuffer)
		mSpriteSheetBuffer->Release();

	if (mMatrixBuffer)
		mMatrixBuffer->Release();

	if (mLayout)
		mLayout->Release();

	if (mPixelShader)
		mPixelShader->Release();

	if (mVertexShader)
		mVertexShader->Release();
}

void D3D11SpriteMaterial::Render(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix,
	D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, int index, int sliceSizeX, int sliceSizeY, int sheetWidth, int sheetHeight)
{
	//
	// Map Material Inputs
	//
	HRESULT result;
	D3D11_MAPPED_SUBRESOURCE mappedResource;
	D3D11_MAPPED_SUBRESOURCE spriteSheetMappedResource;
	MatrixBufferType* dataPtr;
	SpriteSheetType* spriteSheetDataPtr;

	D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
	D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
	D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);

	// Lock Matrix cBuffer
	deviceContext->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

	dataPtr = (MatrixBufferType*)mappedResource.pData;

	dataPtr->world = worldMatrix;
	dataPtr->view = viewMatrix;
	dataPtr->projection = projectionMatrix;

	// Unlock Matrix cBuffer
	deviceContext->Unmap(mMatrixBuffer, 0);

	// Lock SpriteSheet cBuffer
	deviceContext->Map(mSpriteSheetBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &spriteSheetMappedResource);

	spriteSheetDataPtr = (SpriteSheetType*)spriteSheetMappedResource.pData;

	spriteSheetDataPtr->index = index;
	spriteSheetDataPtr->sliceSizeX = sliceSizeX;
	spriteSheetDataPtr->sliceSizeY = sliceSizeY;
	spriteSheetDataPtr->sheetWidth = sheetWidth;
	spriteSheetDataPtr->sheetHeight = sheetHeight;

	// Unload SpriteSheet cBuffer
	deviceContext->Unmap(mSpriteSheetBuffer, 0);

	deviceContext->VSSetConstantBuffers(0, 1, &mMatrixBuffer);
	deviceContext->VSSetConstantBuffers(1, 1, &mSpriteSheetBuffer);
	deviceContext->PSSetShaderResources(0, 1, &texture);

	//
	// Render the material.
	//

	deviceContext->IASetInputLayout(mLayout);
	deviceContext->VSSetShader(mVertexShader, NULL, 0);
	deviceContext->PSSetShader(mPixelShader, NULL, 0);
	deviceContext->PSSetSamplers(0, 1, &mSamplerState);
}<|endoftext|>


<commit_before>/*
 * opencog/persist/file/TimeServerSavable.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "TimeServerSavable.h"
#include "TemporalTableFile.h"

#include <opencog/util/Logger.h>

using namespace opencog;

TimeServerSavable::TimeServerSavable()
{
    timeserver = NULL;
}

TimeServerSavable::~TimeServerSavable()
{
    timeserver = NULL;
}

const char* TimeServerSavable::getId() const
{
    static const char* id = "TimeServer";
    return id;
}

void TimeServerSavable::saveRepository(FILE* fp) const
{
	logger().debug("Saving %s (%ld)\n", getId(), ftell(fp));
    //Saves TemporalTable
    size_t size=(timeserver->temporalTableMap).size();
	fwrite(&size,sizeof(size_t),1,fp);
	for(auto it=(timeserver->temporalTableMap).begin();it!=(timeserver->temporalTableMap).end();it++)
	{
		const string timeDomainName=it->first;
        char chartimeDomainName[128];
        memset(chartimeDomainName, '\0',strlen(timeDomainName.c_str()));
        strcpy(chartimeDomainName,timeDomainName.c_str());
		logger().error("timeserver save repo timedomain name: %s",chartimeDomainName);
        fwrite(&chartimeDomainName, 128,1,fp);

		TemporalTableFile ttf;
		ttf.save(fp,it->second);
	}
}

void TimeServerSavable::loadRepository(FILE* fp, HandMapPtr conv)
{
	logger().debug("Loading %s (%ld)\n", getId(), ftell(fp));
    bool b_read = true;
	size_t size=0;
    FREAD_CK(&size, sizeof(size_t), 1, fp);
    // Loads the TemporalTable
	for(unsigned int i=0;i!=size;i++)
	{
		char chartimeDomainName[128];
        FREAD_CK(&chartimeDomainName, 128, 1, fp);
		std::string timeDomainName(chartimeDomainName);
		logger().error("load timeserver repo: timedomainname %s",chartimeDomainName);
		(timeserver->temporalTableMap)[timeDomainName]=new TemporalTable();

		TemporalTableFile ttf;
		ttf.load(fp,(timeserver->temporalTableMap)[timeDomainName], conv);
	}
	CHECK_FREAD
}

void TimeServerSavable::clear()
{
    timeserver->clear();
}

<commit_msg>fix indent<commit_after>/*
 * opencog/persist/file/TimeServerSavable.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "TimeServerSavable.h"
#include "TemporalTableFile.h"

#include <opencog/util/Logger.h>

using namespace opencog;

TimeServerSavable::TimeServerSavable()
{
    timeserver = NULL;
}

TimeServerSavable::~TimeServerSavable()
{
    timeserver = NULL;
}

const char* TimeServerSavable::getId() const
{
    static const char* id = "TimeServer";
    return id;
}

void TimeServerSavable::saveRepository(FILE* fp) const
{
    logger().debug("Saving %s (%ld)\n", getId(), ftell(fp));
    //Saves TemporalTable
    size_t size=(timeserver->temporalTableMap).size();
    fwrite(&size,sizeof(size_t),1,fp);
    for(auto it=(timeserver->temporalTableMap).begin();it!=(timeserver->temporalTableMap).end();it++)
    {
	const string timeDomainName=it->first;
	char chartimeDomainName[128];
	memset(chartimeDomainName, '\0',strlen(timeDomainName.c_str()));
	strcpy(chartimeDomainName,timeDomainName.c_str());
	logger().error("timeserver save repo timedomain name: %s",chartimeDomainName);
	fwrite(&chartimeDomainName, 128,1,fp);

	TemporalTableFile ttf;
	ttf.save(fp,it->second);
    }
}

void TimeServerSavable::loadRepository(FILE* fp, HandMapPtr conv)
{
    logger().debug("Loading %s (%ld)\n", getId(), ftell(fp));
    bool b_read = true;
    size_t size=0;
    FREAD_CK(&size, sizeof(size_t), 1, fp);
    // Loads the TemporalTable
    for(unsigned int i=0;i!=size;i++)
    {
	char chartimeDomainName[128];
	FREAD_CK(&chartimeDomainName, 128, 1, fp);
	std::string timeDomainName(chartimeDomainName);
	logger().error("load timeserver repo: timedomainname %s",chartimeDomainName);
	(timeserver->temporalTableMap)[timeDomainName]=new TemporalTable();

	TemporalTableFile ttf;
	ttf.load(fp,(timeserver->temporalTableMap)[timeDomainName], conv);
    }
	CHECK_FREAD
}

void TimeServerSavable::clear()
{
    timeserver->clear();
}

<|endoftext|>


<commit_before><commit_msg>add languages/program_on_cpp/object_type_conversion.cpp to repo<commit_after><|endoftext|>


<commit_before><commit_msg>Move deferred render pass creation location<commit_after><|endoftext|>


<commit_before>#include <cstdlib>
#include <QtCore/QBasicTimer>
#include <QtCore/QMetaType>
#include <QtCore/QMutexLocker>
#include <QtCore/QThread>
#ifdef Q_OS_MAC
#include <pthread.h>
#endif

#include "Manager.h"
#include "Object.h"

// Declarations for part of Qt's internal API
Q_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();
namespace QVariantPrivate {
Q_DECL_IMPORT void registerHandler(
    const int name, const QVariant::Handler *handler);
}

static const char* cCounterNames[] = {
    "ClassCounter",
    "ObjectCounter",
    "QObjectCounter",
    "VariantCounter",
    "ClassSerial",
    "ObjectSerial"
};

extern "C" void hsqml_dump_counters()
{
    Q_ASSERT (gManager);
    if (gManager->checkLogLevel(1)) {
        for (int i=0; i<HsQMLManager::TotalCounters; i++) {
            gManager->log(QString().sprintf("%s = %d.",
                cCounterNames[i], gManager->updateCounter(
                    static_cast<HsQMLManager::CounterId>(i), 0)));
        }
    }
}

static void hooked_construct(QVariant::Private* p, const void* copy)
{
    gManager->hookedConstruct(p, copy);
}

static void hooked_clear(QVariant::Private* p)
{
    gManager->hookedClear(p);
}

ManagerPointer gManager;

HsQMLManager::HsQMLManager(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
    : mLogLevel(0)
    , mAtExit(false)
    , mFreeFun(freeFun)
    , mFreeStable(freeStable)
    , mOriginalHandler(qcoreVariantHandler())
    , mHookedHandler(*mOriginalHandler)
    , mApp(NULL)
    , mLock(QMutex::Recursive)
    , mRunning(false)
    , mRunCount(0)
    , mStackBase(NULL)
    , mStartCb(NULL)
    , mJobsCb(NULL)
    , mYieldCb(NULL)
    , mActiveEngine(NULL)
{
    // Get log level from environment
    const char* env = std::getenv("HSQML_DEBUG_LOG_LEVEL");
    if (env) {
        setLogLevel(QString(env).toInt());
    }

    // Set hooked handler functions
    mHookedHandler.construct = &hooked_construct;
    mHookedHandler.clear = &hooked_clear;
}

void HsQMLManager::setLogLevel(int ll)
{
    mLogLevel = ll;
    if (ll > 0 && !mAtExit) {
        if (atexit(&hsqml_dump_counters) == 0) {
            mAtExit = true;
        }
        else {
            log("Failed to register callback with atexit().");
        }
    }
}

bool HsQMLManager::checkLogLevel(int ll)
{
    return mLogLevel >= ll;
}

void HsQMLManager::log(const QString& msg)
{
    QMutexLocker locker(&mLogLock);
    fprintf(stderr, "HsQML: %s\n", msg.toUtf8().data());
}

int HsQMLManager::updateCounter(CounterId id, int delta)
{
    return mCounters[id].fetchAndAddRelaxed(delta);
}

void HsQMLManager::freeFun(HsFunPtr funPtr)
{
    mFreeFun(funPtr);
}

void HsQMLManager::freeStable(HsStablePtr stablePtr)
{
    mFreeStable(stablePtr);
}

void HsQMLManager::registerObject(const QObject* obj)
{
    mObjectSet.insert(obj);
}

void HsQMLManager::unregisterObject(const QObject* obj)
{
    bool removed = mObjectSet.remove(obj);
    Q_ASSERT(removed);
}

void HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)
{
    char guard;
    mOriginalHandler->construct(p, copy);
    void* pp = reinterpret_cast<void*>(p);
    // The QVariant internals sometimes use a special code path for pointer
    // values which avoids calling the handler functions. This makes it
    // difficult to use them to keep a reference count. However, it's my
    // observation that this only affects transient QVariants created on the
    // stack inside the JavaScript engine's marshalling code. The persistent
    // QVariants stored in the heap are manipulated using a more restricted set
    // of operations which always use the handler functions. Hence, by assuming
    // that the stack can be discounted, it's possible to keep an accurate
    // count of heap references using these hooks.
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (isEventThread() && mObjectSet.contains(p->data.o)) {
            HsQMLObject* obj = static_cast<HsQMLObject*>(p->data.o);
            HsQMLObjectProxy* proxy = obj->proxy();
            proxy->ref(HsQMLObjectProxy::Variant);
            proxy->tryGCLock();
            updateCounter(VariantCount, 1);
        }
    }
}

void HsQMLManager::hookedClear(QVariant::Private* p)
{
    char guard;
    void* pp = reinterpret_cast<void*>(p);
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (isEventThread() && mObjectSet.contains(p->data.o)) {
            HsQMLObject* obj = static_cast<HsQMLObject*>(p->data.o);
            obj->proxy()->deref(HsQMLObjectProxy::Variant);
            updateCounter(VariantCount, -1);
        }
    }
    mOriginalHandler->clear(p);
}

bool HsQMLManager::isEventThread()
{
    return mApp && mApp->thread() == QThread::currentThread();
}

HsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    QMutexLocker locker(&mLock);

    // Check if already running
    if (mRunning) {
        return HSQML_EVLOOP_ALREADY_RUNNING;
    }

    // Check if event loop bound to a different thread
    if (mApp && !isEventThread()) {
        return HSQML_EVLOOP_WRONG_THREAD;
    }

#ifdef Q_OS_MAC
    if (!pthread_main_np()) {
        // Cocoa can only be run on the primordial thread and exec() doesn't
        // check this.
        return HSQML_EVLOOP_WRONG_THREAD;
    }
#endif

    // Check for non-threaded RTS
    if (yieldCb) {
        HSQML_LOG(0,
            "Warning: CPU cannot idle when using the non-threaded RTS.");
    }

    // Perform one-time initialisation
    if (!mApp) {
        // Install hooked handler for QVariants
        QVariantPrivate::registerHandler(0, &mHookedHandler);

        // Register custom type
        qRegisterMetaType<HsQMLEngineConfig>("HsQMLEngineConfig");

        // Create application object
        mApp = new HsQMLManagerApp();
    }

    // Save stack base and callbacks
    mStackBase = &locker;
    mStartCb = startCb;
    mJobsCb = jobsCb;
    mYieldCb = yieldCb;

    // Setup events
    QCoreApplication::postEvent(
        mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),
        Qt::HighEventPriority);
    QBasicTimer idleTimer;
    if (yieldCb) {
        idleTimer.start(0, mApp);
    }

    // Run loop
    int ret;
    do {
        ret = mApp->exec();

        // Kill all engines
        const QObjectList& cs = gManager->mApp->children();
        while (!cs.empty()) {
            delete cs.front();
        }

        // Cmd-Q on MacOS can kill the event loop before we're ready
        // Keep it running until a StopLoopEvent is received
    } while (ret == 0 && mRunning);

    // Remove redundant events
    QCoreApplication::removePostedEvents(
        mApp, HsQMLManagerApp::RemoveGCLockEvent);

    // Cleanup callbacks
    freeFun(startCb);
    mStartCb = NULL;
    freeFun(jobsCb);
    mJobsCb = NULL;
    if (yieldCb) {
        freeFun(yieldCb);
        mYieldCb = NULL;
    }

    // Return
    if (ret == 0) {
        return HSQML_EVLOOP_OK;
    }
    else {
        QCoreApplication::removePostedEvents(
            mApp, HsQMLManagerApp::StartedLoopEvent);
        return HSQML_EVLOOP_OTHER_ERROR;
    }
}

HsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        mRunCount++;
        return HSQML_EVLOOP_OK;
    }
    else {
        return HSQML_EVLOOP_NOT_RUNNING;
    }
}

void HsQMLManager::releaseEventLoop()
{
    QMutexLocker locker(&mLock);
    if (--mRunCount == 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),
            Qt::LowEventPriority);
    }
}

void HsQMLManager::notifyJobs()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));
    }
}

void HsQMLManager::createEngine(const HsQMLEngineConfig& config)
{
    Q_ASSERT (mApp);
    QMetaObject::invokeMethod(
        mApp, "createEngine", Q_ARG(HsQMLEngineConfig, config));
}

void HsQMLManager::setActiveEngine(HsQMLEngine* engine)
{
    Q_ASSERT(!mActiveEngine || !engine);
    mActiveEngine = engine;
}

HsQMLEngine* HsQMLManager::activeEngine()
{
    return mActiveEngine;
}

void HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)
{
    QCoreApplication::postEvent(mApp, ev);
}

HsQMLManagerApp::HsQMLManagerApp()
    : mArgC(1)
    , mArg0(0)
    , mArgV(&mArg0)
    , mApp(mArgC, &mArgV)
{
    mApp.setQuitOnLastWindowClosed(false);
}

HsQMLManagerApp::~HsQMLManagerApp()
{}

void HsQMLManagerApp::customEvent(QEvent* ev)
{
    switch (ev->type()) {
    case HsQMLManagerApp::StartedLoopEvent: {
        gManager->mRunning = true;
        gManager->mRunCount++;
        gManager->mLock.unlock();
        gManager->mStartCb();
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::StopLoopEvent: {
        gManager->mLock.lock();
        gManager->mRunning = false;
        gManager->mApp->mApp.quit();
        break;}
    case HsQMLManagerApp::PendingJobsEvent: {
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::RemoveGCLockEvent: {
        static_cast<HsQMLObjectEvent*>(ev)->process();
        break;}
    }
}

void HsQMLManagerApp::timerEvent(QTimerEvent*)
{
    Q_ASSERT(gManager->mYieldCb);
    gManager->mYieldCb();
}

void HsQMLManagerApp::createEngine(HsQMLEngineConfig config)
{
    HsQMLEngine* engine = new HsQMLEngine(config);
    engine->setParent(this);
}

int HsQMLManagerApp::exec()
{
    return mApp.exec();
}

extern "C" void hsqml_init(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
{
    if (gManager == NULL) {
        HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);
        if (!gManager.testAndSetOrdered(NULL, manager)) {
            delete manager;
        }
    }
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_run(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    return gManager->runEventLoop(startCb, jobsCb, yieldCb);
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_require()
{
    return gManager->requireEventLoop();
}

extern "C" void hsqml_evloop_release()
{
    gManager->releaseEventLoop();
}

extern "C" void hsqml_evloop_notify_jobs()
{
    gManager->notifyJobs();
}

extern "C" void hsqml_set_debug_loglevel(int ll)
{
    Q_ASSERT (gManager);
    gManager->setLogLevel(ll);
}
<commit_msg>Add missing header file for fprintf.<commit_after>#include <cstdio>
#include <cstdlib>
#include <QtCore/QBasicTimer>
#include <QtCore/QMetaType>
#include <QtCore/QMutexLocker>
#include <QtCore/QThread>
#ifdef Q_OS_MAC
#include <pthread.h>
#endif

#include "Manager.h"
#include "Object.h"

// Declarations for part of Qt's internal API
Q_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();
namespace QVariantPrivate {
Q_DECL_IMPORT void registerHandler(
    const int name, const QVariant::Handler *handler);
}

static const char* cCounterNames[] = {
    "ClassCounter",
    "ObjectCounter",
    "QObjectCounter",
    "VariantCounter",
    "ClassSerial",
    "ObjectSerial"
};

extern "C" void hsqml_dump_counters()
{
    Q_ASSERT (gManager);
    if (gManager->checkLogLevel(1)) {
        for (int i=0; i<HsQMLManager::TotalCounters; i++) {
            gManager->log(QString().sprintf("%s = %d.",
                cCounterNames[i], gManager->updateCounter(
                    static_cast<HsQMLManager::CounterId>(i), 0)));
        }
    }
}

static void hooked_construct(QVariant::Private* p, const void* copy)
{
    gManager->hookedConstruct(p, copy);
}

static void hooked_clear(QVariant::Private* p)
{
    gManager->hookedClear(p);
}

ManagerPointer gManager;

HsQMLManager::HsQMLManager(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
    : mLogLevel(0)
    , mAtExit(false)
    , mFreeFun(freeFun)
    , mFreeStable(freeStable)
    , mOriginalHandler(qcoreVariantHandler())
    , mHookedHandler(*mOriginalHandler)
    , mApp(NULL)
    , mLock(QMutex::Recursive)
    , mRunning(false)
    , mRunCount(0)
    , mStackBase(NULL)
    , mStartCb(NULL)
    , mJobsCb(NULL)
    , mYieldCb(NULL)
    , mActiveEngine(NULL)
{
    // Get log level from environment
    const char* env = std::getenv("HSQML_DEBUG_LOG_LEVEL");
    if (env) {
        setLogLevel(QString(env).toInt());
    }

    // Set hooked handler functions
    mHookedHandler.construct = &hooked_construct;
    mHookedHandler.clear = &hooked_clear;
}

void HsQMLManager::setLogLevel(int ll)
{
    mLogLevel = ll;
    if (ll > 0 && !mAtExit) {
        if (atexit(&hsqml_dump_counters) == 0) {
            mAtExit = true;
        }
        else {
            log("Failed to register callback with atexit().");
        }
    }
}

bool HsQMLManager::checkLogLevel(int ll)
{
    return mLogLevel >= ll;
}

void HsQMLManager::log(const QString& msg)
{
    QMutexLocker locker(&mLogLock);
    fprintf(stderr, "HsQML: %s\n", msg.toUtf8().data());
}

int HsQMLManager::updateCounter(CounterId id, int delta)
{
    return mCounters[id].fetchAndAddRelaxed(delta);
}

void HsQMLManager::freeFun(HsFunPtr funPtr)
{
    mFreeFun(funPtr);
}

void HsQMLManager::freeStable(HsStablePtr stablePtr)
{
    mFreeStable(stablePtr);
}

void HsQMLManager::registerObject(const QObject* obj)
{
    mObjectSet.insert(obj);
}

void HsQMLManager::unregisterObject(const QObject* obj)
{
    bool removed = mObjectSet.remove(obj);
    Q_ASSERT(removed);
}

void HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)
{
    char guard;
    mOriginalHandler->construct(p, copy);
    void* pp = reinterpret_cast<void*>(p);
    // The QVariant internals sometimes use a special code path for pointer
    // values which avoids calling the handler functions. This makes it
    // difficult to use them to keep a reference count. However, it's my
    // observation that this only affects transient QVariants created on the
    // stack inside the JavaScript engine's marshalling code. The persistent
    // QVariants stored in the heap are manipulated using a more restricted set
    // of operations which always use the handler functions. Hence, by assuming
    // that the stack can be discounted, it's possible to keep an accurate
    // count of heap references using these hooks.
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (isEventThread() && mObjectSet.contains(p->data.o)) {
            HsQMLObject* obj = static_cast<HsQMLObject*>(p->data.o);
            HsQMLObjectProxy* proxy = obj->proxy();
            proxy->ref(HsQMLObjectProxy::Variant);
            proxy->tryGCLock();
            updateCounter(VariantCount, 1);
        }
    }
}

void HsQMLManager::hookedClear(QVariant::Private* p)
{
    char guard;
    void* pp = reinterpret_cast<void*>(p);
    if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {
        if (isEventThread() && mObjectSet.contains(p->data.o)) {
            HsQMLObject* obj = static_cast<HsQMLObject*>(p->data.o);
            obj->proxy()->deref(HsQMLObjectProxy::Variant);
            updateCounter(VariantCount, -1);
        }
    }
    mOriginalHandler->clear(p);
}

bool HsQMLManager::isEventThread()
{
    return mApp && mApp->thread() == QThread::currentThread();
}

HsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    QMutexLocker locker(&mLock);

    // Check if already running
    if (mRunning) {
        return HSQML_EVLOOP_ALREADY_RUNNING;
    }

    // Check if event loop bound to a different thread
    if (mApp && !isEventThread()) {
        return HSQML_EVLOOP_WRONG_THREAD;
    }

#ifdef Q_OS_MAC
    if (!pthread_main_np()) {
        // Cocoa can only be run on the primordial thread and exec() doesn't
        // check this.
        return HSQML_EVLOOP_WRONG_THREAD;
    }
#endif

    // Check for non-threaded RTS
    if (yieldCb) {
        HSQML_LOG(0,
            "Warning: CPU cannot idle when using the non-threaded RTS.");
    }

    // Perform one-time initialisation
    if (!mApp) {
        // Install hooked handler for QVariants
        QVariantPrivate::registerHandler(0, &mHookedHandler);

        // Register custom type
        qRegisterMetaType<HsQMLEngineConfig>("HsQMLEngineConfig");

        // Create application object
        mApp = new HsQMLManagerApp();
    }

    // Save stack base and callbacks
    mStackBase = &locker;
    mStartCb = startCb;
    mJobsCb = jobsCb;
    mYieldCb = yieldCb;

    // Setup events
    QCoreApplication::postEvent(
        mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),
        Qt::HighEventPriority);
    QBasicTimer idleTimer;
    if (yieldCb) {
        idleTimer.start(0, mApp);
    }

    // Run loop
    int ret;
    do {
        ret = mApp->exec();

        // Kill all engines
        const QObjectList& cs = gManager->mApp->children();
        while (!cs.empty()) {
            delete cs.front();
        }

        // Cmd-Q on MacOS can kill the event loop before we're ready
        // Keep it running until a StopLoopEvent is received
    } while (ret == 0 && mRunning);

    // Remove redundant events
    QCoreApplication::removePostedEvents(
        mApp, HsQMLManagerApp::RemoveGCLockEvent);

    // Cleanup callbacks
    freeFun(startCb);
    mStartCb = NULL;
    freeFun(jobsCb);
    mJobsCb = NULL;
    if (yieldCb) {
        freeFun(yieldCb);
        mYieldCb = NULL;
    }

    // Return
    if (ret == 0) {
        return HSQML_EVLOOP_OK;
    }
    else {
        QCoreApplication::removePostedEvents(
            mApp, HsQMLManagerApp::StartedLoopEvent);
        return HSQML_EVLOOP_OTHER_ERROR;
    }
}

HsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        mRunCount++;
        return HSQML_EVLOOP_OK;
    }
    else {
        return HSQML_EVLOOP_NOT_RUNNING;
    }
}

void HsQMLManager::releaseEventLoop()
{
    QMutexLocker locker(&mLock);
    if (--mRunCount == 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),
            Qt::LowEventPriority);
    }
}

void HsQMLManager::notifyJobs()
{
    QMutexLocker locker(&mLock);
    if (mRunCount > 0) {
        QCoreApplication::postEvent(
            mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));
    }
}

void HsQMLManager::createEngine(const HsQMLEngineConfig& config)
{
    Q_ASSERT (mApp);
    QMetaObject::invokeMethod(
        mApp, "createEngine", Q_ARG(HsQMLEngineConfig, config));
}

void HsQMLManager::setActiveEngine(HsQMLEngine* engine)
{
    Q_ASSERT(!mActiveEngine || !engine);
    mActiveEngine = engine;
}

HsQMLEngine* HsQMLManager::activeEngine()
{
    return mActiveEngine;
}

void HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)
{
    QCoreApplication::postEvent(mApp, ev);
}

HsQMLManagerApp::HsQMLManagerApp()
    : mArgC(1)
    , mArg0(0)
    , mArgV(&mArg0)
    , mApp(mArgC, &mArgV)
{
    mApp.setQuitOnLastWindowClosed(false);
}

HsQMLManagerApp::~HsQMLManagerApp()
{}

void HsQMLManagerApp::customEvent(QEvent* ev)
{
    switch (ev->type()) {
    case HsQMLManagerApp::StartedLoopEvent: {
        gManager->mRunning = true;
        gManager->mRunCount++;
        gManager->mLock.unlock();
        gManager->mStartCb();
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::StopLoopEvent: {
        gManager->mLock.lock();
        gManager->mRunning = false;
        gManager->mApp->mApp.quit();
        break;}
    case HsQMLManagerApp::PendingJobsEvent: {
        gManager->mJobsCb();
        break;}
    case HsQMLManagerApp::RemoveGCLockEvent: {
        static_cast<HsQMLObjectEvent*>(ev)->process();
        break;}
    }
}

void HsQMLManagerApp::timerEvent(QTimerEvent*)
{
    Q_ASSERT(gManager->mYieldCb);
    gManager->mYieldCb();
}

void HsQMLManagerApp::createEngine(HsQMLEngineConfig config)
{
    HsQMLEngine* engine = new HsQMLEngine(config);
    engine->setParent(this);
}

int HsQMLManagerApp::exec()
{
    return mApp.exec();
}

extern "C" void hsqml_init(
    void (*freeFun)(HsFunPtr),
    void (*freeStable)(HsStablePtr))
{
    if (gManager == NULL) {
        HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);
        if (!gManager.testAndSetOrdered(NULL, manager)) {
            delete manager;
        }
    }
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_run(
    HsQMLTrivialCb startCb,
    HsQMLTrivialCb jobsCb,
    HsQMLTrivialCb yieldCb)
{
    return gManager->runEventLoop(startCb, jobsCb, yieldCb);
}

extern "C" HsQMLEventLoopStatus hsqml_evloop_require()
{
    return gManager->requireEventLoop();
}

extern "C" void hsqml_evloop_release()
{
    gManager->releaseEventLoop();
}

extern "C" void hsqml_evloop_notify_jobs()
{
    gManager->notifyJobs();
}

extern "C" void hsqml_set_debug_loglevel(int ll)
{
    Q_ASSERT (gManager);
    gManager->setLogLevel(ll);
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <com/sun/star/ucb/Command.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/i18n/XExtendedTransliteration.hpp>
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/script/XInvocation.hpp>

#include <l10ntools/HelpSearch.hxx>
#include <CLucene.h>

#include <rtl/oustringostreaminserter.hxx>

#include <algorithm>
#include <set>

#include <qe/Query.hxx>
#include <qe/DocGenerator.hxx>
#include "resultsetforquery.hxx"
#include "databases.hxx"

using namespace std;
using namespace chelp;
using namespace xmlsearch::excep;
using namespace xmlsearch::qe;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
using namespace com::sun::star::i18n;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;

struct HitItem
{
    rtl::OUString   m_aURL;
    float           m_fScore;

    HitItem( void ) {}
    HitItem( const rtl::OUString& aURL, float fScore )
        : m_aURL( aURL )
        , m_fScore( fScore )
    {}
    bool operator < ( const HitItem& rHitItem ) const
    {
        return rHitItem.m_fScore < m_fScore;
    }
};

ResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >&  xMSF,
                                      const uno::Reference< XContentProvider >&  xProvider,
                                      sal_Int32 nOpenMode,
                                      const uno::Sequence< beans::Property >& seq,
                                      const uno::Sequence< NumberedSortingInfo >& seqSort,
                                      URLParameter& aURLParameter,
                                      Databases* pDatabases )
    : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),
      m_pDatabases( pDatabases ),
      m_aURLParameter( aURLParameter )
{
    Reference< XTransliteration > xTrans(
        xMSF->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.Transliteration" )) ),
        UNO_QUERY );
    Locale aLocale( aURLParameter.get_language(),
                    rtl::OUString(),
                    rtl::OUString() );
    if(xTrans.is())
        xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,
                           aLocale );

    vector< vector< rtl::OUString > > queryList;
    {
        sal_Int32 idx;
        rtl::OUString query = m_aURLParameter.get_query();
        while( !query.isEmpty() )
        {
            idx = query.indexOf( sal_Unicode( ' ' ) );
            if( idx == -1 )
                idx = query.getLength();

            vector< rtl::OUString > currentQuery;
            rtl::OUString tmp(query.copy( 0,idx ));
            rtl:: OUString toliterate = tmp;
            if(xTrans.is()) {
                Sequence<sal_Int32> aSeq;
                toliterate = xTrans->transliterate(
                    tmp,0,tmp.getLength(),aSeq);
            }

            currentQuery.push_back( toliterate );
            queryList.push_back( currentQuery );

            int nCpy = 1 + idx;
            if( nCpy >= query.getLength() )
                query = rtl::OUString();
            else
                query = query.copy( 1 + idx );
        }
    }

    vector< rtl::OUString > aCompleteResultVector;
    rtl::OUString scope = m_aURLParameter.get_scope();
    bool bCaptionsOnly = ( scope.compareToAscii( "Heading" ) == 0 );
    sal_Int32 hitCount = m_aURLParameter.get_hitCount();

    IndexFolderIterator aIndexFolderIt( *pDatabases, m_aURLParameter.get_module(), m_aURLParameter.get_language() );
    rtl::OUString idxDir;
    bool bExtension = false;
    int iDir = 0;
    vector< vector<HitItem>* > aIndexFolderResultVectorVector;

    bool bTemporary;
    while( !(idxDir = aIndexFolderIt.nextIndexFolder( bExtension, bTemporary )).isEmpty() )
    {
        vector<HitItem> aIndexFolderResultVector;

        try
        {
            vector< vector<HitItem>* > aQueryListResultVectorVector;
            set< rtl::OUString > aSet,aCurrent,aResultSet;

            int nQueryListSize = queryList.size();
            if( nQueryListSize > 1 )
                hitCount = 2000;

            for( int i = 0; i < nQueryListSize; ++i )
            {
                vector<HitItem>* pQueryResultVector;
                if( nQueryListSize > 1 )
                {
                    pQueryResultVector = new vector<HitItem>();
                    aQueryListResultVectorVector.push_back( pQueryResultVector );
                }
                else
                {
                    pQueryResultVector = &aIndexFolderResultVector;
                }
                pQueryResultVector->reserve( hitCount );

                rtl::OUString aLang = m_aURLParameter.get_language();
                const std::vector< rtl::OUString >& aListItem = queryList[i];
                ::rtl::OUString aNewQueryStr = aListItem[0];

                vector<float> aScoreVector;
                vector<rtl::OUString> aPathVector;

                try
                {
                    HelpSearch searcher(aLang, idxDir);
                    searcher.query(aNewQueryStr, bCaptionsOnly, aPathVector, aScoreVector);
                }
                catch (CLuceneError &e)
                {
                    SAL_WARN("xmlhelp", "CLuceneError: " << e.what());
                }

                if( nQueryListSize > 1 )
                    aSet.clear();

                for (unsigned j = 0; j < aPathVector.size(); ++j) {
                    pQueryResultVector->push_back(HitItem(aPathVector[j], aScoreVector[j]));
                    if (nQueryListSize > 1)
                        aSet.insert(aPathVector[j]);
                }

                // intersect
                if( nQueryListSize > 1 )
                {
                    if( i == 0 )
                    {
                        aResultSet = aSet;
                    }
                    else
                    {
                        aCurrent = aResultSet;
                        aResultSet.clear();
                        set_intersection( aSet.begin(),aSet.end(),
                                          aCurrent.begin(),aCurrent.end(),
                                          inserter(aResultSet,aResultSet.begin()));
                    }
                }
            }

            // Combine results in aIndexFolderResultVector
            if( nQueryListSize > 1 )
            {
                for( int n = 0 ; n < nQueryListSize ; ++n )
                {
                    vector<HitItem>* pQueryResultVector = aQueryListResultVectorVector[n];
                    vector<HitItem>& rQueryResultVector = *pQueryResultVector;

                    int nItemCount = rQueryResultVector.size();
                    for( int i = 0 ; i < nItemCount ; ++i )
                    {
                        const HitItem& rItem = rQueryResultVector[ i ];
                        set< rtl::OUString >::iterator it;
                        if( (it = aResultSet.find( rItem.m_aURL )) != aResultSet.end() )
                        {
                            HitItem aItemCopy( rItem );
                            aItemCopy.m_fScore /= nQueryListSize;   // To get average score
                            if( n == 0 )
                            {
                                // Use first pass to create entry
                                aIndexFolderResultVector.push_back( aItemCopy );
                            }
                            else
                            {
                                // Find entry in vector
                                int nCount = aIndexFolderResultVector.size();
                                for( int j = 0 ; j < nCount ; ++j )
                                {
                                    HitItem& rFindItem = aIndexFolderResultVector[ j ];
                                    if( rFindItem.m_aURL.equals( aItemCopy.m_aURL ) )
                                    {
                                        rFindItem.m_fScore += aItemCopy.m_fScore;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    delete pQueryResultVector;
                }

                sort( aIndexFolderResultVector.begin(), aIndexFolderResultVector.end() );
            }

            vector<HitItem>* pIndexFolderHitItemVector = new vector<HitItem>( aIndexFolderResultVector );
            aIndexFolderResultVectorVector.push_back( pIndexFolderHitItemVector );
            aIndexFolderResultVector.clear();
        }
        catch (const Exception &e)
        {
            SAL_WARN("xmlhelp", "Exception: " << e.Message);
        }

        ++iDir;

        if( bTemporary )
            aIndexFolderIt.deleteTempIndexFolder( idxDir );

    }   // Iterator

    int nVectorCount = aIndexFolderResultVectorVector.size();
    vector<HitItem>::size_type* pCurrentVectorIndex = new vector<HitItem>::size_type[nVectorCount];
    for( int j = 0 ; j < nVectorCount ; ++j )
        pCurrentVectorIndex[j] = 0;

    sal_Int32 nTotalHitCount = m_aURLParameter.get_hitCount();
    sal_Int32 nHitCount = 0;
    while( nHitCount < nTotalHitCount )
    {
        int iVectorWithBestScore = -1;
        float fBestScore = 0.0;
        for( int k = 0 ; k < nVectorCount ; ++k )
        {
            vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[k];
            if( pCurrentVectorIndex[k] < rIndexFolderVector.size() )
            {
                const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[k] ];

                if( fBestScore < rItem.m_fScore )
                {
                    fBestScore = rItem.m_fScore;
                    iVectorWithBestScore = k;
                }
            }
        }

        if( iVectorWithBestScore == -1 )    // No item left at all
            break;

        vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[iVectorWithBestScore];
        const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[iVectorWithBestScore] ];

        pCurrentVectorIndex[iVectorWithBestScore]++;

        aCompleteResultVector.push_back( rItem.m_aURL );
        ++nHitCount;
    }

    delete[] pCurrentVectorIndex;
    for( int n = 0 ; n < nVectorCount ; ++n )
    {
        vector<HitItem>* pIndexFolderVector = aIndexFolderResultVectorVector[n];
        delete pIndexFolderVector;
    }

    sal_Int32 replIdx = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "#HLP#" )).getLength();
    rtl::OUString replWith = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.help://" ));

    int nResultCount = aCompleteResultVector.size();
    for( int r = 0 ; r < nResultCount ; ++r )
    {
        rtl::OUString aURL = aCompleteResultVector[r];
        rtl::OUString aResultStr = replWith + aURL.copy(replIdx);
          m_aPath.push_back( aResultStr );
    }

    m_aItems.resize( m_aPath.size() );
    m_aIdents.resize( m_aPath.size() );

    Command aCommand;
    aCommand.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ));
    aCommand.Argument <<= m_sProperty;

    for( m_nRow = 0; sal::static_int_cast<sal_uInt32>( m_nRow ) < m_aPath.size(); ++m_nRow )
    {
        m_aPath[m_nRow] =
            m_aPath[m_nRow]                                          +
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "?Language=" ))           +
            m_aURLParameter.get_language()                           +
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "&System=" ))             +
            m_aURLParameter.get_system();

        uno::Reference< XContent > content = queryContent();
        if( content.is() )
        {
            uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );
            cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow]; //TODO: check return value of operator >>=
        }
    }
    m_nRow = 0xffffffff;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: silence warnings from msvc2008 (again)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <com/sun/star/ucb/Command.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/i18n/XExtendedTransliteration.hpp>
#include <com/sun/star/ucb/XCommandProcessor.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/script/XInvocation.hpp>

#include <l10ntools/HelpSearch.hxx>

#if defined _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4068 4263 4264 4266)
#endif

#include <CLucene.h>

#if defined _MSC_VER
#pragma warning(pop)
#endif

#include <rtl/oustringostreaminserter.hxx>

#include <algorithm>
#include <set>

#include <qe/Query.hxx>
#include <qe/DocGenerator.hxx>
#include "resultsetforquery.hxx"
#include "databases.hxx"

using namespace std;
using namespace chelp;
using namespace xmlsearch::excep;
using namespace xmlsearch::qe;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
using namespace com::sun::star::i18n;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;

struct HitItem
{
    rtl::OUString   m_aURL;
    float           m_fScore;

    HitItem( void ) {}
    HitItem( const rtl::OUString& aURL, float fScore )
        : m_aURL( aURL )
        , m_fScore( fScore )
    {}
    bool operator < ( const HitItem& rHitItem ) const
    {
        return rHitItem.m_fScore < m_fScore;
    }
};

ResultSetForQuery::ResultSetForQuery( const uno::Reference< lang::XMultiServiceFactory >&  xMSF,
                                      const uno::Reference< XContentProvider >&  xProvider,
                                      sal_Int32 nOpenMode,
                                      const uno::Sequence< beans::Property >& seq,
                                      const uno::Sequence< NumberedSortingInfo >& seqSort,
                                      URLParameter& aURLParameter,
                                      Databases* pDatabases )
    : ResultSetBase( xMSF,xProvider,nOpenMode,seq,seqSort ),
      m_pDatabases( pDatabases ),
      m_aURLParameter( aURLParameter )
{
    Reference< XTransliteration > xTrans(
        xMSF->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.Transliteration" )) ),
        UNO_QUERY );
    Locale aLocale( aURLParameter.get_language(),
                    rtl::OUString(),
                    rtl::OUString() );
    if(xTrans.is())
        xTrans->loadModule(TransliterationModules_UPPERCASE_LOWERCASE,
                           aLocale );

    vector< vector< rtl::OUString > > queryList;
    {
        sal_Int32 idx;
        rtl::OUString query = m_aURLParameter.get_query();
        while( !query.isEmpty() )
        {
            idx = query.indexOf( sal_Unicode( ' ' ) );
            if( idx == -1 )
                idx = query.getLength();

            vector< rtl::OUString > currentQuery;
            rtl::OUString tmp(query.copy( 0,idx ));
            rtl:: OUString toliterate = tmp;
            if(xTrans.is()) {
                Sequence<sal_Int32> aSeq;
                toliterate = xTrans->transliterate(
                    tmp,0,tmp.getLength(),aSeq);
            }

            currentQuery.push_back( toliterate );
            queryList.push_back( currentQuery );

            int nCpy = 1 + idx;
            if( nCpy >= query.getLength() )
                query = rtl::OUString();
            else
                query = query.copy( 1 + idx );
        }
    }

    vector< rtl::OUString > aCompleteResultVector;
    rtl::OUString scope = m_aURLParameter.get_scope();
    bool bCaptionsOnly = ( scope.compareToAscii( "Heading" ) == 0 );
    sal_Int32 hitCount = m_aURLParameter.get_hitCount();

    IndexFolderIterator aIndexFolderIt( *pDatabases, m_aURLParameter.get_module(), m_aURLParameter.get_language() );
    rtl::OUString idxDir;
    bool bExtension = false;
    int iDir = 0;
    vector< vector<HitItem>* > aIndexFolderResultVectorVector;

    bool bTemporary;
    while( !(idxDir = aIndexFolderIt.nextIndexFolder( bExtension, bTemporary )).isEmpty() )
    {
        vector<HitItem> aIndexFolderResultVector;

        try
        {
            vector< vector<HitItem>* > aQueryListResultVectorVector;
            set< rtl::OUString > aSet,aCurrent,aResultSet;

            int nQueryListSize = queryList.size();
            if( nQueryListSize > 1 )
                hitCount = 2000;

            for( int i = 0; i < nQueryListSize; ++i )
            {
                vector<HitItem>* pQueryResultVector;
                if( nQueryListSize > 1 )
                {
                    pQueryResultVector = new vector<HitItem>();
                    aQueryListResultVectorVector.push_back( pQueryResultVector );
                }
                else
                {
                    pQueryResultVector = &aIndexFolderResultVector;
                }
                pQueryResultVector->reserve( hitCount );

                rtl::OUString aLang = m_aURLParameter.get_language();
                const std::vector< rtl::OUString >& aListItem = queryList[i];
                ::rtl::OUString aNewQueryStr = aListItem[0];

                vector<float> aScoreVector;
                vector<rtl::OUString> aPathVector;

                try
                {
                    HelpSearch searcher(aLang, idxDir);
                    searcher.query(aNewQueryStr, bCaptionsOnly, aPathVector, aScoreVector);
                }
                catch (CLuceneError &e)
                {
                    SAL_WARN("xmlhelp", "CLuceneError: " << e.what());
                }

                if( nQueryListSize > 1 )
                    aSet.clear();

                for (unsigned j = 0; j < aPathVector.size(); ++j) {
                    pQueryResultVector->push_back(HitItem(aPathVector[j], aScoreVector[j]));
                    if (nQueryListSize > 1)
                        aSet.insert(aPathVector[j]);
                }

                // intersect
                if( nQueryListSize > 1 )
                {
                    if( i == 0 )
                    {
                        aResultSet = aSet;
                    }
                    else
                    {
                        aCurrent = aResultSet;
                        aResultSet.clear();
                        set_intersection( aSet.begin(),aSet.end(),
                                          aCurrent.begin(),aCurrent.end(),
                                          inserter(aResultSet,aResultSet.begin()));
                    }
                }
            }

            // Combine results in aIndexFolderResultVector
            if( nQueryListSize > 1 )
            {
                for( int n = 0 ; n < nQueryListSize ; ++n )
                {
                    vector<HitItem>* pQueryResultVector = aQueryListResultVectorVector[n];
                    vector<HitItem>& rQueryResultVector = *pQueryResultVector;

                    int nItemCount = rQueryResultVector.size();
                    for( int i = 0 ; i < nItemCount ; ++i )
                    {
                        const HitItem& rItem = rQueryResultVector[ i ];
                        set< rtl::OUString >::iterator it;
                        if( (it = aResultSet.find( rItem.m_aURL )) != aResultSet.end() )
                        {
                            HitItem aItemCopy( rItem );
                            aItemCopy.m_fScore /= nQueryListSize;   // To get average score
                            if( n == 0 )
                            {
                                // Use first pass to create entry
                                aIndexFolderResultVector.push_back( aItemCopy );
                            }
                            else
                            {
                                // Find entry in vector
                                int nCount = aIndexFolderResultVector.size();
                                for( int j = 0 ; j < nCount ; ++j )
                                {
                                    HitItem& rFindItem = aIndexFolderResultVector[ j ];
                                    if( rFindItem.m_aURL.equals( aItemCopy.m_aURL ) )
                                    {
                                        rFindItem.m_fScore += aItemCopy.m_fScore;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    delete pQueryResultVector;
                }

                sort( aIndexFolderResultVector.begin(), aIndexFolderResultVector.end() );
            }

            vector<HitItem>* pIndexFolderHitItemVector = new vector<HitItem>( aIndexFolderResultVector );
            aIndexFolderResultVectorVector.push_back( pIndexFolderHitItemVector );
            aIndexFolderResultVector.clear();
        }
        catch (const Exception &e)
        {
            SAL_WARN("xmlhelp", "Exception: " << e.Message);
        }

        ++iDir;

        if( bTemporary )
            aIndexFolderIt.deleteTempIndexFolder( idxDir );

    }   // Iterator

    int nVectorCount = aIndexFolderResultVectorVector.size();
    vector<HitItem>::size_type* pCurrentVectorIndex = new vector<HitItem>::size_type[nVectorCount];
    for( int j = 0 ; j < nVectorCount ; ++j )
        pCurrentVectorIndex[j] = 0;

    sal_Int32 nTotalHitCount = m_aURLParameter.get_hitCount();
    sal_Int32 nHitCount = 0;
    while( nHitCount < nTotalHitCount )
    {
        int iVectorWithBestScore = -1;
        float fBestScore = 0.0;
        for( int k = 0 ; k < nVectorCount ; ++k )
        {
            vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[k];
            if( pCurrentVectorIndex[k] < rIndexFolderVector.size() )
            {
                const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[k] ];

                if( fBestScore < rItem.m_fScore )
                {
                    fBestScore = rItem.m_fScore;
                    iVectorWithBestScore = k;
                }
            }
        }

        if( iVectorWithBestScore == -1 )    // No item left at all
            break;

        vector<HitItem>& rIndexFolderVector = *aIndexFolderResultVectorVector[iVectorWithBestScore];
        const HitItem& rItem = rIndexFolderVector[ pCurrentVectorIndex[iVectorWithBestScore] ];

        pCurrentVectorIndex[iVectorWithBestScore]++;

        aCompleteResultVector.push_back( rItem.m_aURL );
        ++nHitCount;
    }

    delete[] pCurrentVectorIndex;
    for( int n = 0 ; n < nVectorCount ; ++n )
    {
        vector<HitItem>* pIndexFolderVector = aIndexFolderResultVectorVector[n];
        delete pIndexFolderVector;
    }

    sal_Int32 replIdx = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "#HLP#" )).getLength();
    rtl::OUString replWith = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.help://" ));

    int nResultCount = aCompleteResultVector.size();
    for( int r = 0 ; r < nResultCount ; ++r )
    {
        rtl::OUString aURL = aCompleteResultVector[r];
        rtl::OUString aResultStr = replWith + aURL.copy(replIdx);
          m_aPath.push_back( aResultStr );
    }

    m_aItems.resize( m_aPath.size() );
    m_aIdents.resize( m_aPath.size() );

    Command aCommand;
    aCommand.Name = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ));
    aCommand.Argument <<= m_sProperty;

    for( m_nRow = 0; sal::static_int_cast<sal_uInt32>( m_nRow ) < m_aPath.size(); ++m_nRow )
    {
        m_aPath[m_nRow] =
            m_aPath[m_nRow]                                          +
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "?Language=" ))           +
            m_aURLParameter.get_language()                           +
            rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "&System=" ))             +
            m_aURLParameter.get_system();

        uno::Reference< XContent > content = queryContent();
        if( content.is() )
        {
            uno::Reference< XCommandProcessor > cmd( content,uno::UNO_QUERY );
            cmd->execute( aCommand,0,uno::Reference< XCommandEnvironment >( 0 ) ) >>= m_aItems[m_nRow]; //TODO: check return value of operator >>=
        }
    }
    m_nRow = 0xffffffff;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFIABLE_HPP_
#include <com/sun/star/util/XModifiable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFIABLE2_HPP_
#include <com/sun/star/util/XModifiable2.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTORABLE_HPP_
#include <com/sun/star/frame/XStorable.hpp>
#endif

// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif

#ifndef _GLOBNAME_HXX
#include <tools/globname.hxx>
#endif
#ifndef _SOT_CLSIDS_HXX
#include <sot/clsids.hxx>
#endif
#ifndef _GLOBNAME_HXX
#include <tools/globname.hxx>
#endif
#ifndef _SOT_CLSIDS_HXX
#include <sot/clsids.hxx>
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLERROR_HXX
#include "xmlerror.hxx"
#endif
#ifndef _XMLOFF_ATTRLIST_HXX
#include <xmloff/attrlist.hxx>
#endif

#ifndef _XMLOFF_XMLFILTERSERVICENAMES_H
#include "XMLFilterServiceNames.h"
#endif
#ifndef _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX
#include "XMLEmbeddedObjectImportContext.hxx"
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

struct XMLServiceMapEntry_Impl
{
    enum XMLTokenEnum eClass;
    const sal_Char *sFilterService;
    sal_Int32      nFilterServiceLen;
};

#define SERVICE_MAP_ENTRY( cls, app ) \
    { XML_##cls, \
      XML_IMPORT_FILTER_##app, sizeof(XML_IMPORT_FILTER_##app)-1}

const XMLServiceMapEntry_Impl aServiceMap[] =
{
    SERVICE_MAP_ENTRY( TEXT, WRITER ),
    SERVICE_MAP_ENTRY( ONLINE_TEXT, WRITER ),
    SERVICE_MAP_ENTRY( SPREADSHEET, CALC ),
    SERVICE_MAP_ENTRY( DRAWING, DRAW ),
    SERVICE_MAP_ENTRY( GRAPHICS, DRAW ),
    SERVICE_MAP_ENTRY( PRESENTATION, IMPRESS ),
    SERVICE_MAP_ENTRY( CHART, CHART ),
    { XML_TOKEN_INVALID, 0, 0 }
};

class XMLEmbeddedObjectImportContext_Impl : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > xHandler;

public:
    TYPEINFO();

    XMLEmbeddedObjectImportContext_Impl( SvXMLImport& rImport, USHORT nPrfx,
                                    const ::rtl::OUString& rLName,
    const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler >& rHandler );

    virtual ~XMLEmbeddedObjectImportContext_Impl();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();

    virtual void Characters( const ::rtl::OUString& rChars );
};

TYPEINIT1( XMLEmbeddedObjectImportContext_Impl, SvXMLImportContext );

XMLEmbeddedObjectImportContext_Impl::XMLEmbeddedObjectImportContext_Impl(
        SvXMLImport& rImport, USHORT nPrfx,
        const OUString& rLName,
        const Reference< XDocumentHandler >& rHandler ) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    xHandler( rHandler )
{
}

XMLEmbeddedObjectImportContext_Impl::~XMLEmbeddedObjectImportContext_Impl()
{
}

SvXMLImportContext *XMLEmbeddedObjectImportContext_Impl::CreateChildContext(
        USHORT nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList >& )
{
    return new XMLEmbeddedObjectImportContext_Impl( GetImport(),
                                                    nPrefix, rLocalName,
                                                    xHandler );
}

void XMLEmbeddedObjectImportContext_Impl::StartElement(
        const Reference< XAttributeList >& xAttrList )
{
    xHandler->startElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                GetPrefix(), GetLocalName() ),
                            xAttrList );
}

void XMLEmbeddedObjectImportContext_Impl::EndElement()
{
    xHandler->endElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                GetPrefix(), GetLocalName() ) );
}

void XMLEmbeddedObjectImportContext_Impl::Characters( const OUString& rChars )
{
    xHandler->characters( rChars );
}

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

TYPEINIT1( XMLEmbeddedObjectImportContext, SvXMLImportContext );

sal_Bool XMLEmbeddedObjectImportContext::SetComponent(
        Reference< XComponent >& rComp )
{
    if( !rComp.is() || !sFilterService.getLength() )
        return sal_False;

    Sequence<Any> aArgs( 0 );

    // #110680#
    // Reference< XMultiServiceFactory > xServiceFactory = comphelper::getProcessServiceFactory();
    Reference< XMultiServiceFactory > xServiceFactory = GetImport().getServiceFactory();

    xHandler = Reference < XDocumentHandler >(
        xServiceFactory->createInstanceWithArguments( sFilterService, aArgs),
                                               UNO_QUERY);

    if( !xHandler.is() )
        return sal_False;

    try
    {
        Reference < XModifiable2 > xModifiable2( rComp, UNO_QUERY_THROW );
        xModifiable2->disableSetModified();
    }
    catch( Exception& )
    {
    }

    Reference < XImporter > xImporter( xHandler, UNO_QUERY );
    xImporter->setTargetDocument( rComp );

    xComp = rComp;  // keep ref to component only if there is a handler

    return sal_True;
}

XMLEmbeddedObjectImportContext::XMLEmbeddedObjectImportContext(
        SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName,
        const Reference< XAttributeList >& xAttrList ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    SvGlobalName aName;

    if( nPrfx == XML_NAMESPACE_MATH &&
        IsXMLToken( rLName, XML_MATH ) )
    {
        sFilterService = OUString( RTL_CONSTASCII_USTRINGPARAM(XML_IMPORT_FILTER_MATH) );
        aName = SvGlobalName(SO3_SM_CLASSID);
    }
    else if( nPrfx == XML_NAMESPACE_OFFICE &&
        IsXMLToken( rLName, XML_DOCUMENT ) )
    {
        OUString sMime;

        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
        for( sal_Int16 i=0; i < nAttrCount; i++ )
        {
            const OUString& rAttrName = xAttrList->getNameByIndex( i );
            OUString aLocalName;
            sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
            if( nPrefix == XML_NAMESPACE_OFFICE &&
                IsXMLToken( aLocalName, XML_MIMETYPE ) )
            {
                sMime = xAttrList->getValueByIndex( i );
                break;
            }
        }

        OUString sClass;
        static const char * aTmp[] =
        {
            "application/vnd.oasis.openoffice.",
            "application/x-vnd.oasis.openoffice.",
            "application/vnd.oasis.opendocument.",
            "application/x-vnd.oasis.opendocument.",
            NULL
        };
        for (int k=0; aTmp[k]; k++)
        {
            ::rtl::OUString sTmpString = ::rtl::OUString::createFromAscii(aTmp[k]);
            if( sMime.matchAsciiL( aTmp[k], sTmpString.getLength() ) )
            {
                sClass = sMime.copy( sTmpString.getLength() );
                break;
            }
        }

        if( sClass.getLength() )
        {
            const XMLServiceMapEntry_Impl *pEntry = aServiceMap;
            while( pEntry->eClass != XML_TOKEN_INVALID )
            {
                if( IsXMLToken( sClass, pEntry->eClass ) )
                {
                    sFilterService = OUString( pEntry->sFilterService,
                                               pEntry->nFilterServiceLen,
                                               RTL_TEXTENCODING_ASCII_US );

                    switch( pEntry->eClass )
                    {
                    case XML_TEXT:          aName = SvGlobalName(SO3_SW_CLASSID); break;
                    case XML_ONLINE_TEXT:   aName = SvGlobalName(SO3_SWWEB_CLASSID); break;
                    case XML_SPREADSHEET:   aName = SvGlobalName(SO3_SC_CLASSID); break;
                    case XML_DRAWING:
                    case XML_GRAPHICS:
                    case XML_IMAGE:     aName = SvGlobalName(SO3_SDRAW_CLASSID); break;
                    case XML_PRESENTATION:  aName = SvGlobalName(SO3_SIMPRESS_CLASSID); break;
                    case XML_CHART:         aName = SvGlobalName(SO3_SCH_CLASSID); break;
                    default:
                        break;
                    }

                    break;
                }
                pEntry++;
            }
        }
    }

    sCLSID = aName.GetHexName();
}

XMLEmbeddedObjectImportContext::~XMLEmbeddedObjectImportContext()
{
}

SvXMLImportContext *XMLEmbeddedObjectImportContext::CreateChildContext(
        USHORT nPrefix, const OUString& rLocalName,
        const Reference< XAttributeList >& )
{
    if( xHandler.is() )
        return new XMLEmbeddedObjectImportContext_Impl( GetImport(),
                                                        nPrefix, rLocalName,
                                                        xHandler );
    else
        return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void XMLEmbeddedObjectImportContext::StartElement(
        const Reference< XAttributeList >& rAttrList )
{
    if( xHandler.is() )
    {
        xHandler->startDocument();
        // #i34042: copy namepspace declarations
        SvXMLAttributeList *pAttrList = new SvXMLAttributeList( rAttrList );
        Reference< XAttributeList > xAttrList( pAttrList );
        const SvXMLNamespaceMap& rNamespaceMap = GetImport().GetNamespaceMap();
        sal_uInt16 nPos = rNamespaceMap.GetFirstKey();
        while( USHRT_MAX != nPos )
        {
            OUString aAttrName( rNamespaceMap.GetAttrNameByKey( nPos ) );
            if( 0 == xAttrList->getValueByName( aAttrName ).getLength() )
            {
                pAttrList->AddAttribute( aAttrName,
                                          rNamespaceMap.GetNameByKey( nPos ) );
            }
            nPos = rNamespaceMap.GetNextKey( nPos );
        }
        xHandler->startElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                    GetPrefix(), GetLocalName() ),
                                xAttrList );
    }
}

void XMLEmbeddedObjectImportContext::EndElement()
{
    if( xHandler.is() )
    {
        xHandler->endElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                    GetPrefix(), GetLocalName() ) );
        xHandler->endDocument();

        // storing part is commented out since it should be done through the object, not the model
        // TODO/LATER: probably an object should be provided here an be stored here

//      // Save the object. That's required because the object should not be
//      // modified (it has been loaded just now). Setting it to unmodified
//      // only does not work, because it is then assumed that it has been
//      // stored.
//      Reference < XStorable > xStorable( xComp, UNO_QUERY );
//      if( xStorable.is() )
//      {
//          try
//          {
//              xStorable->store();
//          }
//          catch( ::com::sun::star::beans::PropertyVetoException& )
//          {
//              Sequence<OUString> aSeq( 0 );
//              GetImport().SetError( XMLERROR_FLAG_WARNING |
//                                XMLERROR_API,
//                                aSeq );
//          }
//      }

    try
    {
        Reference < XModifiable2 > xModifiable2( xComp, UNO_QUERY_THROW );
        xModifiable2->enableSetModified();
        xModifiable2->setModified( sal_True ); // trigger new replacement image generation
    }
    catch( Exception& )
    {
    }

//      // reset modifies state for the object since it has been imported
//      // completly and therfor hasn't been modified.
//      Reference < XModifiable > xModifiable( xComp, UNO_QUERY );
//      if( xModifiable.is() )
//      {
//          try
//          {
//              xModifiable->setModified( sal_False );
//          }
//          catch( ::com::sun::star::beans::PropertyVetoException& e )
//          {
//              Sequence<OUString> aSeq( 0 );
//              GetImport().SetError( XMLERROR_FLAG_WARNING |
//                                XMLERROR_API,
//                                aSeq );
//          }
//      }
    }
}

void XMLEmbeddedObjectImportContext::Characters( const ::rtl::OUString& rChars )
{
    if( xHandler.is() )
        xHandler->characters( rChars );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.17.18); FILE MERGED 2008/04/01 16:09:34 thb 1.17.18.3: #i85898# Stripping all external header guards 2008/04/01 13:04:35 thb 1.17.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:04 rt 1.17.18.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: XMLEmbeddedObjectImportContext.cxx,v $
 * $Revision: 1.18 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <com/sun/star/document/XImporter.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XModifiable2.hpp>
#include <com/sun/star/frame/XStorable.hpp>

// #110680#
//#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
//#include <comphelper/processfactory.hxx>
//#endif
#include <tools/globname.hxx>
#include <sot/clsids.hxx>
#include <tools/globname.hxx>
#include <sot/clsids.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmlimp.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include "xmlerror.hxx"
#include <xmloff/attrlist.hxx>
#include "XMLFilterServiceNames.h"
#include "XMLEmbeddedObjectImportContext.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;

struct XMLServiceMapEntry_Impl
{
    enum XMLTokenEnum eClass;
    const sal_Char *sFilterService;
    sal_Int32      nFilterServiceLen;
};

#define SERVICE_MAP_ENTRY( cls, app ) \
    { XML_##cls, \
      XML_IMPORT_FILTER_##app, sizeof(XML_IMPORT_FILTER_##app)-1}

const XMLServiceMapEntry_Impl aServiceMap[] =
{
    SERVICE_MAP_ENTRY( TEXT, WRITER ),
    SERVICE_MAP_ENTRY( ONLINE_TEXT, WRITER ),
    SERVICE_MAP_ENTRY( SPREADSHEET, CALC ),
    SERVICE_MAP_ENTRY( DRAWING, DRAW ),
    SERVICE_MAP_ENTRY( GRAPHICS, DRAW ),
    SERVICE_MAP_ENTRY( PRESENTATION, IMPRESS ),
    SERVICE_MAP_ENTRY( CHART, CHART ),
    { XML_TOKEN_INVALID, 0, 0 }
};

class XMLEmbeddedObjectImportContext_Impl : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > xHandler;

public:
    TYPEINFO();

    XMLEmbeddedObjectImportContext_Impl( SvXMLImport& rImport, USHORT nPrfx,
                                    const ::rtl::OUString& rLName,
    const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler >& rHandler );

    virtual ~XMLEmbeddedObjectImportContext_Impl();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );

    virtual void EndElement();

    virtual void Characters( const ::rtl::OUString& rChars );
};

TYPEINIT1( XMLEmbeddedObjectImportContext_Impl, SvXMLImportContext );

XMLEmbeddedObjectImportContext_Impl::XMLEmbeddedObjectImportContext_Impl(
        SvXMLImport& rImport, USHORT nPrfx,
        const OUString& rLName,
        const Reference< XDocumentHandler >& rHandler ) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    xHandler( rHandler )
{
}

XMLEmbeddedObjectImportContext_Impl::~XMLEmbeddedObjectImportContext_Impl()
{
}

SvXMLImportContext *XMLEmbeddedObjectImportContext_Impl::CreateChildContext(
        USHORT nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList >& )
{
    return new XMLEmbeddedObjectImportContext_Impl( GetImport(),
                                                    nPrefix, rLocalName,
                                                    xHandler );
}

void XMLEmbeddedObjectImportContext_Impl::StartElement(
        const Reference< XAttributeList >& xAttrList )
{
    xHandler->startElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                GetPrefix(), GetLocalName() ),
                            xAttrList );
}

void XMLEmbeddedObjectImportContext_Impl::EndElement()
{
    xHandler->endElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                GetPrefix(), GetLocalName() ) );
}

void XMLEmbeddedObjectImportContext_Impl::Characters( const OUString& rChars )
{
    xHandler->characters( rChars );
}

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

TYPEINIT1( XMLEmbeddedObjectImportContext, SvXMLImportContext );

sal_Bool XMLEmbeddedObjectImportContext::SetComponent(
        Reference< XComponent >& rComp )
{
    if( !rComp.is() || !sFilterService.getLength() )
        return sal_False;

    Sequence<Any> aArgs( 0 );

    // #110680#
    // Reference< XMultiServiceFactory > xServiceFactory = comphelper::getProcessServiceFactory();
    Reference< XMultiServiceFactory > xServiceFactory = GetImport().getServiceFactory();

    xHandler = Reference < XDocumentHandler >(
        xServiceFactory->createInstanceWithArguments( sFilterService, aArgs),
                                               UNO_QUERY);

    if( !xHandler.is() )
        return sal_False;

    try
    {
        Reference < XModifiable2 > xModifiable2( rComp, UNO_QUERY_THROW );
        xModifiable2->disableSetModified();
    }
    catch( Exception& )
    {
    }

    Reference < XImporter > xImporter( xHandler, UNO_QUERY );
    xImporter->setTargetDocument( rComp );

    xComp = rComp;  // keep ref to component only if there is a handler

    return sal_True;
}

XMLEmbeddedObjectImportContext::XMLEmbeddedObjectImportContext(
        SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName,
        const Reference< XAttributeList >& xAttrList ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    SvGlobalName aName;

    if( nPrfx == XML_NAMESPACE_MATH &&
        IsXMLToken( rLName, XML_MATH ) )
    {
        sFilterService = OUString( RTL_CONSTASCII_USTRINGPARAM(XML_IMPORT_FILTER_MATH) );
        aName = SvGlobalName(SO3_SM_CLASSID);
    }
    else if( nPrfx == XML_NAMESPACE_OFFICE &&
        IsXMLToken( rLName, XML_DOCUMENT ) )
    {
        OUString sMime;

        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
        for( sal_Int16 i=0; i < nAttrCount; i++ )
        {
            const OUString& rAttrName = xAttrList->getNameByIndex( i );
            OUString aLocalName;
            sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
            if( nPrefix == XML_NAMESPACE_OFFICE &&
                IsXMLToken( aLocalName, XML_MIMETYPE ) )
            {
                sMime = xAttrList->getValueByIndex( i );
                break;
            }
        }

        OUString sClass;
        static const char * aTmp[] =
        {
            "application/vnd.oasis.openoffice.",
            "application/x-vnd.oasis.openoffice.",
            "application/vnd.oasis.opendocument.",
            "application/x-vnd.oasis.opendocument.",
            NULL
        };
        for (int k=0; aTmp[k]; k++)
        {
            ::rtl::OUString sTmpString = ::rtl::OUString::createFromAscii(aTmp[k]);
            if( sMime.matchAsciiL( aTmp[k], sTmpString.getLength() ) )
            {
                sClass = sMime.copy( sTmpString.getLength() );
                break;
            }
        }

        if( sClass.getLength() )
        {
            const XMLServiceMapEntry_Impl *pEntry = aServiceMap;
            while( pEntry->eClass != XML_TOKEN_INVALID )
            {
                if( IsXMLToken( sClass, pEntry->eClass ) )
                {
                    sFilterService = OUString( pEntry->sFilterService,
                                               pEntry->nFilterServiceLen,
                                               RTL_TEXTENCODING_ASCII_US );

                    switch( pEntry->eClass )
                    {
                    case XML_TEXT:          aName = SvGlobalName(SO3_SW_CLASSID); break;
                    case XML_ONLINE_TEXT:   aName = SvGlobalName(SO3_SWWEB_CLASSID); break;
                    case XML_SPREADSHEET:   aName = SvGlobalName(SO3_SC_CLASSID); break;
                    case XML_DRAWING:
                    case XML_GRAPHICS:
                    case XML_IMAGE:     aName = SvGlobalName(SO3_SDRAW_CLASSID); break;
                    case XML_PRESENTATION:  aName = SvGlobalName(SO3_SIMPRESS_CLASSID); break;
                    case XML_CHART:         aName = SvGlobalName(SO3_SCH_CLASSID); break;
                    default:
                        break;
                    }

                    break;
                }
                pEntry++;
            }
        }
    }

    sCLSID = aName.GetHexName();
}

XMLEmbeddedObjectImportContext::~XMLEmbeddedObjectImportContext()
{
}

SvXMLImportContext *XMLEmbeddedObjectImportContext::CreateChildContext(
        USHORT nPrefix, const OUString& rLocalName,
        const Reference< XAttributeList >& )
{
    if( xHandler.is() )
        return new XMLEmbeddedObjectImportContext_Impl( GetImport(),
                                                        nPrefix, rLocalName,
                                                        xHandler );
    else
        return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void XMLEmbeddedObjectImportContext::StartElement(
        const Reference< XAttributeList >& rAttrList )
{
    if( xHandler.is() )
    {
        xHandler->startDocument();
        // #i34042: copy namepspace declarations
        SvXMLAttributeList *pAttrList = new SvXMLAttributeList( rAttrList );
        Reference< XAttributeList > xAttrList( pAttrList );
        const SvXMLNamespaceMap& rNamespaceMap = GetImport().GetNamespaceMap();
        sal_uInt16 nPos = rNamespaceMap.GetFirstKey();
        while( USHRT_MAX != nPos )
        {
            OUString aAttrName( rNamespaceMap.GetAttrNameByKey( nPos ) );
            if( 0 == xAttrList->getValueByName( aAttrName ).getLength() )
            {
                pAttrList->AddAttribute( aAttrName,
                                          rNamespaceMap.GetNameByKey( nPos ) );
            }
            nPos = rNamespaceMap.GetNextKey( nPos );
        }
        xHandler->startElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                    GetPrefix(), GetLocalName() ),
                                xAttrList );
    }
}

void XMLEmbeddedObjectImportContext::EndElement()
{
    if( xHandler.is() )
    {
        xHandler->endElement( GetImport().GetNamespaceMap().GetQNameByKey(
                                    GetPrefix(), GetLocalName() ) );
        xHandler->endDocument();

        // storing part is commented out since it should be done through the object, not the model
        // TODO/LATER: probably an object should be provided here an be stored here

//      // Save the object. That's required because the object should not be
//      // modified (it has been loaded just now). Setting it to unmodified
//      // only does not work, because it is then assumed that it has been
//      // stored.
//      Reference < XStorable > xStorable( xComp, UNO_QUERY );
//      if( xStorable.is() )
//      {
//          try
//          {
//              xStorable->store();
//          }
//          catch( ::com::sun::star::beans::PropertyVetoException& )
//          {
//              Sequence<OUString> aSeq( 0 );
//              GetImport().SetError( XMLERROR_FLAG_WARNING |
//                                XMLERROR_API,
//                                aSeq );
//          }
//      }

    try
    {
        Reference < XModifiable2 > xModifiable2( xComp, UNO_QUERY_THROW );
        xModifiable2->enableSetModified();
        xModifiable2->setModified( sal_True ); // trigger new replacement image generation
    }
    catch( Exception& )
    {
    }

//      // reset modifies state for the object since it has been imported
//      // completly and therfor hasn't been modified.
//      Reference < XModifiable > xModifiable( xComp, UNO_QUERY );
//      if( xModifiable.is() )
//      {
//          try
//          {
//              xModifiable->setModified( sal_False );
//          }
//          catch( ::com::sun::star::beans::PropertyVetoException& e )
//          {
//              Sequence<OUString> aSeq( 0 );
//              GetImport().SetError( XMLERROR_FLAG_WARNING |
//                                XMLERROR_API,
//                                aSeq );
//          }
//      }
    }
}

void XMLEmbeddedObjectImportContext::Characters( const ::rtl::OUString& rChars )
{
    if( xHandler.is() )
        xHandler->characters( rChars );
}

<|endoftext|>


<commit_before>#include <async.h>
#include <aios.h>
#include <db.h>
#include <id_utils.h>
#include <merkle_tree_bdb.h>

int
main (int argc, char *argv[])
{
  setprogname (argv[0]);
  if (argc < 2)
    fatal <<  "Usage: " << progname << " merkletreebdb\n";
  char pathbuf[PATH_MAX];
  sprintf (pathbuf, "%s/mtree", argv[1]);
  ptr<merkle_tree_bdb> tree =
    New refcounted<merkle_tree_bdb> (pathbuf, true, true);

  chordID lastread = 0;
  chordID maxid = (chordID (1) << 160) - 1;
  vec<chordID> keys = tree->get_keyrange (0, maxid, 64);
  while (keys.size ()) {
    for (size_t i = 0; i < keys.size (); i++)
      aout << keys[i] << "\n";
    lastread = keys.back ();
    if (keys.size () < 64)
      break;
    keys = tree->get_keyrange (incID (lastread), maxid, 64);
  }
}

<commit_msg>Allow merkledump to handle maintwalk/maintd trees.<commit_after>#include <async.h>
#include <aios.h>
#include <db.h>
#include <id_utils.h>
#include <merkle_tree_bdb.h>

int
main (int argc, char *argv[])
{
  setprogname (argv[0]);
  if (argc < 2)
    fatal <<  "Usage: " << progname << " merkletreebdb\n";

  ptr<merkle_tree_bdb> tree = NULL;
  if (merkle_tree_bdb::tree_exists (argv[1])) {
    // Handle case where path is given directly
    tree = New refcounted<merkle_tree_bdb> (argv[1], true, true);
  } else {
    // Handle case where path may owned by adbd.
    char pathbuf[PATH_MAX];
    sprintf (pathbuf, "%s/mtree", argv[1]);
    tree = New refcounted<merkle_tree_bdb> (pathbuf, true, true);
    // Fatal if this tree does not exist.
  }

  chordID lastread = 0;
  chordID maxid = (chordID (1) << 160) - 1;
  vec<chordID> keys = tree->get_keyrange (0, maxid, 64);
  while (keys.size ()) {
    for (size_t i = 0; i < keys.size (); i++)
      aout << keys[i] << "\n";
    lastread = keys.back ();
    if (keys.size () < 64)
      break;
    keys = tree->get_keyrange (incID (lastread), maxid, 64);
  }
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_OPENCL_SELECT_EVENTS_HPP
#define STAN_MATH_OPENCL_SELECT_EVENTS_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl.hpp>
#include <vector>

namespace stan {
namespace math {
namespace opencl_kernels {

template <typename T>
inline const std::vector<cl::Event> select_events(const T& t) {
  return std::vector<cl::Event>();
}

inline const std::vector<cl::Event>& select_events(const matrix_cl& m) {
  return m.events();
}

inline const std::vector<cl::Event>& select_events(matrix_cl* const& m) {
  return m->events();
}

inline const std::vector<cl::Event>& select_events(
    const std::vector<cl::Event>& m) {
  return m;
}
}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif
<commit_msg>We don't use pointers anywhere do we? removing matrix_cl* overload from select_events<commit_after>#ifndef STAN_MATH_OPENCL_SELECT_EVENTS_HPP
#define STAN_MATH_OPENCL_SELECT_EVENTS_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl.hpp>
#include <vector>

namespace stan {
namespace math {
namespace opencl_kernels {

template <typename T>
inline const std::vector<cl::Event> select_events(const T& t) {
  return std::vector<cl::Event>();
}

inline const std::vector<cl::Event>& select_events(const matrix_cl& m) {
  return m.events();
}

inline const std::vector<cl::Event>& select_events(
    const std::vector<cl::Event>& m) {
  return m;
}
}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif
<|endoftext|>