<commit_before>#include "ThreadsPool.h"

ThreadsPool::ThreadsPool(int thread_num,int request_max):_thread_num(thread_num),_conn_max(request_max),is_work(true){
    threads.clear();
    threads.resize(_thread_num);
    for(int i=0; i< _thread_num; i++){
        std::cout<<"create thread "<<i<<"."<<std::endl;
        if(pthread_create(&threads[i],NULL,worker,this)!=0){
            threads.clear();
            break;
        }
        else if(pthread_detach(threads[i])){
            threads.clear();
            break;
        }
    }
    std::cout<<"threads create complete."<<std::endl;
}

ThreadsPool::~ThreadsPool(){
    threads.clear();
	while(!conn_pool.empty()){
		conn_pool.pop();
	}
	req_pool.clear();
	res_pool.clear();
    is_work = false;
}

bool ThreadsPool::add(int conn,char *read_buff,int buff_size,int req_or_res){
    locker.lock();
    if(conn_pool.size() >= _conn_max){
        locker.unlock();
        return false;
    }
	if(req_or_res == 0){//request
		connection con;
		con.conn = conn;
		con.request_or_response = 0;
		conn_pool.push(con);

		//add to request pool
		std::map<int,Request*>::iterator it;
		it = req_pool.find(conn);
		std::cout<<"inin"<<std::endl;
		if(it != req_pool.end()){//found
			int old_size = req_pool[conn]->content_size;
			char *old_buff = req_pool[conn]->content;
			char *new_buff = new char[old_size+buff_size];
			strncpy(new_buff,old_buff,old_size);
			strncpy(new_buff+old_size,read_buff,buff_size);
			delete[] old_buff;
			req_pool[conn]->content = new_buff;
			req_pool[conn]->content_size = old_size+buff_size;
			return true;
		}
		else{
			std::cout<<"insert"<<std::endl;
			Request *r;
			std::cout<<"insert"<<std::endl;
			request_init(r);
			std::cout<<"insert"<<std::endl;
			r->content_size = buff_size;
			std::cout<<"insert"<<std::endl;
			r->content = read_buff;
			std::cout<<"insert null"<<std::endl;
			req_pool.insert(std::make_pair<int,Request*>(conn,r));
			std::cout<<"insert null"<<std::endl;
			return true;
		}

	}
    locker.unlock();
    status_queue.post();
    return true;
}

void* ThreadsPool::worker(void* arg){
    ThreadsPool *tp = (ThreadsPool*)arg;
    tp->run();
    return tp;
}

void ThreadsPool::run(){
    while(is_work){
        status_queue.wait();
        locker.lock();
        if(conn_pool.empty()){
            locker.unlock();
            continue;
        }
		connection c = conn_pool.front();
		conn_pool.pop();
		if(c.request_or_response == 0){//request
			std::map<int,Request*>::iterator it;
			it = req_pool.find(c.conn);
			if(it!=req_pool.end()){//found
				Request *req = it->second;
				//parser request
			}
			else{
				continue;
			}
		}

        locker.unlock();
        //if(c){
        //    std::cout<<"ok"<<std::endl;
            //r->process();
        //}
    }
}

<commit_msg>add main<commit_after>#include "ThreadsPool.h"

ThreadsPool::ThreadsPool(int thread_num,int request_max):_thread_num(thread_num),_conn_max(request_max),is_work(true){
    threads.clear();
    threads.resize(_thread_num);
    for(int i=0; i< _thread_num; i++){
        std::cout<<"create thread "<<i<<"."<<std::endl;
        if(pthread_create(&threads[i],NULL,worker,this)!=0){
            threads.clear();
            break;
        }
        else if(pthread_detach(threads[i])){
            threads.clear();
            break;
        }
    }
    std::cout<<"threads create complete."<<std::endl;
}

ThreadsPool::~ThreadsPool(){
    threads.clear();
	while(!conn_pool.empty()){
		conn_pool.pop();
	}
	req_pool.clear();
	res_pool.clear();
    is_work = false;
}

bool ThreadsPool::add(int conn,char *read_buff,int buff_size,int req_or_res){
    locker.lock();
    if(conn_pool.size() >= _conn_max){
        locker.unlock();
        return false;
    }
	if(req_or_res == 0){//request
		connection con;
		con.conn = conn;
		con.request_or_response = 0;
		conn_pool.push(con);

		//add to request pool
		std::map<int,Request*>::iterator it;
		it = req_pool.find(conn);
		std::cout<<"inin"<<std::endl;
		if(it != req_pool.end()){//found
			int old_size = req_pool[conn]->content_size;
			char *old_buff = req_pool[conn]->content;
			char *new_buff = new char[old_size+buff_size];
			strncpy(new_buff,old_buff,old_size);
			strncpy(new_buff+old_size,read_buff,buff_size);
			delete[] old_buff;
			req_pool[conn]->content = new_buff;
			req_pool[conn]->content_size = old_size+buff_size;
			return true;
		}
		else{
			std::cout<<"insert"<<std::endl;
			Request *r;
			std::cout<<"insert"<<std::endl;
			request_init(r);
			std::cout<<r->content_size<<std::endl;
			r->content_size = buff_size;
			std::cout<<"insert"<<std::endl;
			r->content = read_buff;
			std::cout<<"insert null"<<std::endl;
			req_pool.insert(std::make_pair<int,Request*>(conn,r));
			std::cout<<"insert null"<<std::endl;
			return true;
		}

	}
    locker.unlock();
    status_queue.post();
    return true;
}

void* ThreadsPool::worker(void* arg){
    ThreadsPool *tp = (ThreadsPool*)arg;
    tp->run();
    return tp;
}

void ThreadsPool::run(){
    while(is_work){
        status_queue.wait();
        locker.lock();
        if(conn_pool.empty()){
            locker.unlock();
            continue;
        }
		connection c = conn_pool.front();
		conn_pool.pop();
		if(c.request_or_response == 0){//request
			std::map<int,Request*>::iterator it;
			it = req_pool.find(c.conn);
			if(it!=req_pool.end()){//found
				Request *req = it->second;
				//parser request
			}
			else{
				continue;
			}
		}

        locker.unlock();
        //if(c){
        //    std::cout<<"ok"<<std::endl;
            //r->process();
        //}
    }
}

<|endoftext|>


<commit_before>#include "DirectionalLightShadowMapRenderer.h"
#include "ShadowManager.h"

#include "VertexShader.h"
#include "AutoBinder.hpp"

using namespace Rendering::Renderer::ShadowMap;
using namespace Rendering::Renderer;
using namespace Rendering::Manager;
using namespace Rendering::Shadow;
using namespace Rendering::Shader;
using namespace Rendering::Texture;
using namespace Rendering::Buffer;
using namespace Rendering::Geometry;
using namespace Rendering::RenderState;
using namespace Rendering::Material;
using namespace Device;
using namespace Core;

void DirectionalLightShadowMapRenderer::Render(DirectX& dx, Param&& param,
	const TempRenderQueue& renderQ, const MeshRenderer::Param& meshParam,
	const ConstBuffersType& shadowMapVPMatCB)
{
	float mapResolution	= static_cast<float>(param.atlasMapResolution);
	auto viewport		= Rect<float>(mapResolution * float(param.shadowIndex), 0.0f, mapResolution, mapResolution);

	dx.SetViewport(viewport);
	dx.SetDepthMapWithoutRenderTarget(param.shadowMap);
	dx.SetDepthStencilState(DepthState::Greater, 0);
	dx.SetPrimitiveTopology(PrimitiveTopology::TriangleList);
	dx.SetBlendState(BlendState::Opaque);

	param.shadowMap.Clear(dx, 0.0f, 0u);

	AutoBinderSampler<PixelShader> defaultSampler(dx, SamplerStateBindIndex::DefaultSamplerState, SamplerState::Linear);
	AutoBinderCB<VertexShader> only(dx, ConstBufferBindIndex::OnlyPassViewProjMat, shadowMapVPMatCB.viewProjMatCB);

	dx.SetRasterizerState(RasterizerState::CWDefault);
	MeshRenderer::RenderOpaqueMeshes(dx, meshParam, DefaultRenderType::Forward_OnlyDepth, renderQ.opaqueRenderQ, [](const Mesh* mesh){ }, [](){});

	dx.SetRasterizerState(RasterizerState::CWDisableCulling);
	MeshRenderer::RenderAlphaTestMeshes(dx, meshParam, DefaultRenderType::Forward_AlphaTestWithDiffuse, renderQ.alphaTestRenderQ,
		[&dx, &materialMgr = param.materialMgr](const Mesh* mesh)
		{
			auto material	= materialMgr.Find<PhysicallyBasedMaterial>(mesh->GetPBRMaterialID()); assert(material);

			auto diffuseMap	= material->GetTextures().Find(PhysicallyBasedMaterial::GetDiffuseMapKey()); assert(diffuseMap);
			PixelShader::BindShaderResourceView(dx, TextureBindIndex::DiffuseMap, diffuseMap->resource.GetShaderResourceView());

			auto opacityMap = material->GetTextures().Find(PhysicallyBasedMaterial::GetOpacityMapKey());
			if (opacityMap)
				PixelShader::BindShaderResourceView(dx, TextureBindIndex::OpacityMap, opacityMap->resource.GetShaderResourceView());
		},
		[&dx]()
		{
			PixelShader::UnBindShaderResourceView(dx, TextureBindIndex::OpacityMap);
			PixelShader::UnBindShaderResourceView(dx, TextureBindIndex::DiffuseMap);
		}
	);

	dx.SetRasterizerState(RasterizerState::CWDefault);
}
<commit_msg>DirectionalShadowMapRenderer - Render시 DefaultRenderType을 Forward_OnlyDepth와 Forward_AlphaTestWithDiffuse를 Forward_PCSSViewDepth, Forward_PCSSViewDepthAlphaTest로 변경<commit_after>#include "DirectionalLightShadowMapRenderer.h"
#include "ShadowManager.h"

#include "VertexShader.h"
#include "AutoBinder.hpp"

using namespace Rendering::Renderer::ShadowMap;
using namespace Rendering::Renderer;
using namespace Rendering::Manager;
using namespace Rendering::Shadow;
using namespace Rendering::Shader;
using namespace Rendering::Texture;
using namespace Rendering::Buffer;
using namespace Rendering::Geometry;
using namespace Rendering::RenderState;
using namespace Rendering::Material;
using namespace Device;
using namespace Core;

void DirectionalLightShadowMapRenderer::Render(DirectX& dx, Param&& param,
	const TempRenderQueue& renderQ, const MeshRenderer::Param& meshParam,
	const ConstBuffersType& shadowMapVPMatCB)
{
	float mapResolution	= static_cast<float>(param.atlasMapResolution);
	auto viewport		= Rect<float>(mapResolution * float(param.shadowIndex), 0.0f, mapResolution, mapResolution);

	dx.SetViewport(viewport);
	dx.SetRenderTarget(*param.shadowMap.GetViewDepthMap(), param.shadowMap);
	dx.SetDepthStencilState(DepthState::Greater, 0);
	dx.SetPrimitiveTopology(PrimitiveTopology::TriangleList);
	dx.SetBlendState(BlendState::Opaque);

	param.shadowMap.Clear(dx, 0.0f, 0u);

	AutoBinderSampler<PixelShader> defaultSampler(dx,	SamplerStateBindIndex::DefaultSamplerState,		SamplerState::Linear);
	AutoBinderCB<VertexShader> viewProjMatCB(dx,		ConstBufferBindIndex::OnlyPassViewProjMat,		shadowMapVPMatCB.viewProjMatCB);
	AutoBinderCB<VertexShader> viewMatCB(dx,			ConstBufferBindIndex::PCSSViewDepth,			shadowMapVPMatCB.viewMatCB);

	dx.SetRasterizerState(RasterizerState::CWDefault);
	MeshRenderer::RenderOpaqueMeshes(dx, meshParam, DefaultRenderType::Forward_PCSSViewDepth, renderQ.opaqueRenderQ, [](const Mesh* mesh){ }, [](){});

	dx.SetRasterizerState(RasterizerState::CWDisableCulling);
	MeshRenderer::RenderAlphaTestMeshes(dx, meshParam, DefaultRenderType::Forward_PCSSViewDepthAlphaTest, renderQ.alphaTestRenderQ,
		[&dx, &materialMgr = param.materialMgr](const Mesh* mesh)
		{
			auto material	= materialMgr.Find<PhysicallyBasedMaterial>(mesh->GetPBRMaterialID()); assert(material);

			auto diffuseMap	= material->GetTextures().Find(PhysicallyBasedMaterial::GetDiffuseMapKey()); assert(diffuseMap);
			PixelShader::BindShaderResourceView(dx, TextureBindIndex::DiffuseMap, diffuseMap->resource.GetShaderResourceView());

			auto opacityMap = material->GetTextures().Find(PhysicallyBasedMaterial::GetOpacityMapKey());
			if (opacityMap)
				PixelShader::BindShaderResourceView(dx, TextureBindIndex::OpacityMap, opacityMap->resource.GetShaderResourceView());
		},
		[&dx]()
		{
			PixelShader::UnBindShaderResourceView(dx, TextureBindIndex::OpacityMap);
			PixelShader::UnBindShaderResourceView(dx, TextureBindIndex::DiffuseMap);
		}
	);

	dx.SetRasterizerState(RasterizerState::CWDefault);
	dx.ReSetRenderTargets(1);
}
<|endoftext|>


<commit_before>#include "qmljsoutline.h"
#include "qmloutlinemodel.h"
#include "qmljsoutlinetreeview.h"

#include <coreplugin/icore.h>
#include <coreplugin/ifile.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QtCore/QDebug>
#include <QtCore/QSettings>
#include <QtGui/QAction>
#include <QtGui/QVBoxLayout>

using namespace QmlJS;

enum {
    debug = false
};

namespace QmlJSEditor {
namespace Internal {

QmlJSOutlineFilterModel::QmlJSOutlineFilterModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
    setDynamicSortFilter(true);
}

bool QmlJSOutlineFilterModel::filterAcceptsRow(int sourceRow,
                                               const QModelIndex &sourceParent) const
{
    if (m_filterBindings) {
        QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent);
        QVariant itemType = sourceIndex.data(QmlOutlineModel::ItemTypeRole);
        if (itemType == QmlOutlineModel::NonElementBindingType) {
            return false;
        }
    }
    return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}

QVariant QmlJSOutlineFilterModel::data(const QModelIndex &index, int role) const
{
    if (role == QmlOutlineModel::AnnotationRole) {
        // Don't show element id etc behind element if the property is also visible
        if (!filterBindings()
                && index.data(QmlOutlineModel::ItemTypeRole) == QmlOutlineModel::ElementType) {
            return QVariant();
        }
    }
    return QSortFilterProxyModel::data(index, role);
}

bool QmlJSOutlineFilterModel::filterBindings() const
{
    return m_filterBindings;
}

void QmlJSOutlineFilterModel::setFilterBindings(bool filterBindings)
{
    m_filterBindings = filterBindings;
    invalidateFilter();
}

QmlJSOutlineWidget::QmlJSOutlineWidget(QWidget *parent) :
    TextEditor::IOutlineWidget(parent),
    m_treeView(new QmlJSOutlineTreeView(this)),
    m_filterModel(new QmlJSOutlineFilterModel(this)),
    m_editor(0),
    m_enableCursorSync(true),
    m_blockCursorSync(false)
{
    m_filterModel->setFilterBindings(false);

    m_treeView->setModel(m_filterModel);

    QVBoxLayout *layout = new QVBoxLayout;

    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_treeView);

    m_showBindingsAction = new QAction(this);
    m_showBindingsAction->setText(tr("Show all bindings"));
    m_showBindingsAction->setCheckable(true);
    m_showBindingsAction->setChecked(true);
    connect(m_showBindingsAction, SIGNAL(toggled(bool)), this, SLOT(setShowBindings(bool)));

    setLayout(layout);
}

void QmlJSOutlineWidget::setEditor(QmlJSTextEditor *editor)
{
    m_editor = editor;

    m_filterModel->setSourceModel(m_editor->outlineModel());
    modelUpdated();

    connect(m_treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(updateSelectionInText(QItemSelection)));

    connect(m_editor, SIGNAL(outlineModelIndexChanged(QModelIndex)),
            this, SLOT(updateSelectionInTree(QModelIndex)));
    connect(m_editor->outlineModel(), SIGNAL(updated()),
            this, SLOT(modelUpdated()));
}

QList<QAction*> QmlJSOutlineWidget::filterMenuActions() const
{
    QList<QAction*> list;
    list.append(m_showBindingsAction);
    return list;
}

void QmlJSOutlineWidget::setCursorSynchronization(bool syncWithCursor)
{
    m_enableCursorSync = syncWithCursor;
    if (m_enableCursorSync)
        updateSelectionInTree(m_editor->outlineModelIndex());
}

void QmlJSOutlineWidget::restoreSettings(int position)
{
    QSettings *settings = Core::ICore::instance()->settings();
    bool showBindings = settings->value("QmlJSOutline."+QString::number(position)+".ShowBindings", true).toBool();
    m_showBindingsAction->setChecked(showBindings);
}

void QmlJSOutlineWidget::saveSettings(int position)
{
    QSettings *settings = Core::ICore::instance()->settings();
    settings->setValue("QmlJSOutline."+QString::number(position)+".ShowBindings",
                       m_showBindingsAction->isChecked());
}

void QmlJSOutlineWidget::modelUpdated()
{
    m_treeView->expandAll();
}

void QmlJSOutlineWidget::updateSelectionInTree(const QModelIndex &index)
{
    if (!syncCursor())
        return;

    m_blockCursorSync = true;
    m_treeView->selectionModel()->select(m_filterModel->mapFromSource(index), QItemSelectionModel::ClearAndSelect);
    m_treeView->scrollTo(m_filterModel->mapFromSource(index), QTreeView::PositionAtCenter);
    m_blockCursorSync = false;
}

void QmlJSOutlineWidget::updateSelectionInText(const QItemSelection &selection)
{
    if (!syncCursor())
        return;

    if (!selection.indexes().isEmpty()) {
        QModelIndex index = selection.indexes().first();
        QModelIndex sourceIndex = m_filterModel->mapToSource(index);

        AST::SourceLocation location = m_editor->outlineModel()->sourceLocation(sourceIndex);

        if (!location.isValid())
            return;

        Core::EditorManager *editorManager = Core::EditorManager::instance();
        editorManager->cutForwardNavigationHistory();
        editorManager->addCurrentPositionToNavigationHistory();

        QTextCursor textCursor = m_editor->textCursor();
        m_blockCursorSync = true;
        textCursor.setPosition(location.offset);
        m_editor->setTextCursor(textCursor);
        m_editor->centerCursor();
        m_blockCursorSync = false;
    }
}

void QmlJSOutlineWidget::setShowBindings(bool showBindings)
{
    m_filterModel->setFilterBindings(!showBindings);
    modelUpdated();
}

bool QmlJSOutlineWidget::syncCursor()
{
    return m_enableCursorSync && !m_blockCursorSync;
}

bool QmlJSOutlineWidgetFactory::supportsEditor(Core::IEditor *editor) const
{
    if (qobject_cast<QmlJSEditorEditable*>(editor))
        return true;
    return false;
}

TextEditor::IOutlineWidget *QmlJSOutlineWidgetFactory::createWidget(Core::IEditor *editor)
{
    QmlJSOutlineWidget *widget = new QmlJSOutlineWidget;

    QmlJSEditorEditable *qmlJSEditable = qobject_cast<QmlJSEditorEditable*>(editor);
    QmlJSTextEditor *qmlJSEditor = qobject_cast<QmlJSTextEditor*>(qmlJSEditable->widget());
    Q_ASSERT(qmlJSEditor);

    widget->setEditor(qmlJSEditor);

    return widget;
}

} // namespace Internal
} // namespace QmlJSEditor
<commit_msg>QmlOutline: Don't scroll to (horizontal) center when auto-selecting<commit_after>#include "qmljsoutline.h"
#include "qmloutlinemodel.h"
#include "qmljsoutlinetreeview.h"

#include <coreplugin/icore.h>
#include <coreplugin/ifile.h>
#include <coreplugin/editormanager/editormanager.h>

#include <QtCore/QDebug>
#include <QtCore/QSettings>
#include <QtGui/QAction>
#include <QtGui/QVBoxLayout>

using namespace QmlJS;

enum {
    debug = false
};

namespace QmlJSEditor {
namespace Internal {

QmlJSOutlineFilterModel::QmlJSOutlineFilterModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
    setDynamicSortFilter(true);
}

bool QmlJSOutlineFilterModel::filterAcceptsRow(int sourceRow,
                                               const QModelIndex &sourceParent) const
{
    if (m_filterBindings) {
        QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent);
        QVariant itemType = sourceIndex.data(QmlOutlineModel::ItemTypeRole);
        if (itemType == QmlOutlineModel::NonElementBindingType) {
            return false;
        }
    }
    return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}

QVariant QmlJSOutlineFilterModel::data(const QModelIndex &index, int role) const
{
    if (role == QmlOutlineModel::AnnotationRole) {
        // Don't show element id etc behind element if the property is also visible
        if (!filterBindings()
                && index.data(QmlOutlineModel::ItemTypeRole) == QmlOutlineModel::ElementType) {
            return QVariant();
        }
    }
    return QSortFilterProxyModel::data(index, role);
}

bool QmlJSOutlineFilterModel::filterBindings() const
{
    return m_filterBindings;
}

void QmlJSOutlineFilterModel::setFilterBindings(bool filterBindings)
{
    m_filterBindings = filterBindings;
    invalidateFilter();
}

QmlJSOutlineWidget::QmlJSOutlineWidget(QWidget *parent) :
    TextEditor::IOutlineWidget(parent),
    m_treeView(new QmlJSOutlineTreeView(this)),
    m_filterModel(new QmlJSOutlineFilterModel(this)),
    m_editor(0),
    m_enableCursorSync(true),
    m_blockCursorSync(false)
{
    m_filterModel->setFilterBindings(false);

    m_treeView->setModel(m_filterModel);

    QVBoxLayout *layout = new QVBoxLayout;

    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_treeView);

    m_showBindingsAction = new QAction(this);
    m_showBindingsAction->setText(tr("Show all bindings"));
    m_showBindingsAction->setCheckable(true);
    m_showBindingsAction->setChecked(true);
    connect(m_showBindingsAction, SIGNAL(toggled(bool)), this, SLOT(setShowBindings(bool)));

    setLayout(layout);
}

void QmlJSOutlineWidget::setEditor(QmlJSTextEditor *editor)
{
    m_editor = editor;

    m_filterModel->setSourceModel(m_editor->outlineModel());
    modelUpdated();

    connect(m_treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(updateSelectionInText(QItemSelection)));

    connect(m_editor, SIGNAL(outlineModelIndexChanged(QModelIndex)),
            this, SLOT(updateSelectionInTree(QModelIndex)));
    connect(m_editor->outlineModel(), SIGNAL(updated()),
            this, SLOT(modelUpdated()));
}

QList<QAction*> QmlJSOutlineWidget::filterMenuActions() const
{
    QList<QAction*> list;
    list.append(m_showBindingsAction);
    return list;
}

void QmlJSOutlineWidget::setCursorSynchronization(bool syncWithCursor)
{
    m_enableCursorSync = syncWithCursor;
    if (m_enableCursorSync)
        updateSelectionInTree(m_editor->outlineModelIndex());
}

void QmlJSOutlineWidget::restoreSettings(int position)
{
    QSettings *settings = Core::ICore::instance()->settings();
    bool showBindings = settings->value("QmlJSOutline."+QString::number(position)+".ShowBindings", true).toBool();
    m_showBindingsAction->setChecked(showBindings);
}

void QmlJSOutlineWidget::saveSettings(int position)
{
    QSettings *settings = Core::ICore::instance()->settings();
    settings->setValue("QmlJSOutline."+QString::number(position)+".ShowBindings",
                       m_showBindingsAction->isChecked());
}

void QmlJSOutlineWidget::modelUpdated()
{
    m_treeView->expandAll();
}

void QmlJSOutlineWidget::updateSelectionInTree(const QModelIndex &index)
{
    if (!syncCursor())
        return;

    m_blockCursorSync = true;
    m_treeView->selectionModel()->select(m_filterModel->mapFromSource(index), QItemSelectionModel::ClearAndSelect);
    m_treeView->scrollTo(m_filterModel->mapFromSource(index));
    m_blockCursorSync = false;
}

void QmlJSOutlineWidget::updateSelectionInText(const QItemSelection &selection)
{
    if (!syncCursor())
        return;

    if (!selection.indexes().isEmpty()) {
        QModelIndex index = selection.indexes().first();
        QModelIndex sourceIndex = m_filterModel->mapToSource(index);

        AST::SourceLocation location = m_editor->outlineModel()->sourceLocation(sourceIndex);

        if (!location.isValid())
            return;

        Core::EditorManager *editorManager = Core::EditorManager::instance();
        editorManager->cutForwardNavigationHistory();
        editorManager->addCurrentPositionToNavigationHistory();

        QTextCursor textCursor = m_editor->textCursor();
        m_blockCursorSync = true;
        textCursor.setPosition(location.offset);
        m_editor->setTextCursor(textCursor);
        m_editor->centerCursor();
        m_blockCursorSync = false;
    }
}

void QmlJSOutlineWidget::setShowBindings(bool showBindings)
{
    m_filterModel->setFilterBindings(!showBindings);
    modelUpdated();
}

bool QmlJSOutlineWidget::syncCursor()
{
    return m_enableCursorSync && !m_blockCursorSync;
}

bool QmlJSOutlineWidgetFactory::supportsEditor(Core::IEditor *editor) const
{
    if (qobject_cast<QmlJSEditorEditable*>(editor))
        return true;
    return false;
}

TextEditor::IOutlineWidget *QmlJSOutlineWidgetFactory::createWidget(Core::IEditor *editor)
{
    QmlJSOutlineWidget *widget = new QmlJSOutlineWidget;

    QmlJSEditorEditable *qmlJSEditable = qobject_cast<QmlJSEditorEditable*>(editor);
    QmlJSTextEditor *qmlJSEditor = qobject_cast<QmlJSTextEditor*>(qmlJSEditable->widget());
    Q_ASSERT(qmlJSEditor);

    widget->setEditor(qmlJSEditor);

    return widget;
}

} // namespace Internal
} // namespace QmlJSEditor
<|endoftext|>


<commit_before>#include <catch.hpp>

#include <vector>

#include "aux/Aux.hpp"
#include "CPU.hpp"

namespace {

SCENARIO("CPUs can load addresses to the address register I", "[memory]") {
  GIVEN("A CPU") {
    Aux::TestKit testKit;
    Core8::CPU& cpu = testKit.cpu;

    WHEN("the CPU executes a ANNN operation") {
      cpu.execute(0xA123);
      const auto address1 = cpu.getI();

      cpu.execute(0xAFFF);
      const auto address2 = cpu.getI();

      THEN("the address NNN is loaded into the address register I") {
        REQUIRE(0x123 == address1);
        REQUIRE(0xFFF == address2);
      }
    }
  }
}

SCENARIO("CPUs can load the registers into memory", "[memory]") {
  GIVEN("A CPU with initialized V and I registers") {
    const std::vector<Core8::Chip8::BYTE> bytes{
        0x10, 0x11, 0x12, 0x13, 0x24, 0x25, 0x26, 0x27,
        0x38, 0x39, 0x3A, 0x3B, 0x4C, 0x4D, 0x4E, 0x4F
    };

    Aux::TestKit testKit;
    Core8::CPU& cpu = testKit.cpu;
    cpu.setI(1024);

    for (std::size_t i = 0; i < 16; ++i) {
      cpu.writeRegister(static_cast<Core8::Chip8::Register>(i), bytes[i]);
    }

    WHEN("the CPU executes a FX55 operation") {
      cpu.execute(0xFF55);

      THEN("the registers from V0 to VX are stored in memory starting at address I") {
        const Core8::MMU& mmu = testKit.mmu;
        for (std::size_t i = 0; i < 0xF; ++i) {
          REQUIRE(mmu.readByte(1024 + i) == bytes[i]);
        }
      }
      AND_THEN("the value of I is incremented by X plus one") {
        REQUIRE(cpu.getI() == 1024 + 0xF + 1);
      }
    }
  }
}

SCENARIO("CPUs can load values from memory into registers", "[memory]") {
  GIVEN("A CPU with initialized memory and register I") {
    Aux::TestKit testKit;
    Core8::CPU& cpu = testKit.cpu;
    Core8::MMU& mmu = testKit.mmu;

    cpu.setI(1024);

    std::vector<Core8::Chip8::BYTE> bytes = { 0x10, 0x11, 0x12, 0x13, 0x24, 0x25 };
    Aux::ByteStream rom{bytes};
    mmu.load(rom, 1024);

    WHEN("the CPU executes a FX65 operation") {
      cpu.execute(0xF565);

      THEN("registers V0 to VX are filled with values from memory starting at address I") {
        for (std::size_t i = 0; i < 0x5; ++i) {
          REQUIRE(cpu.readRegister(static_cast<Core8::Chip8::Register>(i)) == bytes[i]);
        }
      }
      AND_THEN("the value of I is incremented by X plus one") {
        REQUIRE(cpu.getI() == 1024 + 0x5 + 1);
      }
    }
  }
}

SCENARIO("CPUs can add registers to the address register I", "[memory]") {
  GIVEN("A CPU with registers V and I initialized") {
    Aux::TestKit testKit;
    Core8::CPU& cpu = testKit.cpu;
    cpu.writeRegister(Core8::Chip8::Register::V0, 10);
    cpu.writeRegister(Core8::Chip8::Register::VE, 66);
    cpu.setI(512);

    WHEN("the CPU executes a FX1E operation") {
      cpu.execute(0xF01E);
      const auto address1 = cpu.getI();

      cpu.execute(0xFE1E);
      const auto address2 = cpu.getI();

      THEN("the value of register Vx is added to the address register I") {
        REQUIRE(522 == address1);
        REQUIRE(588 == address2);
      }
    }
  }
}

SCENARIO("CPUs can load to I the address of the sprite for the character in Vx", "[memory]") {
  GIVEN("A CPU with registers Vx initialized") {
    Aux::TestKit testKit;
    Core8::CPU& cpu = testKit.cpu;
    cpu.writeRegister(Core8::Chip8::Register::V0, 0x0);
    cpu.writeRegister(Core8::Chip8::Register::VE, 0xF);

    WHEN("the CPU executes a FX29 operation") {
      cpu.execute(0xF029);
      const auto address1 = cpu.getI();

      cpu.execute(0xFE29);
      const auto address2 = cpu.getI();

      THEN("register I is updated with the address of the character sprite of Vx value") {
        REQUIRE(address1 == 0);
        REQUIRE(address2 == 75);
      }
    }
  }
}

} // unnamed namespace<commit_msg>Update memory tests<commit_after>#include <algorithm>
#include <vector>

#include <catch.hpp>

#include "aux/Aux.hpp"
#include "CPU.hpp"

namespace {

struct CpuFixture {
  Aux::TestKit testKit;
  Core8::MMU& mmu = testKit.mmu;
  Core8::CPU& cpu = testKit.cpu;
};

SCENARIO_METHOD(
    CpuFixture,
    "CPU sets I to the address NNN using opcode ANNN",
    "[memory]"
) {
  GIVEN("A CPU") {
    WHEN("the CPU executes a ANNN operation") {
      cpu.execute(0xA123);
      const auto address1 = cpu.getI();
      cpu.execute(0xAFFF);
      const auto address2 = cpu.getI();

      THEN("the address NNN is loaded into the address register I") {
        REQUIRE(0x123 == address1);
        REQUIRE(0xFFF == address2);
      }
    }
  }
}

SCENARIO_METHOD(
    CpuFixture,
    "CPU stores registers V0 to VX in memory starting at address I "
        "using the FX55 opcode",
    "[memory]"
) {
  GIVEN("A CPU with initialized V and I registers") {
    const Core8::Chip8::WORD address{1024};
    cpu.setI(address);

    const std::vector<Core8::Chip8::BYTE> bytes{
        0x10, 0x11, 0x12, 0x13, 0x24, 0x25, 0x26, 0x27,
        0x38, 0x39, 0x3A, 0x3B, 0x4C, 0x4D, 0x4E, 0x4F
    };
    cpu.loadToRegisters(bytes);

    WHEN("the CPU executes a FX55 opcode") {
      cpu.execute(0xFF55);

      THEN("the registers from V0 to VX are stored in memory") {
        for (auto i = 0u; i < 0xFu; ++i) {
          const auto r = cpu.readRegister(static_cast<Core8::Chip8::Register>(i));
          const auto m = mmu.readByte(address + i);
          REQUIRE(r == m);
        }
      }
      AND_THEN("the value of I is incremented by X plus one") {
        REQUIRE(cpu.getI() == 1024 + 0xF + 1);
      }
    }
  }
}

SCENARIO_METHOD(
    CpuFixture,
    "CPU fills registers V0 to VX in memory starting at address I "
        "using the FX65 opcode",
    "[memory]"
) {
  GIVEN("A CPU with initialized memory and register I") {
    const Core8::Chip8::WORD address{1024};
    cpu.setI(address);

    const std::vector<Core8::Chip8::BYTE> bytes = { 0x10, 0x11, 0x12,
                                                    0x13, 0x24, 0x25 };
    mmu.load(bytes, address);

    WHEN("the CPU executes a FX65 opcode") {
      cpu.execute(0xF565);

      THEN("registers V0 to VX are filled with values from memory") {
        for (auto i = 0u; i < 0x5; ++i) {
          const auto r = cpu.readRegister(static_cast<Core8::Chip8::Register>(i));
          const auto m = mmu.readByte(address + i);
          REQUIRE(r == m);
        }
      }
      AND_THEN("the value of I is incremented by X plus one") {
        REQUIRE(cpu.getI() == 1024 + 0x5 + 1);
      }
    }
  }
}

SCENARIO_METHOD(
    CpuFixture,
    "CPU adds register X to register I using FX1E opcode",
    "[memory]"
) {
  GIVEN("A CPU with registers V and I initialized") {
    cpu.writeRegister(Core8::Chip8::Register::V0, 10);
    cpu.writeRegister(Core8::Chip8::Register::VE, 66);
    cpu.setI(512);

    WHEN("the CPU executes a FX1E opcode") {
      cpu.execute(0xF01E);
      const auto address1 = cpu.getI();

      cpu.execute(0xFE1E);
      const auto address2 = cpu.getI();

      THEN("the value of register VX is added to register I") {
        REQUIRE(522 == address1);
        REQUIRE(588 == address2);
      }
    }
  }
}

SCENARIO_METHOD(
    CpuFixture,
    "CPU sets I to the location of the sprite for the character in VX "
        "using FX29 opcode",
    "[memory]"
) {
  GIVEN("A CPU with initialized registers") {
    cpu.writeRegister(Core8::Chip8::Register::V0, 0x0);
    cpu.writeRegister(Core8::Chip8::Register::VE, 0xF);

    WHEN("the CPU executes a FX29 opcode") {
      cpu.execute(0xF029);
      const auto address1 = cpu.getI();

      cpu.execute(0xFE29);
      const auto address2 = cpu.getI();

      THEN("register I is updated to the address of the character sprite of VX") {
        REQUIRE(address1 == 0);
        REQUIRE(address2 == 75);
      }
    }
  }
}

} // namespace<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
typedef enum {k1,k2} enumName;
enumName var
// CHECK: (enumName) (::k1) : (int) 0
// End PR #98146
<commit_msg>Correct comment.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
// End PR #98146
typedef enum {k1,k2} enumName;
enumName var
// CHECK: (enumName) (::k1) : (int) 0
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2006 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author makes no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header:

#include <loki/ScopeGuard.h>
#include <vector>
#include <string>
#include <iostream>

void Decrement(int& x)
{
	--x;
}

struct UserDatabase
{
    void AddFriend(const std::string&, const std::string&)
    {
        throw 55;
    }
};

class User
{
public:
    User(UserDatabase* db) : fCount(0), pDB_(db)
	{}

    std::string GetName();

    void AddFriend(User& newFriend);
    void AddFriendGuarded(User& newFriend);

    size_t countFriends();

    int fCount;

private:
    typedef std::vector<User*> UserCont;
    UserCont friends_;
    UserDatabase* pDB_;
};

std::string User::GetName()
{
    return "A name";
}

size_t User::countFriends()
{
    return friends_.size();
}

void User::AddFriend(User& newFriend)
{
    friends_.push_back(&newFriend);
    fCount++;
    pDB_->AddFriend(GetName(), newFriend.GetName());
}

void User::AddFriendGuarded(User& newFriend)
{
    friends_.push_back(&newFriend);
    Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);

    fCount++;
    Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));
    (void) guardRef;

    pDB_->AddFriend(GetName(), newFriend.GetName());
    guard.Dismiss();
}

int main()
{
    UserDatabase db;

    User u1(&db);
    User u2(&db);

    try{ u1.AddFriend(u2); }
    catch (...){}
    std::cout << "u1 countFriends: " << u1.countFriends() << "\n";
	std::cout << "u1 fCount      : " << u1.fCount << "\n";

    try{ u2.AddFriendGuarded(u1); }
    catch (...){}
    std::cout << "u2 countFriends: " << u2.countFriends() << "\n";
	std::cout << "u2 fCount      : " << u2.fCount << "\n";

#if defined(__BORLANDC__) || defined(_MSC_VER)
    system("PAUSE");
#endif

}
<commit_msg>use RefToValue.h, add dismiss for the ref guard<commit_after>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2006 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author makes no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header:

#include <loki/ScopeGuard.h>
#include <loki/RefToValue.h>

#include <vector>
#include <string>
#include <iostream>

void Decrement(int& x)
{
    --x;
}

struct UserDatabase
{
    void AddFriend(const std::string&, const std::string&)
    {
        throw 55;
    }
};

class User
{
public:
    User(UserDatabase* db) : fCount(0), pDB_(db)
    {}

    std::string GetName();

    void AddFriend(User& newFriend);
    void AddFriendGuarded(User& newFriend);

    size_t countFriends();

    int fCount;

private:
    typedef std::vector<User*> UserCont;
    UserCont friends_;
    UserDatabase* pDB_;
};

std::string User::GetName()
{
    return "A name";
}

size_t User::countFriends()
{
    return friends_.size();
}

void User::AddFriend(User& newFriend)
{
    friends_.push_back(&newFriend);
    fCount++;
    pDB_->AddFriend(GetName(), newFriend.GetName());
}

void User::AddFriendGuarded(User& newFriend)
{
    friends_.push_back(&newFriend);
    Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);

    fCount++;
    Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));

    pDB_->AddFriend(GetName(), newFriend.GetName());
    guard.Dismiss();
    guardRef.Dismiss();
}

int main()
{
    UserDatabase db;

    User u1(&db);
    User u2(&db);

    try{ u1.AddFriend(u2); }
    catch (...){}
    std::cout << "u1 countFriends: " << u1.countFriends() << "\n";
    std::cout << "u1 fCount      : " << u1.fCount << "\n";

    try{ u2.AddFriendGuarded(u1); }
    catch (...){}
    std::cout << "u2 countFriends: " << u2.countFriends() << "\n";
    std::cout << "u2 fCount      : " << u2.fCount << "\n";

#if defined(__BORLANDC__) || defined(_MSC_VER)
    system("PAUSE");
#endif

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

// This is an implementation of the x86-64 ABI as described in 'System V
// Application Binary Interface, AMD64 Architecture Processor Supplement'
// (http://www.x86-64.org/documentation/abi-0.95.pdf)
//
// The code in this file is a modification of src/x86/ffi64.c from libffi
// (http://sources.redhat.com/libffi/) which is under the following license:

/* -----------------------------------------------------------------------
   ffi.c - Copyright (c) 2002  Bo Thorsen <bo@suse.de>

   x86-64 Foreign Function Interface

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   ``Software''), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR
   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
   OTHER DEALINGS IN THE SOFTWARE.
   ----------------------------------------------------------------------- */

#include "sal/config.h"

#include "abi.hxx"

using namespace x86_64;

/* Register class used for passing given 64bit part of the argument.
   These represent classes as documented by the PS ABI, with the exception
   of SSESF, SSEDF classes, that are basically SSE class, just gcc will
   use SF or DFmode move instead of DImode to avoid reformating penalties.

   Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves
   whenever possible (upper half does contain padding).
 */
enum x86_64_reg_class
{
    X86_64_NO_CLASS,
    X86_64_INTEGER_CLASS,
    X86_64_INTEGERSI_CLASS,
    X86_64_SSE_CLASS,
    X86_64_SSESF_CLASS,
    X86_64_SSEDF_CLASS,
    X86_64_SSEUP_CLASS,
    X86_64_X87_CLASS,
    X86_64_X87UP_CLASS,
    X86_64_MEMORY_CLASS
};

#define MAX_CLASSES 4

/* x86-64 register passing implementation.  See x86-64 ABI for details.  Goal
   of this code is to classify each 8bytes of incoming argument by the register
   class and assign registers accordingly.  */

/* Return the union class of CLASS1 and CLASS2.
   See the x86-64 PS ABI for details.  */

static enum x86_64_reg_class
merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2)
    throw ()
{
    /* Rule #1: If both classes are equal, this is the resulting class.  */
    if (class1 == class2)
        return class1;

    /* Rule #2: If one of the classes is NO_CLASS, the resulting class is
       the other class.  */
    if (class1 == X86_64_NO_CLASS)
        return class2;
    if (class2 == X86_64_NO_CLASS)
        return class1;

    /* Rule #3: If one of the classes is MEMORY, the result is MEMORY.  */
    if (class1 == X86_64_MEMORY_CLASS || class2 == X86_64_MEMORY_CLASS)
        return X86_64_MEMORY_CLASS;

    /* Rule #4: If one of the classes is INTEGER, the result is INTEGER.  */
    if ((class1 == X86_64_INTEGERSI_CLASS && class2 == X86_64_SSESF_CLASS)
            || (class2 == X86_64_INTEGERSI_CLASS && class1 == X86_64_SSESF_CLASS))
        return X86_64_INTEGERSI_CLASS;
    if (class1 == X86_64_INTEGER_CLASS || class1 == X86_64_INTEGERSI_CLASS
            || class2 == X86_64_INTEGER_CLASS || class2 == X86_64_INTEGERSI_CLASS)
        return X86_64_INTEGER_CLASS;

    /* Rule #5: If one of the classes is X87 or X87UP class, MEMORY is used.  */
    if (class1 == X86_64_X87_CLASS || class1 == X86_64_X87UP_CLASS
            || class2 == X86_64_X87_CLASS || class2 == X86_64_X87UP_CLASS)
        return X86_64_MEMORY_CLASS;

    /* Rule #6: Otherwise class SSE is used.  */
    return X86_64_SSE_CLASS;
}

/* Classify the argument of type TYPE and mode MODE.
   CLASSES will be filled by the register class used to pass each word
   of the operand.  The number of words is returned.  In case the parameter
   should be passed in memory, 0 is returned. As a special case for zero
   sized containers, classes[0] will be NO_CLASS and 1 is returned.

   See the x86-64 PS ABI for details.
*/
static int
classify_argument( typelib_TypeDescriptionReference *pTypeRef, enum x86_64_reg_class classes[], int byteOffset ) throw ()
{
    switch ( pTypeRef->eTypeClass )
    {
        case typelib_TypeClass_VOID:
            classes[0] = X86_64_NO_CLASS;
            return 1;
        case typelib_TypeClass_CHAR:
        case typelib_TypeClass_BOOLEAN:
        case typelib_TypeClass_BYTE:
        case typelib_TypeClass_SHORT:
        case typelib_TypeClass_UNSIGNED_SHORT:
        case typelib_TypeClass_LONG:
        case typelib_TypeClass_UNSIGNED_LONG:
        case typelib_TypeClass_HYPER:
        case typelib_TypeClass_UNSIGNED_HYPER:
        case typelib_TypeClass_ENUM:
            if ( ( byteOffset % 8 + pTypeRef->pType->nSize ) <= 4 )
                classes[0] = X86_64_INTEGERSI_CLASS;
            else
                classes[0] = X86_64_INTEGER_CLASS;
            return 1;
        case typelib_TypeClass_FLOAT:
            if ( ( byteOffset % 8 ) == 0 )
                classes[0] = X86_64_SSESF_CLASS;
            else
                classes[0] = X86_64_SSE_CLASS;
            return 1;
        case typelib_TypeClass_DOUBLE:
            classes[0] = X86_64_SSEDF_CLASS;
            return 1;
        /*case LONGDOUBLE:
            classes[0] = X86_64_X87_CLASS;
            classes[1] = X86_64_X87UP_CLASS;
            return 2;*/
        case typelib_TypeClass_STRING:
        case typelib_TypeClass_TYPE:
        case typelib_TypeClass_ANY:
        case typelib_TypeClass_TYPEDEF:
        case typelib_TypeClass_UNION:
        case typelib_TypeClass_SEQUENCE:
        case typelib_TypeClass_ARRAY:
        case typelib_TypeClass_INTERFACE:
            return 0;
        case typelib_TypeClass_STRUCT:
        case typelib_TypeClass_EXCEPTION:
            {
                typelib_TypeDescription * pTypeDescr = 0;
                TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef );

                const int UNITS_PER_WORD = 8;
                int words = ( pTypeDescr->nSize + UNITS_PER_WORD - 1 ) / UNITS_PER_WORD;
                enum x86_64_reg_class subclasses[MAX_CLASSES];

                /* If the struct is larger than 16 bytes, pass it on the stack.  */
                if ( pTypeDescr->nSize > 16 )
                {
                    TYPELIB_DANGER_RELEASE( pTypeDescr );
                    return 0;
                }

                for ( int i = 0; i < words; i++ )
                    classes[i] = X86_64_NO_CLASS;

                const typelib_CompoundTypeDescription *pStruct = reinterpret_cast<const typelib_CompoundTypeDescription*>( pTypeDescr );

                /* Merge the fields of structure.  */
                for ( sal_Int32 nMember = 0; nMember < pStruct->nMembers; ++nMember )
                {
                    typelib_TypeDescriptionReference *pTypeInStruct = pStruct->ppTypeRefs[ nMember ];
                    int offset = byteOffset + pStruct->pMemberOffsets[ nMember ];

                    int num = classify_argument( pTypeInStruct, subclasses, offset );

                    if ( num == 0 )
                    {
                        TYPELIB_DANGER_RELEASE( pTypeDescr );
                        return 0;
                    }

                    for ( int i = 0; i < num; i++ )
                    {
                        int pos = offset / 8;
                        classes[i + pos] = merge_classes( subclasses[i], classes[i + pos] );
                    }
                }

                TYPELIB_DANGER_RELEASE( pTypeDescr );

                /* Final merger cleanup.  */
                for ( int i = 0; i < words; i++ )
                {
                    /* If one class is MEMORY, everything should be passed in
                       memory.  */
                    if ( classes[i] == X86_64_MEMORY_CLASS )
                        return 0;

                    /* The X86_64_SSEUP_CLASS should be always preceded by
                       X86_64_SSE_CLASS.  */
                    if ( classes[i] == X86_64_SSEUP_CLASS
                            && ( i == 0 || classes[i - 1] != X86_64_SSE_CLASS ) )
                        classes[i] = X86_64_SSE_CLASS;

                    /*  X86_64_X87UP_CLASS should be preceded by X86_64_X87_CLASS.  */
                    if ( classes[i] == X86_64_X87UP_CLASS
                            && ( i == 0 || classes[i - 1] != X86_64_X87_CLASS ) )
                        classes[i] = X86_64_SSE_CLASS;
                }
                return words;
            }

        default:
#if OSL_DEBUG_LEVEL > 1
            OSL_TRACE( "Unhandled case: pType->eTypeClass == %d", pTypeRef->eTypeClass );
#endif
            OSL_ASSERT(0);
    }
    return 0; /* Never reached.  */
}

/* Examine the argument and return set number of register required in each
   class.  Return 0 iff parameter should be passed in memory.  */
bool x86_64::examine_argument( typelib_TypeDescriptionReference *pTypeRef, bool bInReturn, int &nUsedGPR, int &nUsedSSE ) throw ()
{
    enum x86_64_reg_class classes[MAX_CLASSES];
    int n;

    n = classify_argument( pTypeRef, classes, 0 );

    if ( n == 0 )
        return false;

    nUsedGPR = 0;
    nUsedSSE = 0;
    for ( n--; n >= 0; n-- )
        switch ( classes[n] )
        {
            case X86_64_INTEGER_CLASS:
            case X86_64_INTEGERSI_CLASS:
                nUsedGPR++;
                break;
            case X86_64_SSE_CLASS:
            case X86_64_SSESF_CLASS:
            case X86_64_SSEDF_CLASS:
                nUsedSSE++;
                break;
            case X86_64_NO_CLASS:
            case X86_64_SSEUP_CLASS:
                break;
            case X86_64_X87_CLASS:
            case X86_64_X87UP_CLASS:
                if ( !bInReturn )
                    return false;
                break;
            default:
#if OSL_DEBUG_LEVEL > 1
            OSL_TRACE( "Unhandled case: classes[n] == %d", classes[n] );
#endif
            OSL_ASSERT(0);
        }
    return true;
}

bool x86_64::return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef ) throw ()
{
    int g, s;

    return examine_argument( pTypeRef, true, g, s ) == 0;
}

void x86_64::fill_struct( typelib_TypeDescriptionReference *pTypeRef, const sal_uInt64 *pGPR, const double *pSSE, void *pStruct ) throw ()
{
    enum x86_64_reg_class classes[MAX_CLASSES];
    int n;

    n = classify_argument( pTypeRef, classes, 0 );

    sal_uInt64 *pStructAlign = reinterpret_cast<sal_uInt64 *>( pStruct );
    for ( n--; n >= 0; n-- )
        switch ( classes[n] )
        {
            case X86_64_INTEGER_CLASS:
            case X86_64_INTEGERSI_CLASS:
                *pStructAlign++ = *pGPR++;
                break;
            case X86_64_SSE_CLASS:
            case X86_64_SSESF_CLASS:
            case X86_64_SSEDF_CLASS:
                *pStructAlign++ = *reinterpret_cast<const sal_uInt64 *>( pSSE++ );
                break;
            default:
                break;
        }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Use proper bool operations<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

// This is an implementation of the x86-64 ABI as described in 'System V
// Application Binary Interface, AMD64 Architecture Processor Supplement'
// (http://www.x86-64.org/documentation/abi-0.95.pdf)
//
// The code in this file is a modification of src/x86/ffi64.c from libffi
// (http://sources.redhat.com/libffi/) which is under the following license:

/* -----------------------------------------------------------------------
   ffi.c - Copyright (c) 2002  Bo Thorsen <bo@suse.de>

   x86-64 Foreign Function Interface

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   ``Software''), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR
   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
   OTHER DEALINGS IN THE SOFTWARE.
   ----------------------------------------------------------------------- */

#include "sal/config.h"

#include "abi.hxx"

using namespace x86_64;

/* Register class used for passing given 64bit part of the argument.
   These represent classes as documented by the PS ABI, with the exception
   of SSESF, SSEDF classes, that are basically SSE class, just gcc will
   use SF or DFmode move instead of DImode to avoid reformating penalties.

   Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves
   whenever possible (upper half does contain padding).
 */
enum x86_64_reg_class
{
    X86_64_NO_CLASS,
    X86_64_INTEGER_CLASS,
    X86_64_INTEGERSI_CLASS,
    X86_64_SSE_CLASS,
    X86_64_SSESF_CLASS,
    X86_64_SSEDF_CLASS,
    X86_64_SSEUP_CLASS,
    X86_64_X87_CLASS,
    X86_64_X87UP_CLASS,
    X86_64_MEMORY_CLASS
};

#define MAX_CLASSES 4

/* x86-64 register passing implementation.  See x86-64 ABI for details.  Goal
   of this code is to classify each 8bytes of incoming argument by the register
   class and assign registers accordingly.  */

/* Return the union class of CLASS1 and CLASS2.
   See the x86-64 PS ABI for details.  */

static enum x86_64_reg_class
merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2)
    throw ()
{
    /* Rule #1: If both classes are equal, this is the resulting class.  */
    if (class1 == class2)
        return class1;

    /* Rule #2: If one of the classes is NO_CLASS, the resulting class is
       the other class.  */
    if (class1 == X86_64_NO_CLASS)
        return class2;
    if (class2 == X86_64_NO_CLASS)
        return class1;

    /* Rule #3: If one of the classes is MEMORY, the result is MEMORY.  */
    if (class1 == X86_64_MEMORY_CLASS || class2 == X86_64_MEMORY_CLASS)
        return X86_64_MEMORY_CLASS;

    /* Rule #4: If one of the classes is INTEGER, the result is INTEGER.  */
    if ((class1 == X86_64_INTEGERSI_CLASS && class2 == X86_64_SSESF_CLASS)
            || (class2 == X86_64_INTEGERSI_CLASS && class1 == X86_64_SSESF_CLASS))
        return X86_64_INTEGERSI_CLASS;
    if (class1 == X86_64_INTEGER_CLASS || class1 == X86_64_INTEGERSI_CLASS
            || class2 == X86_64_INTEGER_CLASS || class2 == X86_64_INTEGERSI_CLASS)
        return X86_64_INTEGER_CLASS;

    /* Rule #5: If one of the classes is X87 or X87UP class, MEMORY is used.  */
    if (class1 == X86_64_X87_CLASS || class1 == X86_64_X87UP_CLASS
            || class2 == X86_64_X87_CLASS || class2 == X86_64_X87UP_CLASS)
        return X86_64_MEMORY_CLASS;

    /* Rule #6: Otherwise class SSE is used.  */
    return X86_64_SSE_CLASS;
}

/* Classify the argument of type TYPE and mode MODE.
   CLASSES will be filled by the register class used to pass each word
   of the operand.  The number of words is returned.  In case the parameter
   should be passed in memory, 0 is returned. As a special case for zero
   sized containers, classes[0] will be NO_CLASS and 1 is returned.

   See the x86-64 PS ABI for details.
*/
static int
classify_argument( typelib_TypeDescriptionReference *pTypeRef, enum x86_64_reg_class classes[], int byteOffset ) throw ()
{
    switch ( pTypeRef->eTypeClass )
    {
        case typelib_TypeClass_VOID:
            classes[0] = X86_64_NO_CLASS;
            return 1;
        case typelib_TypeClass_CHAR:
        case typelib_TypeClass_BOOLEAN:
        case typelib_TypeClass_BYTE:
        case typelib_TypeClass_SHORT:
        case typelib_TypeClass_UNSIGNED_SHORT:
        case typelib_TypeClass_LONG:
        case typelib_TypeClass_UNSIGNED_LONG:
        case typelib_TypeClass_HYPER:
        case typelib_TypeClass_UNSIGNED_HYPER:
        case typelib_TypeClass_ENUM:
            if ( ( byteOffset % 8 + pTypeRef->pType->nSize ) <= 4 )
                classes[0] = X86_64_INTEGERSI_CLASS;
            else
                classes[0] = X86_64_INTEGER_CLASS;
            return 1;
        case typelib_TypeClass_FLOAT:
            if ( ( byteOffset % 8 ) == 0 )
                classes[0] = X86_64_SSESF_CLASS;
            else
                classes[0] = X86_64_SSE_CLASS;
            return 1;
        case typelib_TypeClass_DOUBLE:
            classes[0] = X86_64_SSEDF_CLASS;
            return 1;
        /*case LONGDOUBLE:
            classes[0] = X86_64_X87_CLASS;
            classes[1] = X86_64_X87UP_CLASS;
            return 2;*/
        case typelib_TypeClass_STRING:
        case typelib_TypeClass_TYPE:
        case typelib_TypeClass_ANY:
        case typelib_TypeClass_TYPEDEF:
        case typelib_TypeClass_UNION:
        case typelib_TypeClass_SEQUENCE:
        case typelib_TypeClass_ARRAY:
        case typelib_TypeClass_INTERFACE:
            return 0;
        case typelib_TypeClass_STRUCT:
        case typelib_TypeClass_EXCEPTION:
            {
                typelib_TypeDescription * pTypeDescr = 0;
                TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef );

                const int UNITS_PER_WORD = 8;
                int words = ( pTypeDescr->nSize + UNITS_PER_WORD - 1 ) / UNITS_PER_WORD;
                enum x86_64_reg_class subclasses[MAX_CLASSES];

                /* If the struct is larger than 16 bytes, pass it on the stack.  */
                if ( pTypeDescr->nSize > 16 )
                {
                    TYPELIB_DANGER_RELEASE( pTypeDescr );
                    return 0;
                }

                for ( int i = 0; i < words; i++ )
                    classes[i] = X86_64_NO_CLASS;

                const typelib_CompoundTypeDescription *pStruct = reinterpret_cast<const typelib_CompoundTypeDescription*>( pTypeDescr );

                /* Merge the fields of structure.  */
                for ( sal_Int32 nMember = 0; nMember < pStruct->nMembers; ++nMember )
                {
                    typelib_TypeDescriptionReference *pTypeInStruct = pStruct->ppTypeRefs[ nMember ];
                    int offset = byteOffset + pStruct->pMemberOffsets[ nMember ];

                    int num = classify_argument( pTypeInStruct, subclasses, offset );

                    if ( num == 0 )
                    {
                        TYPELIB_DANGER_RELEASE( pTypeDescr );
                        return 0;
                    }

                    for ( int i = 0; i < num; i++ )
                    {
                        int pos = offset / 8;
                        classes[i + pos] = merge_classes( subclasses[i], classes[i + pos] );
                    }
                }

                TYPELIB_DANGER_RELEASE( pTypeDescr );

                /* Final merger cleanup.  */
                for ( int i = 0; i < words; i++ )
                {
                    /* If one class is MEMORY, everything should be passed in
                       memory.  */
                    if ( classes[i] == X86_64_MEMORY_CLASS )
                        return 0;

                    /* The X86_64_SSEUP_CLASS should be always preceded by
                       X86_64_SSE_CLASS.  */
                    if ( classes[i] == X86_64_SSEUP_CLASS
                            && ( i == 0 || classes[i - 1] != X86_64_SSE_CLASS ) )
                        classes[i] = X86_64_SSE_CLASS;

                    /*  X86_64_X87UP_CLASS should be preceded by X86_64_X87_CLASS.  */
                    if ( classes[i] == X86_64_X87UP_CLASS
                            && ( i == 0 || classes[i - 1] != X86_64_X87_CLASS ) )
                        classes[i] = X86_64_SSE_CLASS;
                }
                return words;
            }

        default:
#if OSL_DEBUG_LEVEL > 1
            OSL_TRACE( "Unhandled case: pType->eTypeClass == %d", pTypeRef->eTypeClass );
#endif
            OSL_ASSERT(0);
    }
    return 0; /* Never reached.  */
}

/* Examine the argument and return set number of register required in each
   class.  Return 0 iff parameter should be passed in memory.  */
bool x86_64::examine_argument( typelib_TypeDescriptionReference *pTypeRef, bool bInReturn, int &nUsedGPR, int &nUsedSSE ) throw ()
{
    enum x86_64_reg_class classes[MAX_CLASSES];
    int n;

    n = classify_argument( pTypeRef, classes, 0 );

    if ( n == 0 )
        return false;

    nUsedGPR = 0;
    nUsedSSE = 0;
    for ( n--; n >= 0; n-- )
        switch ( classes[n] )
        {
            case X86_64_INTEGER_CLASS:
            case X86_64_INTEGERSI_CLASS:
                nUsedGPR++;
                break;
            case X86_64_SSE_CLASS:
            case X86_64_SSESF_CLASS:
            case X86_64_SSEDF_CLASS:
                nUsedSSE++;
                break;
            case X86_64_NO_CLASS:
            case X86_64_SSEUP_CLASS:
                break;
            case X86_64_X87_CLASS:
            case X86_64_X87UP_CLASS:
                if ( !bInReturn )
                    return false;
                break;
            default:
#if OSL_DEBUG_LEVEL > 1
            OSL_TRACE( "Unhandled case: classes[n] == %d", classes[n] );
#endif
            OSL_ASSERT(0);
        }
    return true;
}

bool x86_64::return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef ) throw ()
{
    int g, s;

    return !examine_argument( pTypeRef, true, g, s );
}

void x86_64::fill_struct( typelib_TypeDescriptionReference *pTypeRef, const sal_uInt64 *pGPR, const double *pSSE, void *pStruct ) throw ()
{
    enum x86_64_reg_class classes[MAX_CLASSES];
    int n;

    n = classify_argument( pTypeRef, classes, 0 );

    sal_uInt64 *pStructAlign = reinterpret_cast<sal_uInt64 *>( pStruct );
    for ( n--; n >= 0; n-- )
        switch ( classes[n] )
        {
            case X86_64_INTEGER_CLASS:
            case X86_64_INTEGERSI_CLASS:
                *pStructAlign++ = *pGPR++;
                break;
            case X86_64_SSE_CLASS:
            case X86_64_SSESF_CLASS:
            case X86_64_SSEDF_CLASS:
                *pStructAlign++ = *reinterpret_cast<const sal_uInt64 *>( pSSE++ );
                break;
            default:
                break;
        }
}

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


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: msci.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 22:33:13 $
 *
 *  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
 *
 ************************************************************************/

#include <windows.h>
#include "rtl/ustring.hxx"

class type_info;
typedef struct _uno_Any uno_Any;
typedef struct _uno_Mapping uno_Mapping;

namespace CPPU_CURRENT_NAMESPACE
{

const long MSVC_ExceptionCode = 0xe06d7363;
const long MSVC_magic_number = 0x19930520L;

//==============================================================================
type_info * msci_getRTTI( ::rtl::OUString const & rUNOname );

//==============================================================================
int msci_filterCppException(
    EXCEPTION_POINTERS * pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno );

//==============================================================================
void msci_raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

}

<commit_msg>INTEGRATION: CWS warnings01 (1.5.4); FILE MERGED 2006/02/28 15:00:33 sb 1.5.4.1: #i53898# Made code waring-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: msci.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 23:45:05 $
 *
 *  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
 *
 ************************************************************************/

#pragma warning(push, 1)
#include <windows.h>
#pragma warning(pop)

#include "rtl/ustring.hxx"

class type_info;
typedef struct _uno_Any uno_Any;
typedef struct _uno_Mapping uno_Mapping;

namespace CPPU_CURRENT_NAMESPACE
{

const DWORD MSVC_ExceptionCode = 0xe06d7363;
const long MSVC_magic_number = 0x19930520L;

//==============================================================================
type_info * msci_getRTTI( ::rtl::OUString const & rUNOname );

//==============================================================================
int msci_filterCppException(
    EXCEPTION_POINTERS * pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno );

//==============================================================================
void msci_raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

}

<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeTextureSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    float TextureSource::getVolumeGridValue(size_t x, size_t y, size_t z) const
    {
        x = x >= mWidth ? mWidth - 1 : x;
        y = y >= mHeight ? mHeight - 1 : y;
        z = z >= mDepth ? mDepth - 1 : z;
        return mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x];
    }

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

    void TextureSource::setVolumeGridValue(int x, int y, int z, float value)
    {
        mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x] = value;
    }

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

    TextureSource::TextureSource(const String &volumeTextureName, const Real worldWidth, const Real worldHeight, const Real worldDepth, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) :
        GridSource(trilinearValue, trilinearGradient, sobelGradient)
    {

        Timer t;
        //we to load then read a 3d texture. we cannot load it directly as that will mean we might
        //not be able to read it. we need to change it's usage from dynamic (default) to a readable static.
        Ogre::ResourceManager::ResourceCreateOrRetrieveResult res =
            TextureManager::getSingleton().createOrRetrieve(volumeTextureName,
            Ogre::ResourceGroupManager::getSingleton().getWorldResourceGroupName(),
            false, 0, 0, Ogre::TEX_TYPE_3D, 0);
        Ogre::TexturePtr tex = static_pointer_cast<Texture>(res.first);
        tex->setUsage(TU_DYNAMIC);
        tex->load();

        LogManager::getSingleton().stream() << "Loaded texture in " << t.getMilliseconds() << "ms.";
        t.reset();

        mWidth = tex->getSrcWidth();
        mHeight= tex->getSrcHeight();
        mWidthTimesHeight = mWidth * mHeight;
        mDepth = tex->getSrcDepth();

        mPosXScale = (Real)1.0 / (Real)worldWidth * (Real)mWidth;
        mPosYScale = (Real)1.0 / (Real)worldHeight * (Real)mHeight;
        mPosZScale = (Real)1.0 / (Real)worldDepth * (Real)mDepth;

        mVolumeSpaceToWorldSpaceFactor = (Real)worldWidth * (Real)mWidth;

        HardwarePixelBufferSharedPtr buffer = tex->getBuffer(0, 0);
        buffer->lock(HardwareBuffer::HBL_READ_ONLY);
        const PixelBox &pb = buffer->getCurrentLock();
        float *pbptr = reinterpret_cast<float*>(pb.data);
        mData = OGRE_ALLOC_T(float, mWidth * mHeight * mDepth, MEMCATEGORY_GENERAL);
        float * dataRunner = mData;
        ColourValue cv;
        size_t x, y;
        size_t zEnd = pb.back;
        size_t yStart = pb.top;
        size_t yEnd = pb.bottom;
        size_t xStart = pb.left;
        size_t xEnd = pb.right;
        size_t sliceSkip = pb.getSliceSkip();
        for (size_t z = pb.front; z < zEnd; ++z)
        {
            for (y = yStart; y < yEnd; ++y)
            {
                for (x = xStart; x < xEnd; ++x)
                {
                    *dataRunner++ = pbptr[x];
                }
                pbptr += pb.rowPitch;
            }
            pbptr += sliceSkip;
        }
        buffer->unlock();

        TextureManager::getSingleton().remove(tex->getHandle());

        LogManager::getSingleton().stream() << "Processed texture in " << t.getMilliseconds() << "ms.";
    }

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

    TextureSource::~TextureSource(void)
    {
        OGRE_FREE(mData, MEMCATEGORY_GENERAL);
    }

}
}
<commit_msg>Volume: TextureSource - skip GPU round-trip and allow different formats<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVolumeTextureSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    float TextureSource::getVolumeGridValue(size_t x, size_t y, size_t z) const
    {
        x = x >= mWidth ? mWidth - 1 : x;
        y = y >= mHeight ? mHeight - 1 : y;
        z = z >= mDepth ? mDepth - 1 : z;
        return mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x];
    }

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

    void TextureSource::setVolumeGridValue(int x, int y, int z, float value)
    {
        mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x] = value;
    }

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

    TextureSource::TextureSource(const String &volumeTextureName, const Real worldWidth, const Real worldHeight, const Real worldDepth, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) :
        GridSource(trilinearValue, trilinearGradient, sobelGradient)
    {

        Timer t;
        Image img;
        img.load(volumeTextureName, ResourceGroupManager::getSingleton().getWorldResourceGroupName());

        LogManager::getSingleton().stream() << "Loaded texture in " << t.getMilliseconds() << "ms.";
        t.reset();

        mWidth = img.getWidth();
        mHeight= img.getHeight();
        mWidthTimesHeight = mWidth * mHeight;
        mDepth = img.getDepth();

        mPosXScale = (Real)1.0 / (Real)worldWidth * (Real)mWidth;
        mPosYScale = (Real)1.0 / (Real)worldHeight * (Real)mHeight;
        mPosZScale = (Real)1.0 / (Real)worldDepth * (Real)mDepth;

        mVolumeSpaceToWorldSpaceFactor = (Real)worldWidth * (Real)mWidth;

        auto srcBox = img.getPixelBox();

        mData = OGRE_ALLOC_T(float, mWidth * mHeight * mDepth, MEMCATEGORY_GENERAL);
        auto dstBox = srcBox;
        dstBox.data = (uchar*)mData;
        dstBox.format = PF_FLOAT32_R;
        PixelUtil::bulkPixelConversion(srcBox, dstBox);

        LogManager::getSingleton().stream() << "Processed texture in " << t.getMilliseconds() << "ms.";
    }

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

    TextureSource::~TextureSource(void)
    {
        OGRE_FREE(mData, MEMCATEGORY_GENERAL);
    }

}
}
<|endoftext|>


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

#include "cpu_collapse_dims.hpp"
#include <algorithm>
#include <iostream>
#include <numeric>
#include <unordered_set>
#include "ngraph/graph_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/util.hpp"

using namespace ngraph;

struct CollapsedDims
{
    std::vector<size_t> output_shape;
    std::vector<bool> is_operated_axis;
    std::vector<size_t> axis_set;
    std::vector<size_t> input_shape;
};

// Fold and collapse axes of output_shape.
// Contiguous axes that are not being operated on can be collapsed.
// Contiguous axes that are being operated on are collapsed optionally.
// Skip size 1 dimensions.
static void collapse_dims(std::vector<size_t>& output_shape,
                          std::set<size_t> operated_axes,
                          struct CollapsedDims& cdims,
                          bool collapse_operated_axes)
{
    size_t collapse_size = 1;
    bool operated_axes_run = false;
    bool collapsing = false;
    for (int output_idx = static_cast<int>(output_shape.size()) - 1; output_idx >= 0; output_idx--)
    {
        auto is_operated_axis = operated_axes.count(output_idx) == 1;
        auto end_run = (operated_axes_run != is_operated_axis) ||
                       (is_operated_axis && !collapse_operated_axes);
        if (collapsing && end_run)
        {
            if (collapse_size != 1)
            {
                cdims.output_shape.push_back(collapse_size);
                cdims.is_operated_axis.push_back(operated_axes_run);
                collapse_size = 1;
            }
        }

        collapse_size *= output_shape[output_idx];
        operated_axes_run = is_operated_axis;
        collapsing = true;
    }
    // Last run
    if (collapse_size != 1)
    {
        cdims.output_shape.push_back(collapse_size);
        cdims.is_operated_axis.push_back(operated_axes_run);
    }
    std::reverse(cdims.output_shape.begin(), cdims.output_shape.end());
    std::reverse(cdims.is_operated_axis.begin(), cdims.is_operated_axis.end());

    for (size_t i = 0; i < cdims.is_operated_axis.size(); i++)
    {
        if (cdims.is_operated_axis[i])
        {
            cdims.axis_set.push_back(i);
        }
        else
        {
            cdims.input_shape.push_back(cdims.output_shape[i]);
        }
    }
}

bool runtime::cpu::pass::CPUCollapseDims::run_on_function(std::shared_ptr<ngraph::Function> f)
{
    bool replaced = false;
    for (auto n : f->get_ordered_ops())
    {
        if (std::dynamic_pointer_cast<op::Broadcast>(n))
        {
            auto node = std::dynamic_pointer_cast<op::Broadcast>(n).get();
            auto input_shape = node->get_argument(0)->get_shape();
            auto output_shape = node->get_shape();
            auto operated_axes = node->get_broadcast_axes();

            struct CollapsedDims cdims;

            collapse_dims(output_shape, operated_axes, cdims, true);

            if (cdims.axis_set.size() == 0)
            {
                // Null broadcast operation, replace with reshape
                AxisVector axis_order = ngraph::get_default_order(input_shape);
                auto reshape = std::make_shared<op::Reshape>(
                    node->get_argument(0), axis_order, Shape(cdims.output_shape));
                ngraph::replace_node(n, reshape);
                replaced = true;
            }
            else if (output_shape.size() != cdims.output_shape.size())
            {
                // Reshape arg to collapsed input_shape
                AxisVector input_axis_order = ngraph::get_default_order(input_shape);
                auto reshape_input = std::make_shared<op::Reshape>(
                    node->get_argument(0), input_axis_order, Shape(cdims.input_shape));

                auto broadcast = std::make_shared<op::Broadcast>(
                    reshape_input, Shape(cdims.output_shape), AxisSet(cdims.axis_set));

                // Reshape collapsed output to original output_shape
                AxisVector output_axis_order = ngraph::get_default_order(cdims.output_shape);
                auto reshape_output =
                    std::make_shared<op::Reshape>(broadcast, output_axis_order, output_shape);
                ngraph::replace_node(n, reshape_output);
                replaced = true;
            }

            if (replaced)
            {
                NGRAPH_DEBUG << "CollapseDims: Replaced broadcast " << input_shape << " "
                             << operated_axes << " " << output_shape << " with "
                             << Shape(cdims.input_shape) << " " << AxisSet(cdims.axis_set) << " "
                             << Shape(cdims.output_shape);
            }
        }
    }

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

#include "cpu_collapse_dims.hpp"
#include <algorithm>
#include <iostream>
#include <numeric>
#include <unordered_set>
#include "ngraph/graph_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/util.hpp"

using namespace ngraph;

struct CollapsedDims
{
    std::vector<size_t> output_shape;
    std::vector<bool> is_operated_axis;
    std::vector<size_t> axis_set;
    std::vector<size_t> input_shape;
};

// Fold and collapse axes of output_shape.
// Contiguous axes that are not being operated on can be collapsed.
// Contiguous axes that are being operated on are collapsed optionally.
// Skip size 1 dimensions.
static void collapse_dims(std::vector<size_t>& output_shape,
                          std::set<size_t> operated_axes,
                          struct CollapsedDims& cdims,
                          bool collapse_operated_axes)
{
    size_t collapse_size = 1;
    bool operated_axes_run = false;
    bool collapsing = false;
    for (int output_idx = static_cast<int>(output_shape.size()) - 1; output_idx >= 0; output_idx--)
    {
        auto is_operated_axis = operated_axes.count(output_idx) == 1;
        auto end_run = (operated_axes_run != is_operated_axis) ||
                       (is_operated_axis && !collapse_operated_axes);
        if (collapsing && end_run)
        {
            if (collapse_size != 1)
            {
                cdims.output_shape.push_back(collapse_size);
                cdims.is_operated_axis.push_back(operated_axes_run);
                collapse_size = 1;
            }
        }

        collapse_size *= output_shape[output_idx];
        operated_axes_run = is_operated_axis;
        collapsing = true;
    }
    // Last run
    if (collapse_size != 1)
    {
        cdims.output_shape.push_back(collapse_size);
        cdims.is_operated_axis.push_back(operated_axes_run);
    }
    std::reverse(cdims.output_shape.begin(), cdims.output_shape.end());
    std::reverse(cdims.is_operated_axis.begin(), cdims.is_operated_axis.end());

    for (size_t i = 0; i < cdims.is_operated_axis.size(); i++)
    {
        if (cdims.is_operated_axis[i])
        {
            cdims.axis_set.push_back(i);
        }
        else
        {
            cdims.input_shape.push_back(cdims.output_shape[i]);
        }
    }
}

bool runtime::cpu::pass::CPUCollapseDims::run_on_function(std::shared_ptr<ngraph::Function> f)
{
    bool replaced = false;
    for (auto n : f->get_ordered_ops())
    {
        if (std::dynamic_pointer_cast<op::Broadcast>(n))
        {
            auto node = std::dynamic_pointer_cast<op::Broadcast>(n).get();
            auto input_shape = node->get_argument(0)->get_shape();
            auto output_shape = node->get_shape();
            auto operated_axes = node->get_broadcast_axes();

            struct CollapsedDims cdims;

            collapse_dims(output_shape, operated_axes, cdims, true);

            if (cdims.axis_set.size() == 0)
            {
                // Null broadcast operation, replace with reshape
                AxisVector axis_order = ngraph::get_default_order(input_shape);
                auto reshape = std::make_shared<op::Reshape>(
                    node->get_argument(0), axis_order, n->get_shape());
                ngraph::replace_node(n, reshape);
                replaced = true;
            }
            else if (output_shape.size() != cdims.output_shape.size())
            {
                // Reshape arg to collapsed input_shape
                AxisVector input_axis_order = ngraph::get_default_order(input_shape);
                auto reshape_input = std::make_shared<op::Reshape>(
                    node->get_argument(0), input_axis_order, Shape(cdims.input_shape));

                auto broadcast = std::make_shared<op::Broadcast>(
                    reshape_input, Shape(cdims.output_shape), AxisSet(cdims.axis_set));

                // Reshape collapsed output to original output_shape
                AxisVector output_axis_order = ngraph::get_default_order(cdims.output_shape);
                auto reshape_output =
                    std::make_shared<op::Reshape>(broadcast, output_axis_order, output_shape);
                ngraph::replace_node(n, reshape_output);
                replaced = true;
            }

            if (replaced)
            {
                NGRAPH_DEBUG << "CollapseDims: Replaced broadcast " << input_shape << " "
                             << operated_axes << " " << output_shape << " with "
                             << Shape(cdims.input_shape) << " " << AxisSet(cdims.axis_set) << " "
                             << Shape(cdims.output_shape);
            }
        }
    }

    return replaced;
}
<|endoftext|>