<commit_before>/*
 *  RudeMesh.cpp
 *
 *  Bork3D Game Engine
 *  Copyright (c) 2009 Bork 3D LLC. All rights reserved.
 *
 */

#include "RudeMesh.h"
#include "RudeGL.h"
#include "RudeTextureManager.h"
#include "RudeFile.h"
#include "RudeDebug.h"

RudeMesh::RudeMesh(RudeObject *owner)
: m_owner(owner)
, m_scale(1.0f, 1.0f, 1.0f)
, m_textureOverride(false)
{
	for(int i = 0; i < kMaxNodes; i++)
		m_colorOverrides[i] = 0;

	for(int i = 0; i < kMaxTextures; i++)
		m_textureOverrides[i] = -1;
}

RudeMesh::~RudeMesh()
{
}

int RudeMesh::Load(const char *name)
{
	RUDE_ASSERT(name, "Loading mesh with no name");

	RUDE_REPORT("RudeMesh::Load %s\n", name);

	char filename[64];
	sprintf(filename, "%s.POD", name);

	char modelfile[512];
	RudeFileGetFile(filename, modelfile, 512);

	int result = m_model.ReadFromFile(modelfile, 0, 0);

	RUDE_ASSERT(result == 1, "Could not load model");

	if(result == 0)
		return -1;

	RUDE_ASSERT(m_model.nNumTexture < kMaxTextures, "Too many textures in model");
	for(unsigned int i = 0; i < m_model.nNumTexture; i++)
	{
		SPODTexture *texture = &m_model.pTexture[i];
		RUDE_ASSERT(texture, "Invalid texture in model");

		char texturename[64];
		sprintf(texturename, "%s", texture->pszName);
		int texturenamelen = strlen(texturename);

		// cut off the last 4 chars
		texturename[texturenamelen-4] = '\0';

		m_textures[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(texturename);
		RUDE_ASSERT(m_textures[i] >= 0, "Could not load texture");

	}

	// make sure we have at least one renderable node
	bool foundRenderable = false;
	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'M')
			continue;

		foundRenderable = true;

		RUDE_REPORT("  Node %s: mesh %d\n", node->pszName, node->nIdx);
	}

	RUDE_ASSERT(foundRenderable, "Didn't find any renderable meshes in %s", name);

	// flip endianess of colors stored in meshes
	for(unsigned int i = 0; i < m_model.nNumMesh; i++)
	{
		SPODMesh *mesh = &m_model.pMesh[i];

		RUDE_ASSERT(mesh->pInterleaved, "Mesh data must be interleaved");

		if((mesh->sVtxColours.n > 0))
		{
			RUDE_ASSERT(mesh->sVtxColours.eType == EPODDataRGBA, "Vertex colors must be in RGBA format");

			if(mesh->sVtxColours.eType == EPODDataRGBA)
			{
				unsigned char *c = (mesh->pInterleaved + (long)mesh->sVtxColours.pData);

				for(unsigned int j = 0; j < mesh->nNumVertex; j++)
				{
					unsigned int *cc = (unsigned int *) c;
					unsigned int b = *cc & 0x000000FF;
					unsigned int g = (*cc & 0x0000FF00) >> 8;
					unsigned int r = (*cc & 0x00FF0000) >> 16;
					//unsigned int a = (*cc & 0xFF000000) >> 24;
					b = g = r;

					*cc = 0xFF000000 | (b << 16) | (g << 8) | r;

					c += mesh->sVtxColours.nStride;
				}
			}
		}
	}

	return 0;

}

void RudeMesh::AddTextureOverride(const char *oldTexture, const char *newTexture)
{
	bool found = false;

	for(unsigned int i = 0; i < m_model.nNumTexture; i++)
	{
		SPODTexture *texture = &m_model.pTexture[i];
		RUDE_ASSERT(texture, "Invalid texture in model");

		char texturename[64];
		sprintf(texturename, "%s", texture->pszName);
		int texturenamelen = strlen(texturename);

		// cut off the last 4 chars
		texturename[texturenamelen-4] = '\0';

		if(strcmp(oldTexture, texturename) == 0)
		{
			m_textureOverrides[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(newTexture);
			RUDE_ASSERT(m_textureOverrides[i] >= 0, "Could not load texture %s", newTexture);
			found = true;
		}
	}

	RUDE_ASSERT(found, "Texture %s not found", oldTexture);
}

void RudeMesh::SetColorOverride(int node, const char *colordata)
{
	RUDE_ASSERT(node < kMaxNodes, "Invalid node");

	m_colorOverrides[node] = colordata;
}

void RudeMesh::EnableModel(int n, bool enable)
{
	bool found = false;
	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;

		if(node->pszName[0] == 'M' || node->pszName[0] == 'm')
		{
			if(node->pszName[1] == ('0' + n))
			{
				found = true;

				if(enable)
					node->pszName[0] = 'M';
				else
					node->pszName[0] = 'm';
			}
		}
	}

	RUDE_ASSERT(found, "Could not find model number %d", n);

}

void RudeMesh::Render()
{

	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	RGL.EnableClient(kVertexArray, true);
	RGL.EnableClient(kTextureCoordArray, true);

	//glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

	//glScalef(m_scale.x(), m_scale.y(), m_scale.z());

	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'M')
			continue;

		SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
		SPODMesh *mesh = &m_model.pMesh[node->nIdx];

		int textureid = material->nIdxTexDiffuse;
		if(textureid >= 0)
		{
			if(m_textureOverride && m_textureOverrides[textureid] >= 0)
				RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]);
			else
				RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
		}

		unsigned short *indices	= (unsigned short*) mesh->sFaces.pData;

		if(mesh->sVertex.eType == EPODDataShortNorm)
		{
			float s = 1.0f / 1000.0f;
			glMatrixMode(GL_MODELVIEW);
			glScalef(s, s, s);
			glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		}
		else
			glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);

		glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);

		if(m_colorOverrides[i])
		{
			RGL.EnableClient(kColorArray, true);
			glColorPointer(4, GL_UNSIGNED_BYTE, 4, m_colorOverrides[i]);
		}
		else
		{
			if(mesh->sVtxColours.n > 0)
			{
				RGL.EnableClient(kColorArray, true);
				glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
			}
			else
				RGL.EnableClient(kColorArray, false);
		}

		glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices);

	}

#if 0

	glAlphaFunc ( GL_GREATER, 0.5 ) ;
    glEnable ( GL_ALPHA_TEST ) ;

	for(int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'D')
			continue;

		SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
		SPODMesh *mesh = &m_model.pMesh[node->nIdx];

		int textureid = material->nIdxTexDiffuse;
		if(textureid >= 0)
		{
			if(m_textureOverride && m_textureOverrides[textureid] >= 0)
				RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]);
			else
				RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
		}

		unsigned short *indices	= (unsigned short*) mesh->sFaces.pData;

		if(mesh->sVertex.eType == EPODDataFixed16_16)
			glVertexPointer(3, GL_FIXED, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		else if(mesh->sVertex.eType == EPODDataShortNorm)
		{
			float s = 1.0f / 1000.0f;
			glMatrixMode(GL_MODELVIEW);
			glScalef(s, s, s);
			glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		}
		else
			glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);

		glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);

		if(mesh->sVtxColours.n > 0)
		{
			RGL.EnableClient(kColorArray, true);
			glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
		}
		else
			RGL.EnableClient(kColorArray, false);

		glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices);

	}

    glDisable ( GL_ALPHA_TEST ) ;

#endif

}

<commit_msg>Fix for no-color mesh rendering on win32<commit_after>/*
 *  RudeMesh.cpp
 *
 *  Bork3D Game Engine
 *  Copyright (c) 2009 Bork 3D LLC. All rights reserved.
 *
 */

#include "RudeMesh.h"
#include "RudeGL.h"
#include "RudeTextureManager.h"
#include "RudeFile.h"
#include "RudeDebug.h"

RudeMesh::RudeMesh(RudeObject *owner)
: m_owner(owner)
, m_scale(1.0f, 1.0f, 1.0f)
, m_textureOverride(false)
{
	for(int i = 0; i < kMaxNodes; i++)
		m_colorOverrides[i] = 0;

	for(int i = 0; i < kMaxTextures; i++)
		m_textureOverrides[i] = -1;
}

RudeMesh::~RudeMesh()
{
}

int RudeMesh::Load(const char *name)
{
	RUDE_ASSERT(name, "Loading mesh with no name");

	RUDE_REPORT("RudeMesh::Load %s\n", name);

	char filename[64];
	sprintf(filename, "%s.POD", name);

	char modelfile[512];
	RudeFileGetFile(filename, modelfile, 512);

	int result = m_model.ReadFromFile(modelfile, 0, 0);

	RUDE_ASSERT(result == 1, "Could not load model");

	if(result == 0)
		return -1;

	RUDE_ASSERT(m_model.nNumTexture < kMaxTextures, "Too many textures in model");
	for(unsigned int i = 0; i < m_model.nNumTexture; i++)
	{
		SPODTexture *texture = &m_model.pTexture[i];
		RUDE_ASSERT(texture, "Invalid texture in model");

		char texturename[64];
		sprintf(texturename, "%s", texture->pszName);
		int texturenamelen = strlen(texturename);

		// cut off the last 4 chars
		texturename[texturenamelen-4] = '\0';

		m_textures[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(texturename);
		RUDE_ASSERT(m_textures[i] >= 0, "Could not load texture");

	}

	// make sure we have at least one renderable node
	bool foundRenderable = false;
	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'M')
			continue;

		foundRenderable = true;

		RUDE_REPORT("  Node %s: mesh %d\n", node->pszName, node->nIdx);
	}

	RUDE_ASSERT(foundRenderable, "Didn't find any renderable meshes in %s", name);

	// flip endianess of colors stored in meshes
	for(unsigned int i = 0; i < m_model.nNumMesh; i++)
	{
		SPODMesh *mesh = &m_model.pMesh[i];

		RUDE_ASSERT(mesh->pInterleaved, "Mesh data must be interleaved");

		if((mesh->sVtxColours.n > 0))
		{
			RUDE_ASSERT(mesh->sVtxColours.eType == EPODDataRGBA, "Vertex colors must be in RGBA format");

			if(mesh->sVtxColours.eType == EPODDataRGBA)
			{
				unsigned char *c = (mesh->pInterleaved + (long)mesh->sVtxColours.pData);

				for(unsigned int j = 0; j < mesh->nNumVertex; j++)
				{
					unsigned int *cc = (unsigned int *) c;
					unsigned int b = *cc & 0x000000FF;
					unsigned int g = (*cc & 0x0000FF00) >> 8;
					unsigned int r = (*cc & 0x00FF0000) >> 16;
					//unsigned int a = (*cc & 0xFF000000) >> 24;
					b = g = r;

					*cc = 0xFF000000 | (b << 16) | (g << 8) | r;

					c += mesh->sVtxColours.nStride;
				}
			}
		}
	}

	return 0;

}

void RudeMesh::AddTextureOverride(const char *oldTexture, const char *newTexture)
{
	bool found = false;

	for(unsigned int i = 0; i < m_model.nNumTexture; i++)
	{
		SPODTexture *texture = &m_model.pTexture[i];
		RUDE_ASSERT(texture, "Invalid texture in model");

		char texturename[64];
		sprintf(texturename, "%s", texture->pszName);
		int texturenamelen = strlen(texturename);

		// cut off the last 4 chars
		texturename[texturenamelen-4] = '\0';

		if(strcmp(oldTexture, texturename) == 0)
		{
			m_textureOverrides[i] = RudeTextureManager::GetInstance()->LoadTextureFromPVRTFile(newTexture);
			RUDE_ASSERT(m_textureOverrides[i] >= 0, "Could not load texture %s", newTexture);
			found = true;
		}
	}

	RUDE_ASSERT(found, "Texture %s not found", oldTexture);
}

void RudeMesh::SetColorOverride(int node, const char *colordata)
{
	RUDE_ASSERT(node < kMaxNodes, "Invalid node");

	m_colorOverrides[node] = colordata;
}

void RudeMesh::EnableModel(int n, bool enable)
{
	bool found = false;
	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;

		if(node->pszName[0] == 'M' || node->pszName[0] == 'm')
		{
			if(node->pszName[1] == ('0' + n))
			{
				found = true;

				if(enable)
					node->pszName[0] = 'M';
				else
					node->pszName[0] = 'm';
			}
		}
	}

	RUDE_ASSERT(found, "Could not find model number %d", n);

}

void RudeMesh::Render()
{

	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	RGL.EnableClient(kVertexArray, true);
	RGL.EnableClient(kTextureCoordArray, true);

	//glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

	//glScalef(m_scale.x(), m_scale.y(), m_scale.z());

	for(unsigned int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'M')
			continue;

		SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
		SPODMesh *mesh = &m_model.pMesh[node->nIdx];

		int textureid = material->nIdxTexDiffuse;
		if(textureid >= 0)
		{
			if(m_textureOverride && m_textureOverrides[textureid] >= 0)
				RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]);
			else
				RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
		}

		unsigned short *indices	= (unsigned short*) mesh->sFaces.pData;

		if(mesh->sVertex.eType == EPODDataShortNorm)
		{
			float s = 1.0f / 1000.0f;
			glMatrixMode(GL_MODELVIEW);
			glScalef(s, s, s);
			glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		}
		else
			glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);

		glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);

		if(m_colorOverrides[i])
		{
			RGL.EnableClient(kColorArray, true);
			glColorPointer(4, GL_UNSIGNED_BYTE, 4, m_colorOverrides[i]);
		}
		else
		{
			if(mesh->sVtxColours.n > 0)
			{
				RGL.EnableClient(kColorArray, true);
				glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
			}
			else
			{
				RGL.EnableClient(kColorArray, false);
				glColor4f(1.0, 1.0, 1.0, 1.0);
			}
		}

		glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices);

	}

#if 0

	glAlphaFunc ( GL_GREATER, 0.5 ) ;
    glEnable ( GL_ALPHA_TEST ) ;

	for(int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];

		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'D')
			continue;

		SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
		SPODMesh *mesh = &m_model.pMesh[node->nIdx];

		int textureid = material->nIdxTexDiffuse;
		if(textureid >= 0)
		{
			if(m_textureOverride && m_textureOverrides[textureid] >= 0)
				RudeTextureManager::GetInstance()->SetTexture(m_textureOverrides[textureid]);
			else
				RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
		}

		unsigned short *indices	= (unsigned short*) mesh->sFaces.pData;

		if(mesh->sVertex.eType == EPODDataFixed16_16)
			glVertexPointer(3, GL_FIXED, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		else if(mesh->sVertex.eType == EPODDataShortNorm)
		{
			float s = 1.0f / 1000.0f;
			glMatrixMode(GL_MODELVIEW);
			glScalef(s, s, s);
			glVertexPointer(3, GL_UNSIGNED_SHORT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		}
		else
			glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);

		glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);

		if(mesh->sVtxColours.n > 0)
		{
			RGL.EnableClient(kColorArray, true);
			glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
		}
		else
			RGL.EnableClient(kColorArray, false);

		glDrawElements(GL_TRIANGLES, mesh->nNumFaces*3, GL_UNSIGNED_SHORT, indices);

	}

    glDisable ( GL_ALPHA_TEST ) ;

#endif

}

<|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.
 *
 ************************************************************************/

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

#include <vcl/toolbox.hxx>

#include <sfx2/app.hxx>
#include "appdata.hxx"
#include "arrdecl.hxx"
#include "sfx2/sfxhelp.hxx"
#include <sfx2/templdlg.hxx>
#include "inettbc.hxx"
#include "sfx2/stbitem.hxx"
#include <sfx2/navigat.hxx>
#include <sfx2/taskpane.hxx>
#include <sfx2/module.hxx>
#include <sfx2/viewfrm.hxx>
#include "partwnd.hxx"
#include <sfx2/sfxsids.hrc>
#include "recfloat.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/objface.hxx>

//===================================================================

void SfxApplication::Registrations_Impl()
{
    // Interfaces
    SfxApplication::RegisterInterface();
    SfxModule::RegisterInterface();
    SfxViewFrame::RegisterInterface();
    SfxObjectShell::RegisterInterface();
    SfxViewShell::RegisterInterface();

    // ChildWindows
    SfxRecordingFloatWrapper_Impl::RegisterChildWindow();
    SfxNavigatorWrapper::RegisterChildWindow( sal_False, NULL, SFX_CHILDWIN_NEVERHIDE );
    SfxPartChildWnd_Impl::RegisterChildWindow();
    SfxTemplateDialogWrapper::RegisterChildWindow(sal_True);
    SfxDockingWrapper::RegisterChildWindow();

    // Controller
    SfxToolBoxControl::RegisterControl(SID_REPEAT);
    SfxURLToolBoxControl_Impl::RegisterControl(SID_OPENURL);
    SfxAppToolBoxControl_Impl::RegisterControl( SID_NEWDOCDIRECT );
    SfxAppToolBoxControl_Impl::RegisterControl( SID_AUTOPILOTMENU );
};

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

void SfxApplication::RegisterToolBoxControl_Impl( SfxModule *pMod, SfxTbxCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterToolBoxControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pTbxCtrlFac->Count(); n++ )
    {
        SfxTbxCtrlFactory *pF = (*pAppData_Impl->pTbxCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("TbxController registration is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pTbxCtrlFac->C40_INSERT( SfxTbxCtrlFactory, pFact, pAppData_Impl->pTbxCtrlFac->Count() );
}

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

void SfxApplication::RegisterStatusBarControl_Impl( SfxModule *pMod, SfxStbCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterStatusBarControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pStbCtrlFac->Count(); n++ )
    {
        SfxStbCtrlFactory *pF = (*pAppData_Impl->pStbCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("StbController registration is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pStbCtrlFac->C40_INSERT( SfxStbCtrlFactory, pFact, pAppData_Impl->pStbCtrlFac->Count() );
}

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

void SfxApplication::RegisterMenuControl_Impl( SfxModule *pMod, SfxMenuCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterMenuControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pMenuCtrlFac->Count(); n++ )
    {
        SfxMenuCtrlFactory *pF = (*pAppData_Impl->pMenuCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("MenuController register is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pMenuCtrlFac->C40_INSERT( SfxMenuCtrlFactory, pFact, pAppData_Impl->pMenuCtrlFac->Count() );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>include mnuitem.hxx to build with --enable-dbgutil<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.
 *
 ************************************************************************/

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

#include <vcl/toolbox.hxx>

#include <sfx2/app.hxx>
#include "appdata.hxx"
#include "arrdecl.hxx"
#include "sfx2/sfxhelp.hxx"
#include <sfx2/templdlg.hxx>
#include "inettbc.hxx"
#include "sfx2/stbitem.hxx"
#include <sfx2/navigat.hxx>
#include <sfx2/taskpane.hxx>
#include <sfx2/module.hxx>
#include <sfx2/viewfrm.hxx>
#include "partwnd.hxx"
#include <sfx2/sfxsids.hrc>
#include "recfloat.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/mnuitem.hxx>

//===================================================================

void SfxApplication::Registrations_Impl()
{
    // Interfaces
    SfxApplication::RegisterInterface();
    SfxModule::RegisterInterface();
    SfxViewFrame::RegisterInterface();
    SfxObjectShell::RegisterInterface();
    SfxViewShell::RegisterInterface();

    // ChildWindows
    SfxRecordingFloatWrapper_Impl::RegisterChildWindow();
    SfxNavigatorWrapper::RegisterChildWindow( sal_False, NULL, SFX_CHILDWIN_NEVERHIDE );
    SfxPartChildWnd_Impl::RegisterChildWindow();
    SfxTemplateDialogWrapper::RegisterChildWindow(sal_True);
    SfxDockingWrapper::RegisterChildWindow();

    // Controller
    SfxToolBoxControl::RegisterControl(SID_REPEAT);
    SfxURLToolBoxControl_Impl::RegisterControl(SID_OPENURL);
    SfxAppToolBoxControl_Impl::RegisterControl( SID_NEWDOCDIRECT );
    SfxAppToolBoxControl_Impl::RegisterControl( SID_AUTOPILOTMENU );
};

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

void SfxApplication::RegisterToolBoxControl_Impl( SfxModule *pMod, SfxTbxCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterToolBoxControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pTbxCtrlFac->Count(); n++ )
    {
        SfxTbxCtrlFactory *pF = (*pAppData_Impl->pTbxCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("TbxController registration is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pTbxCtrlFac->C40_INSERT( SfxTbxCtrlFactory, pFact, pAppData_Impl->pTbxCtrlFac->Count() );
}

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

void SfxApplication::RegisterStatusBarControl_Impl( SfxModule *pMod, SfxStbCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterStatusBarControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pStbCtrlFac->Count(); n++ )
    {
        SfxStbCtrlFactory *pF = (*pAppData_Impl->pStbCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("StbController registration is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pStbCtrlFac->C40_INSERT( SfxStbCtrlFactory, pFact, pAppData_Impl->pStbCtrlFac->Count() );
}

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

void SfxApplication::RegisterMenuControl_Impl( SfxModule *pMod, SfxMenuCtrlFactory *pFact )
{
    if ( pMod )
    {
        pMod->RegisterMenuControl( pFact );
        return;
    }

#ifdef DBG_UTIL
    for ( sal_uInt16 n=0; n<pAppData_Impl->pMenuCtrlFac->Count(); n++ )
    {
        SfxMenuCtrlFactory *pF = (*pAppData_Impl->pMenuCtrlFac)[n];
        if ( pF->nTypeId && pF->nTypeId == pFact->nTypeId &&
            (pF->nSlotId == pFact->nSlotId || pF->nSlotId == 0) )
        {
            DBG_WARNING("MenuController register is not clearly defined!");
        }
    }
#endif

    pAppData_Impl->pMenuCtrlFac->C40_INSERT( SfxMenuCtrlFactory, pFact, pAppData_Impl->pMenuCtrlFac->Count() );
}

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


<commit_before>#include <iostream>
#include <fstream>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include "Reseed.h"
#include "Log.h"
#include "util.h"

namespace i2p
{
namespace data
{

	static std::vector<std::string> httpReseedHostList = {
				"http://193.150.121.66/netDb/",
				"http://netdb.i2p2.no/",
				"http://reseed.i2p-projekt.de/",
				"http://cowpuncher.drollette.com/netdb/",
				"http://i2p.mooo.com/netDb/",
				"http://reseed.info/",
				"http://reseed.pkol.de/",
				"http://uk.reseed.i2p2.no/",
				"http://i2p-netdb.innovatio.no/",
				"http://ieb9oopo.mooo.com"
			};

	//TODO: Implement v2 reseeding. Lightweight zip library is needed.
	//TODO: Implement SU3, utils.
	Reseeder::Reseeder()
	{
	}

	Reseeder::~Reseeder()
	{
	}

	bool Reseeder::reseedNow()
	{
		try
		{
			std::string reseedHost = httpReseedHostList[(rand() % httpReseedHostList.size())];
			LogPrint("Reseeding from ", reseedHost);
			std::string content = i2p::util::http::httpRequest(reseedHost);
			if (content == "")
			{
				LogPrint("Reseed failed");
				return false;
			}
			boost::regex e("<\\s*A\\s+[^>]*href\\s*=\\s*\"([^\"]*)\"", boost::regex::normal | boost::regbase::icase);
			boost::sregex_token_iterator i(content.begin(), content.end(), e, 1);
			boost::sregex_token_iterator j;
			//TODO: Ugly code, try to clean up.
			//TODO: Try to reduce N number of variables
			std::string name;
			std::string routerInfo;
			std::string tmpUrl;
			std::string filename;
			std::string ignoreFileSuffix = ".zip";
			boost::filesystem::path root = i2p::util::filesystem::GetDataDir();
			while (i != j)
			{
				name = *i++;
				if (name.find(ignoreFileSuffix)!=std::string::npos)
					continue;
				LogPrint("Downloading ", name);
				tmpUrl = reseedHost;
				tmpUrl.append(name);
				routerInfo = i2p::util::http::httpRequest(tmpUrl);
				if (routerInfo.size()==0)
					continue;
				filename = root.string();
#ifndef _WIN32
				filename += "/netDb/r";
#else
				filename += "\\netDb\\r";
#endif
				filename += name.at(11); // first char in id
#ifndef _WIN32
				filename.append("/");
#else
				filename.append("\\");
#endif
				filename.append(name.c_str());
				std::ofstream outfile (filename, std::ios::binary);
				outfile << routerInfo;
				outfile.close();
			}
			return true;
		}
		catch (std::exception& ex)
		{
			//TODO: error reporting
			return false;
		}
		return false;
	}

}
}

<commit_msg>Ignore su3 files for now, support is comming.<commit_after>#include <iostream>
#include <fstream>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include "Reseed.h"
#include "Log.h"
#include "util.h"

namespace i2p
{
namespace data
{

	static std::vector<std::string> httpReseedHostList = {
				"http://193.150.121.66/netDb/",
				"http://netdb.i2p2.no/",
				"http://reseed.i2p-projekt.de/",
				"http://cowpuncher.drollette.com/netdb/",
				"http://i2p.mooo.com/netDb/",
				"http://reseed.info/",
				"http://reseed.pkol.de/",
				"http://uk.reseed.i2p2.no/",
				"http://i2p-netdb.innovatio.no/",
				"http://ieb9oopo.mooo.com"
			};

	//TODO: Implement v2 reseeding. Lightweight zip library is needed.
	//TODO: Implement SU3, utils.
	Reseeder::Reseeder()
	{
	}

	Reseeder::~Reseeder()
	{
	}

	bool Reseeder::reseedNow()
	{
		try
		{
			std::string reseedHost = httpReseedHostList[(rand() % httpReseedHostList.size())];
			LogPrint("Reseeding from ", reseedHost);
			std::string content = i2p::util::http::httpRequest(reseedHost);
			if (content == "")
			{
				LogPrint("Reseed failed");
				return false;
			}
			boost::regex e("<\\s*A\\s+[^>]*href\\s*=\\s*\"([^\"]*)\"", boost::regex::normal | boost::regbase::icase);
			boost::sregex_token_iterator i(content.begin(), content.end(), e, 1);
			boost::sregex_token_iterator j;
			//TODO: Ugly code, try to clean up.
			//TODO: Try to reduce N number of variables
			std::string name;
			std::string routerInfo;
			std::string tmpUrl;
			std::string filename;
			std::string ignoreFileSuffix = ".su3";
			boost::filesystem::path root = i2p::util::filesystem::GetDataDir();
			while (i != j)
			{
				name = *i++;
				if (name.find(ignoreFileSuffix)!=std::string::npos)
					continue;
				LogPrint("Downloading ", name);
				tmpUrl = reseedHost;
				tmpUrl.append(name);
				routerInfo = i2p::util::http::httpRequest(tmpUrl);
				if (routerInfo.size()==0)
					continue;
				filename = root.string();
#ifndef _WIN32
				filename += "/netDb/r";
#else
				filename += "\\netDb\\r";
#endif
				filename += name.at(11); // first char in id
#ifndef _WIN32
				filename.append("/");
#else
				filename.append("\\");
#endif
				filename.append(name.c_str());
				std::ofstream outfile (filename, std::ios::binary);
				outfile << routerInfo;
				outfile.close();
			}
			return true;
		}
		catch (std::exception& ex)
		{
			//TODO: error reporting
			return false;
		}
		return false;
	}

}
}

<|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 .
 */
#ifndef INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX
#define INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX

#include <vector>
#include <deque>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/ui/XUIElement.hpp>
#include <com/sun/star/task/XStatusIndicator.hpp>
#include <com/sun/star/frame/XLayoutManagerListener.hpp>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/propshlp.hxx>

#include <rtl/ustring.hxx>
#include <osl/mutex.hxx>
#include <o3tl/typed_flags_set.hxx>

#include <sfx2/sfx.hrc>
#include <sfx2/childwin.hxx>
#include <sfx2/shell.hxx>
#include <sfx2/ctrlitem.hxx>
#include <sfx2/viewfrm.hxx>

class SfxSplitWindow;
class SfxWorkWindow;

// This struct makes all relevant Informationen available of Toolboxes
struct SfxObjectBar_Impl
{
    sal_uInt16        nId;   // Resource - and ConfigId of Toolbox
    sal_uInt16        nMode; // special visibility flags
    sal_uInt16        nPos;
    sal_uInt16        nIndex;
    bool              bDestroy;
    SfxInterface*     pIFace;

    SfxObjectBar_Impl() :
        nId(0),
        nMode(0),
        nPos(0),
        nIndex(0),
        bDestroy(false),
        pIFace(0)
    {}
};

// This struct makes all relevant Informationen available of the status bar

struct SfxStatBar_Impl
{
    sal_uInt16              nId;
    bool                    bOn;
    bool                    bTemp;

    SfxStatBar_Impl() :
        nId(0),
        bOn(true),
        bTemp(false)
    {}
};

enum class SfxChildVisibility
{
    NOT_VISIBLE  = 0,
    ACTIVE       = 1,   // not disabled through HidePopups
    NOT_HIDDEN   = 2,   // not disabled through HideChildWindow
    FITS_IN      = 4,    // not too large for output size of the parent
    VISIBLE      = 7,   // NOT_HIDDEN | ACTIVE | FITS_IN)
};
namespace o3tl
{
    template<> struct typed_flags<SfxChildVisibility> : is_typed_flags<SfxChildVisibility, 0x07> {};
}

struct SfxChild_Impl
{
    vcl::Window*                     pWin;
    Size                            aSize;
    SfxChildAlignment               eAlign;
    SfxChildVisibility              nVisible;
    bool                            bResize;
    bool                            bCanGetFocus;
    bool                            bSetFocus;

    SfxChild_Impl( vcl::Window& rChild, const Size& rSize,
                   SfxChildAlignment eAlignment, bool bIsVisible ):
        pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(false),
        bCanGetFocus( false ), bSetFocus( false )
    {
        nVisible = bIsVisible ? SfxChildVisibility::VISIBLE : SfxChildVisibility::NOT_VISIBLE;
    }
};

struct SfxChildWin_Impl
{
    sal_uInt16                      nSaveId;       // the ChildWindow-Id
    sal_uInt16                      nInterfaceId;  // the current context
    sal_uInt16                      nId;           // current Id
    SfxChildWindow*                 pWin;
    bool                            bCreate;
    SfxChildWinInfo                 aInfo;
    SfxChild_Impl*                  pCli;          // != 0 at direct Children
    sal_uInt16                      nVisibility;
    bool                            bEnable;
    bool                            bDisabled;

    SfxChildWin_Impl( sal_uInt32 nID ) :
        nSaveId((sal_uInt16) (nID & 0xFFFF) ),
        nInterfaceId((sal_uInt16) (nID >> 16)),
        nId(nSaveId),
        pWin(0),
        bCreate(false),
        pCli(0),
        nVisibility( sal_False ),
        bEnable( true ),
        bDisabled( false )
    {}
};

enum class SfxChildIdentifier
{
    STATBAR,
    OBJECTBAR,
    DOCKINGWINDOW,
    SPLITWINDOW
};

enum class SfxDockingConfig
{
    SETDOCKINGRECTS,
    ALIGNDOCKINGWINDOW,
    TOGGLEFLOATMODE,
    MOVEDOCKINGWINDOW
};

typedef std::vector<SfxChild_Impl*> SfxChildList_Impl;
typedef std::vector<SfxChildWin_Impl*> SfxChildWindows_Impl;

struct SfxObjectBarList_Impl
{
    std::deque<SfxObjectBar_Impl>   aArr;
    sal_uInt16                  nAct;

    SfxObjectBar_Impl       operator[] ( sal_uInt16 n )
                            { return aArr[n]; }
    SfxObjectBar_Impl       Actual()
                            { return aArr[nAct]; }
};

#define SFX_SPLITWINDOWS_LEFT   0
#define SFX_SPLITWINDOWS_TOP    2
#define SFX_SPLITWINDOWS_RIGHT  1
#define SFX_SPLITWINDOWS_MAX    4

class LayoutManagerListener : public ::cppu::WeakImplHelper2<
                                         css::frame::XLayoutManagerListener,
                                         css::lang::XComponent >
{
    public:
        LayoutManagerListener( SfxWorkWindow* pWrkWin );
        virtual ~LayoutManagerListener();

        void setFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        //  XComponent

        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
        virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

        //  XEventListener

        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

        // XLayoutManagerEventListener

        virtual void SAL_CALL layoutEvent( const ::com::sun::star::lang::EventObject& aSource, ::sal_Int16 eLayoutEvent, const ::com::sun::star::uno::Any& aInfo ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

    private:
        bool                                                                m_bHasFrame;
        SfxWorkWindow*                                                          m_pWrkWin;
        ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > m_xFrame;
        OUString                                                           m_aLayoutManagerPropName;
};

class SfxWorkWindow
{
    friend class LayoutManagerListener;

protected:
    std::vector<sal_uInt16> aSortedList;
    SfxStatBar_Impl         aStatBar;
    std::vector< SfxObjectBar_Impl > aObjBarList;
    Rectangle               aClientArea;
    Rectangle               aUpperClientArea;
    SfxWorkWindow*          pParent;
    SfxSplitWindow*         pSplit[SFX_SPLITWINDOWS_MAX];
    SfxChildList_Impl       aChildren;
    SfxChildWindows_Impl    aChildWins;
    SfxBindings*            pBindings;
    vcl::Window*                 pWorkWin;
    SfxShell*               pConfigShell;
    vcl::Window*                 pActiveChild;
    sal_uInt16                  nUpdateMode;
    sal_uInt16                  nChildren;
    sal_uInt16                  nOrigMode;
    bool                    bSorted : 1;
    bool                    bDockingAllowed : 1;
    bool                    bInternalDockingAllowed : 1;
    bool                    bAllChildrenVisible : 1;
    bool                    bIsFullScreen : 1;
    bool                    bShowStatusBar : 1;
    sal_Int32               m_nLock;
    OUString           m_aStatusBarResName;
    OUString           m_aLayoutManagerPropName;
    OUString           m_aTbxTypeName;
    OUString           m_aProgressBarResName;
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xLayoutManagerListener;

protected:
    void                    CreateChildWin_Impl(SfxChildWin_Impl*,bool);
    void                    RemoveChildWin_Impl(SfxChildWin_Impl*);
    void                    Sort_Impl();
    SfxChild_Impl*          FindChild_Impl( const vcl::Window& rWindow ) const;
    bool                    RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual Rectangle       GetTopRect_Impl();
    SvBorder                Arrange_Impl();
    void                    SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
    static bool             IsPluginMode( SfxObjectShell* pObjShell );

public:
                            SfxWorkWindow( vcl::Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL);
    virtual                 ~SfxWorkWindow();
    SfxBindings&            GetBindings()
                            { return *pBindings; }
    vcl::Window*                 GetWindow() const
                            { return pWorkWin; }
    Rectangle               GetFreeArea( bool bAutoHide ) const;
    void                    SetDockingAllowed(bool bSet)
                            { bDockingAllowed = bSet; }
    void                    SetInternalDockingAllowed(bool bSet)
                            { bInternalDockingAllowed = bSet; }
    bool                    IsDockingAllowed() const
                            { return bDockingAllowed; }
    bool                    IsInternalDockingAllowed() const
                            { return bInternalDockingAllowed; }
    SfxWorkWindow*          GetParent_Impl() const
                            { return pParent; }

    // Methods for all Child windows
    void                    DataChanged_Impl( const DataChangedEvent& rDCEvt );
    void                    ReleaseChild_Impl( vcl::Window& rWindow );
    SfxChild_Impl*          RegisterChild_Impl( vcl::Window& rWindow, SfxChildAlignment eAlign, bool bCanGetFocus=false );
    void                    ShowChildren_Impl();
    void                    HideChildren_Impl();
    bool                    PrepareClose_Impl();
    virtual void            ArrangeChildren_Impl( bool bForce = true );
    void                    DeleteControllers_Impl();
    void                    HidePopups_Impl(bool bHide, bool bParent=false, sal_uInt16 nId=0);
    void                    ConfigChild_Impl(SfxChildIdentifier,
                                             SfxDockingConfig, sal_uInt16);
    void                    MakeChildrenVisible_Impl( bool bVis );
    void                    ArrangeAutoHideWindows( SfxSplitWindow *pSplit );
    bool                    IsAutoHideMode( const SfxSplitWindow *pSplit );
    void                    EndAutoShow_Impl( Point aPos );
    void                    SetFullScreen_Impl( bool bSet ) { bIsFullScreen = bSet; }
    bool                    IsFullScreen_Impl() const { return bIsFullScreen; }

    // Methods for Objectbars
    virtual void            UpdateObjectBars_Impl();
    void                    ResetObjectBars_Impl();
    void                    SetObjectBar_Impl(sal_uInt16 nPos, sal_uInt32 nResId,
                                    SfxInterface *pIFace);
    bool                    KnowsObjectBar_Impl( sal_uInt16 nPos ) const;
    bool                    IsVisible_Impl();
    void                    MakeVisible_Impl( bool );
    void                    SetObjectBarVisibility_Impl( sal_uInt16 nVis );
    bool                    IsContainer_Impl() const;
    void                    Lock_Impl( bool );

    // Methods for ChildWindows
    void                    UpdateChildWindows_Impl();
    void                    ResetChildWindows_Impl();
    void                    SetChildWindowVisible_Impl( sal_uInt32, bool, sal_uInt16 );
    void                    ToggleChildWindow_Impl(sal_uInt16,bool);
    bool                    HasChildWindow_Impl(sal_uInt16);
    bool                    KnowsChildWindow_Impl(sal_uInt16);
    void                    ShowChildWindow_Impl(sal_uInt16, bool bVisible, bool bSetFocus);
    void                    SetChildWindow_Impl(sal_uInt16, bool bOn, bool bSetFocus);
    SfxChildWindow*         GetChildWindow_Impl(sal_uInt16);
    void                    InitializeChild_Impl(SfxChildWin_Impl*);
    SfxSplitWindow*         GetSplitWindow_Impl(SfxChildAlignment);

    bool                    IsVisible_Impl( sal_uInt16 nMode ) const;
    bool                    IsFloating( sal_uInt16 nId );
    void                    SetActiveChild_Impl( vcl::Window *pChild );
    bool                    ActivateNextChild_Impl( bool bForward = true );
    bool                    AllowChildWindowCreation_Impl( const SfxChildWin_Impl& i_rCW ) const;

    // Methods for StatusBar
    void                    ResetStatusBar_Impl();
    void                    SetStatusBar_Impl(sal_uInt32 nResId, SfxShell *pShell, SfxBindings& );
    void                    UpdateStatusBar_Impl();
    ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > GetStatusIndicator();
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > GetFrameInterface();
};

class SfxFrameWorkWin_Impl : public SfxWorkWindow
{
    SfxFrame*           pMasterFrame;
    SfxFrame*           pFrame;
public:
                        SfxFrameWorkWin_Impl( vcl::Window* pWin, SfxFrame* pFrm, SfxFrame* pMaster );
    virtual void        ArrangeChildren_Impl( bool bForce = true ) SAL_OVERRIDE;
    virtual void        UpdateObjectBars_Impl() SAL_OVERRIDE;
    virtual Rectangle   GetTopRect_Impl() SAL_OVERRIDE;
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>SfxChildWin_Impl::nVisibility is of type sal_uInt16/SVX_VISIBILITY_*<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 .
 */
#ifndef INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX
#define INCLUDED_SFX2_SOURCE_INC_WORKWIN_HXX

#include <vector>
#include <deque>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/ui/XUIElement.hpp>
#include <com/sun/star/task/XStatusIndicator.hpp>
#include <com/sun/star/frame/XLayoutManagerListener.hpp>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/propshlp.hxx>

#include <rtl/ustring.hxx>
#include <osl/mutex.hxx>
#include <o3tl/typed_flags_set.hxx>

#include <sfx2/sfx.hrc>
#include <sfx2/childwin.hxx>
#include <sfx2/shell.hxx>
#include <sfx2/ctrlitem.hxx>
#include <sfx2/viewfrm.hxx>

class SfxSplitWindow;
class SfxWorkWindow;

// This struct makes all relevant Informationen available of Toolboxes
struct SfxObjectBar_Impl
{
    sal_uInt16        nId;   // Resource - and ConfigId of Toolbox
    sal_uInt16        nMode; // special visibility flags
    sal_uInt16        nPos;
    sal_uInt16        nIndex;
    bool              bDestroy;
    SfxInterface*     pIFace;

    SfxObjectBar_Impl() :
        nId(0),
        nMode(0),
        nPos(0),
        nIndex(0),
        bDestroy(false),
        pIFace(0)
    {}
};

// This struct makes all relevant Informationen available of the status bar

struct SfxStatBar_Impl
{
    sal_uInt16              nId;
    bool                    bOn;
    bool                    bTemp;

    SfxStatBar_Impl() :
        nId(0),
        bOn(true),
        bTemp(false)
    {}
};

enum class SfxChildVisibility
{
    NOT_VISIBLE  = 0,
    ACTIVE       = 1,   // not disabled through HidePopups
    NOT_HIDDEN   = 2,   // not disabled through HideChildWindow
    FITS_IN      = 4,    // not too large for output size of the parent
    VISIBLE      = 7,   // NOT_HIDDEN | ACTIVE | FITS_IN)
};
namespace o3tl
{
    template<> struct typed_flags<SfxChildVisibility> : is_typed_flags<SfxChildVisibility, 0x07> {};
}

struct SfxChild_Impl
{
    vcl::Window*                     pWin;
    Size                            aSize;
    SfxChildAlignment               eAlign;
    SfxChildVisibility              nVisible;
    bool                            bResize;
    bool                            bCanGetFocus;
    bool                            bSetFocus;

    SfxChild_Impl( vcl::Window& rChild, const Size& rSize,
                   SfxChildAlignment eAlignment, bool bIsVisible ):
        pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(false),
        bCanGetFocus( false ), bSetFocus( false )
    {
        nVisible = bIsVisible ? SfxChildVisibility::VISIBLE : SfxChildVisibility::NOT_VISIBLE;
    }
};

struct SfxChildWin_Impl
{
    sal_uInt16                      nSaveId;       // the ChildWindow-Id
    sal_uInt16                      nInterfaceId;  // the current context
    sal_uInt16                      nId;           // current Id
    SfxChildWindow*                 pWin;
    bool                            bCreate;
    SfxChildWinInfo                 aInfo;
    SfxChild_Impl*                  pCli;          // != 0 at direct Children
    sal_uInt16                      nVisibility;
    bool                            bEnable;
    bool                            bDisabled;

    SfxChildWin_Impl( sal_uInt32 nID ) :
        nSaveId((sal_uInt16) (nID & 0xFFFF) ),
        nInterfaceId((sal_uInt16) (nID >> 16)),
        nId(nSaveId),
        pWin(0),
        bCreate(false),
        pCli(0),
        nVisibility( SFX_VISIBILITY_UNVISIBLE ),
        bEnable( true ),
        bDisabled( false )
    {}
};

enum class SfxChildIdentifier
{
    STATBAR,
    OBJECTBAR,
    DOCKINGWINDOW,
    SPLITWINDOW
};

enum class SfxDockingConfig
{
    SETDOCKINGRECTS,
    ALIGNDOCKINGWINDOW,
    TOGGLEFLOATMODE,
    MOVEDOCKINGWINDOW
};

typedef std::vector<SfxChild_Impl*> SfxChildList_Impl;
typedef std::vector<SfxChildWin_Impl*> SfxChildWindows_Impl;

struct SfxObjectBarList_Impl
{
    std::deque<SfxObjectBar_Impl>   aArr;
    sal_uInt16                  nAct;

    SfxObjectBar_Impl       operator[] ( sal_uInt16 n )
                            { return aArr[n]; }
    SfxObjectBar_Impl       Actual()
                            { return aArr[nAct]; }
};

#define SFX_SPLITWINDOWS_LEFT   0
#define SFX_SPLITWINDOWS_TOP    2
#define SFX_SPLITWINDOWS_RIGHT  1
#define SFX_SPLITWINDOWS_MAX    4

class LayoutManagerListener : public ::cppu::WeakImplHelper2<
                                         css::frame::XLayoutManagerListener,
                                         css::lang::XComponent >
{
    public:
        LayoutManagerListener( SfxWorkWindow* pWrkWin );
        virtual ~LayoutManagerListener();

        void setFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        //  XComponent

        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
        virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

        //  XEventListener

        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw( ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

        // XLayoutManagerEventListener

        virtual void SAL_CALL layoutEvent( const ::com::sun::star::lang::EventObject& aSource, ::sal_Int16 eLayoutEvent, const ::com::sun::star::uno::Any& aInfo ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

    private:
        bool                                                                m_bHasFrame;
        SfxWorkWindow*                                                          m_pWrkWin;
        ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XFrame > m_xFrame;
        OUString                                                           m_aLayoutManagerPropName;
};

class SfxWorkWindow
{
    friend class LayoutManagerListener;

protected:
    std::vector<sal_uInt16> aSortedList;
    SfxStatBar_Impl         aStatBar;
    std::vector< SfxObjectBar_Impl > aObjBarList;
    Rectangle               aClientArea;
    Rectangle               aUpperClientArea;
    SfxWorkWindow*          pParent;
    SfxSplitWindow*         pSplit[SFX_SPLITWINDOWS_MAX];
    SfxChildList_Impl       aChildren;
    SfxChildWindows_Impl    aChildWins;
    SfxBindings*            pBindings;
    vcl::Window*                 pWorkWin;
    SfxShell*               pConfigShell;
    vcl::Window*                 pActiveChild;
    sal_uInt16                  nUpdateMode;
    sal_uInt16                  nChildren;
    sal_uInt16                  nOrigMode;
    bool                    bSorted : 1;
    bool                    bDockingAllowed : 1;
    bool                    bInternalDockingAllowed : 1;
    bool                    bAllChildrenVisible : 1;
    bool                    bIsFullScreen : 1;
    bool                    bShowStatusBar : 1;
    sal_Int32               m_nLock;
    OUString           m_aStatusBarResName;
    OUString           m_aLayoutManagerPropName;
    OUString           m_aTbxTypeName;
    OUString           m_aProgressBarResName;
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xLayoutManagerListener;

protected:
    void                    CreateChildWin_Impl(SfxChildWin_Impl*,bool);
    void                    RemoveChildWin_Impl(SfxChildWin_Impl*);
    void                    Sort_Impl();
    SfxChild_Impl*          FindChild_Impl( const vcl::Window& rWindow ) const;
    bool                    RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual Rectangle       GetTopRect_Impl();
    SvBorder                Arrange_Impl();
    void                    SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
    static bool             IsPluginMode( SfxObjectShell* pObjShell );

public:
                            SfxWorkWindow( vcl::Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL);
    virtual                 ~SfxWorkWindow();
    SfxBindings&            GetBindings()
                            { return *pBindings; }
    vcl::Window*                 GetWindow() const
                            { return pWorkWin; }
    Rectangle               GetFreeArea( bool bAutoHide ) const;
    void                    SetDockingAllowed(bool bSet)
                            { bDockingAllowed = bSet; }
    void                    SetInternalDockingAllowed(bool bSet)
                            { bInternalDockingAllowed = bSet; }
    bool                    IsDockingAllowed() const
                            { return bDockingAllowed; }
    bool                    IsInternalDockingAllowed() const
                            { return bInternalDockingAllowed; }
    SfxWorkWindow*          GetParent_Impl() const
                            { return pParent; }

    // Methods for all Child windows
    void                    DataChanged_Impl( const DataChangedEvent& rDCEvt );
    void                    ReleaseChild_Impl( vcl::Window& rWindow );
    SfxChild_Impl*          RegisterChild_Impl( vcl::Window& rWindow, SfxChildAlignment eAlign, bool bCanGetFocus=false );
    void                    ShowChildren_Impl();
    void                    HideChildren_Impl();
    bool                    PrepareClose_Impl();
    virtual void            ArrangeChildren_Impl( bool bForce = true );
    void                    DeleteControllers_Impl();
    void                    HidePopups_Impl(bool bHide, bool bParent=false, sal_uInt16 nId=0);
    void                    ConfigChild_Impl(SfxChildIdentifier,
                                             SfxDockingConfig, sal_uInt16);
    void                    MakeChildrenVisible_Impl( bool bVis );
    void                    ArrangeAutoHideWindows( SfxSplitWindow *pSplit );
    bool                    IsAutoHideMode( const SfxSplitWindow *pSplit );
    void                    EndAutoShow_Impl( Point aPos );
    void                    SetFullScreen_Impl( bool bSet ) { bIsFullScreen = bSet; }
    bool                    IsFullScreen_Impl() const { return bIsFullScreen; }

    // Methods for Objectbars
    virtual void            UpdateObjectBars_Impl();
    void                    ResetObjectBars_Impl();
    void                    SetObjectBar_Impl(sal_uInt16 nPos, sal_uInt32 nResId,
                                    SfxInterface *pIFace);
    bool                    KnowsObjectBar_Impl( sal_uInt16 nPos ) const;
    bool                    IsVisible_Impl();
    void                    MakeVisible_Impl( bool );
    void                    SetObjectBarVisibility_Impl( sal_uInt16 nVis );
    bool                    IsContainer_Impl() const;
    void                    Lock_Impl( bool );

    // Methods for ChildWindows
    void                    UpdateChildWindows_Impl();
    void                    ResetChildWindows_Impl();
    void                    SetChildWindowVisible_Impl( sal_uInt32, bool, sal_uInt16 );
    void                    ToggleChildWindow_Impl(sal_uInt16,bool);
    bool                    HasChildWindow_Impl(sal_uInt16);
    bool                    KnowsChildWindow_Impl(sal_uInt16);
    void                    ShowChildWindow_Impl(sal_uInt16, bool bVisible, bool bSetFocus);
    void                    SetChildWindow_Impl(sal_uInt16, bool bOn, bool bSetFocus);
    SfxChildWindow*         GetChildWindow_Impl(sal_uInt16);
    void                    InitializeChild_Impl(SfxChildWin_Impl*);
    SfxSplitWindow*         GetSplitWindow_Impl(SfxChildAlignment);

    bool                    IsVisible_Impl( sal_uInt16 nMode ) const;
    bool                    IsFloating( sal_uInt16 nId );
    void                    SetActiveChild_Impl( vcl::Window *pChild );
    bool                    ActivateNextChild_Impl( bool bForward = true );
    bool                    AllowChildWindowCreation_Impl( const SfxChildWin_Impl& i_rCW ) const;

    // Methods for StatusBar
    void                    ResetStatusBar_Impl();
    void                    SetStatusBar_Impl(sal_uInt32 nResId, SfxShell *pShell, SfxBindings& );
    void                    UpdateStatusBar_Impl();
    ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > GetStatusIndicator();
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > GetFrameInterface();
};

class SfxFrameWorkWin_Impl : public SfxWorkWindow
{
    SfxFrame*           pMasterFrame;
    SfxFrame*           pFrame;
public:
                        SfxFrameWorkWin_Impl( vcl::Window* pWin, SfxFrame* pFrm, SfxFrame* pMaster );
    virtual void        ArrangeChildren_Impl( bool bForce = true ) SAL_OVERRIDE;
    virtual void        UpdateObjectBars_Impl() SAL_OVERRIDE;
    virtual Rectangle   GetTopRect_Impl() SAL_OVERRIDE;
};

#endif

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


<commit_before>#include <cassert>
#include <iostream>
#include "CallGraph.h"
#include "FindCalls.h"
#include "IR.h"
#include "Util.h"

namespace Bish {

void Module::set_main(Function *f) {
    add_function(f);
    main = f;
}

void Module::add_function(Function *f) {
    functions.push_back(f);
}

void Module::add_global(Assignment *a) {
    global_variables.push_back(a);
}

void Module::set_path(const std::string &p) {
    path = p;
    namespace_id = remove_suffix(basename(path), ".");
    assert(!namespace_id.empty() && "Unable to resolve namespace identifier.");
}

Function *Module::get_function(const Name &name) const {
    for (std::vector<Function *>::const_iterator I = functions.begin(),
             E = functions.end(); I != E; ++I) {
        if (name.name == (*I)->name.name) {
            return *I;
        }
    }
    return NULL;
}

void Module::import(Module *m) {
    FindCallsToModule find(m);
    accept(&find);
    CallGraphBuilder cgb;
    CallGraph cg = cgb.build(m);

    std::set<Name> to_link = find.functions();
    for (std::set<Name>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
        const Name &name = *I;
        // FindCallsToModule only compares function names to allow the
        // standard library functions to be called without a
        // namespace. Therefore, to_link can contain functions with
        // the same name but belonging to a different namespace. Don't
        // process those here:
        if (!name.namespace_id.empty() && name.namespace_id != m->namespace_id) continue;
        Function *f = m->get_function(name);
        assert(f);
        assert(f->name.namespace_id.empty());
        f->name.namespace_id = m->namespace_id;
        add_function(f);
        // Make sure to pull in functions that f calls as well.
        std::vector<Function *> calls = cg.transitive_calls(f);
        for (std::vector<Function *>::iterator CI = calls.begin(), CE = calls.end(); CI != CE; ++CI) {
            f = *CI;
            // Avoid dummy functions and duplicates.
            if (f->body == NULL || to_link.count(f->name)) continue;
            assert(f->name.namespace_id.empty());
            f->name.namespace_id = m->namespace_id;
            add_function(f);
        }
    }

    // Special case for standard library functions: fix up the
    // function call namespaces. This is so that the user does not
    // have to write, for example, "Stdlib.assert()" in order to call
    // the standard library assert function.
    if (m->path == get_stdlib_path()) {
        std::vector<FunctionCall *> calls = find.function_calls();
        for (std::vector<FunctionCall *>::iterator I = calls.begin(), E = calls.end(); I != E; ++I) {
            FunctionCall *call = *I;
            call->function->name.namespace_id = "StdLib";
        }
    }
}

}
<commit_msg>Update function pointers when importing.<commit_after>#include <cassert>
#include <iostream>
#include "CallGraph.h"
#include "FindCalls.h"
#include "IR.h"
#include "Util.h"

namespace Bish {

void Module::set_main(Function *f) {
    add_function(f);
    main = f;
}

void Module::add_function(Function *f) {
    functions.push_back(f);
}

void Module::add_global(Assignment *a) {
    global_variables.push_back(a);
}

void Module::set_path(const std::string &p) {
    path = p;
    namespace_id = remove_suffix(basename(path), ".");
    assert(!namespace_id.empty() && "Unable to resolve namespace identifier.");
}

Function *Module::get_function(const Name &name) const {
    for (std::vector<Function *>::const_iterator I = functions.begin(),
             E = functions.end(); I != E; ++I) {
        if (name.name == (*I)->name.name) {
            return *I;
        }
    }
    return NULL;
}

void Module::import(Module *m) {
    FindCallsToModule find(m);
    accept(&find);
    CallGraphBuilder cgb;
    CallGraph cg = cgb.build(m);

    std::set<Name> to_link = find.functions();
    std::map<Name, Function *> linked;
    for (std::set<Name>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
        const Name &name = *I;
        // FindCallsToModule only compares function names to allow the
        // standard library functions to be called without a
        // namespace. Therefore, to_link can contain functions with
        // the same name but belonging to a different namespace. Don't
        // process those here:
        if (!name.namespace_id.empty() && name.namespace_id != m->namespace_id) continue;
        Function *f = m->get_function(name);
        assert(f);
        assert(f->name.namespace_id.empty());
        f->name.namespace_id = m->namespace_id;
        add_function(f);
        linked[f->name] = f;
        // Make sure to pull in functions that f calls as well.
        std::vector<Function *> calls = cg.transitive_calls(f);
        for (std::vector<Function *>::iterator CI = calls.begin(), CE = calls.end(); CI != CE; ++CI) {
            f = *CI;
            // Avoid dummy functions and duplicates.
            if (f->body == NULL || to_link.count(f->name)) continue;
            //assert(f->name.namespace_id.empty());
            f->name.namespace_id = m->namespace_id;
            add_function(f);
            linked[f->name] = f;
        }
    }

    // Now patch up the function pointers, replacing the "dummy"
    // functions inserted at parse time with the real functions from
    // the imported module.
    std::vector<FunctionCall *> calls = find.function_calls();
    std::set<Function *> to_erase;
    for (std::vector<FunctionCall *>::iterator I = calls.begin(), E = calls.end(); I != E; ++I) {
        FunctionCall *call = *I;
        Name name = call->function->name;
        // Special case for stdlib functions: they can be called
        // without a namespace, so add it here.
        if (m->path == get_stdlib_path()) {
            call->function->name.namespace_id = "StdLib";
        }
        if (linked.find(name) != linked.end()) {
            assert(call->function->body == NULL);
            to_erase.insert(call->function);
            call->function = linked[name];
        }
    }

    // Finally, erase the old dummy functions.
    for (std::vector<Function *>::iterator I = functions.begin(), E = functions.end(); I != E; ) {
        if (to_erase.find(*I) != to_erase.end()) {
            delete *I;
            I = functions.erase(I);
        } else {
            ++I;
        }
    }
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: admininvokationpage.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 17:36:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX
#include "admininvokationpage.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADMININVOKATIONIMPL_HXX
#include "admininvokationimpl.hxx"
#endif

//.........................................................................
namespace abp
{
//.........................................................................

    //=====================================================================
    //= AdminDialogInvokationPage
    //=====================================================================
    AdminDialogInvokationPage::AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent )
        :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_ADMININVOKATION))
        ,m_aExplanation         (this, ResId(FT_ADMINEXPLANATION))
        ,m_aInvokeAdminDialog   (this, ResId(PB_INVOKE_ADMIN_DIALOG))
        ,m_aErrorMessage        (this, ResId(FT_ERROR))
        ,m_bSuccessfullyExecutedDialog(sal_False)
    {
        FreeResource();

        m_aInvokeAdminDialog.SetClickHdl( LINK(this, AdminDialogInvokationPage, OnInvokeAdminDialog) );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::ActivatePage()
    {
        AddressBookSourcePage::ActivatePage();
        m_aInvokeAdminDialog.GrabFocus();
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::implUpdateErrorMessage()
    {
        const sal_Bool bIsConnected = getDialog()->getDataSource().isConnected();
        m_aErrorMessage.Show( !bIsConnected );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::initializePage()
    {
        AddressBookSourcePage::initializePage();
        m_aErrorMessage.Hide();
            // if we're entering this page, we assume we had no connection trial with this data source
    }

    //---------------------------------------------------------------------
    sal_Bool AdminDialogInvokationPage::commitPage( COMMIT_REASON _eReason )
    {
        return AddressBookSourcePage::commitPage( _eReason );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::implTryConnect()
    {
        sal_Bool bConnected = getDialog()->connectToDataSource( sal_True );

        // show our error message if and only if we could not connect
        implUpdateErrorMessage();

        // the status of the next button may have changed
        implCheckNextButton();

        // automatically go to the next page (if successfully connected)
        if ( determineNextButtonState() )
            getDialog()->travelNext();
    }

    //---------------------------------------------------------------------
    sal_Bool AdminDialogInvokationPage::determineNextButtonState()
    {
        return AddressBookSourcePage::determineNextButtonState() && getDialog()->getDataSource().isConnected();
    }

    //---------------------------------------------------------------------
    IMPL_LINK( AdminDialogInvokationPage, OnInvokeAdminDialog, void*, NOTINTERESTEDIN )
    {
        OAdminDialogInvokation aInvokation( getORB(), getDialog()->getDataSource().getDataSource(), getDialog() );
        if ( aInvokation.invokeAdministration( AST_LDAP == getSettings().eType ) )
        {
            // try to connect to this data source
            implTryConnect();
        }

        return 0L;
    }

//.........................................................................
}   // namespace abp
//.........................................................................

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.222); FILE MERGED 2005/09/05 12:58:31 rt 1.4.222.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: admininvokationpage.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:05:47 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX
#include "admininvokationpage.hxx"
#endif
#ifndef EXTENSIONS_ABSPILOT_HXX
#include "abspilot.hxx"
#endif
#ifndef EXTENSIONS_ABP_ADMININVOKATIONIMPL_HXX
#include "admininvokationimpl.hxx"
#endif

//.........................................................................
namespace abp
{
//.........................................................................

    //=====================================================================
    //= AdminDialogInvokationPage
    //=====================================================================
    AdminDialogInvokationPage::AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent )
        :AddressBookSourcePage(_pParent, ModuleRes(RID_PAGE_ADMININVOKATION))
        ,m_aExplanation         (this, ResId(FT_ADMINEXPLANATION))
        ,m_aInvokeAdminDialog   (this, ResId(PB_INVOKE_ADMIN_DIALOG))
        ,m_aErrorMessage        (this, ResId(FT_ERROR))
        ,m_bSuccessfullyExecutedDialog(sal_False)
    {
        FreeResource();

        m_aInvokeAdminDialog.SetClickHdl( LINK(this, AdminDialogInvokationPage, OnInvokeAdminDialog) );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::ActivatePage()
    {
        AddressBookSourcePage::ActivatePage();
        m_aInvokeAdminDialog.GrabFocus();
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::implUpdateErrorMessage()
    {
        const sal_Bool bIsConnected = getDialog()->getDataSource().isConnected();
        m_aErrorMessage.Show( !bIsConnected );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::initializePage()
    {
        AddressBookSourcePage::initializePage();
        m_aErrorMessage.Hide();
            // if we're entering this page, we assume we had no connection trial with this data source
    }

    //---------------------------------------------------------------------
    sal_Bool AdminDialogInvokationPage::commitPage( COMMIT_REASON _eReason )
    {
        return AddressBookSourcePage::commitPage( _eReason );
    }

    //---------------------------------------------------------------------
    void AdminDialogInvokationPage::implTryConnect()
    {
        sal_Bool bConnected = getDialog()->connectToDataSource( sal_True );

        // show our error message if and only if we could not connect
        implUpdateErrorMessage();

        // the status of the next button may have changed
        implCheckNextButton();

        // automatically go to the next page (if successfully connected)
        if ( determineNextButtonState() )
            getDialog()->travelNext();
    }

    //---------------------------------------------------------------------
    sal_Bool AdminDialogInvokationPage::determineNextButtonState()
    {
        return AddressBookSourcePage::determineNextButtonState() && getDialog()->getDataSource().isConnected();
    }

    //---------------------------------------------------------------------
    IMPL_LINK( AdminDialogInvokationPage, OnInvokeAdminDialog, void*, NOTINTERESTEDIN )
    {
        OAdminDialogInvokation aInvokation( getORB(), getDialog()->getDataSource().getDataSource(), getDialog() );
        if ( aInvokation.invokeAdministration( AST_LDAP == getSettings().eType ) )
        {
            // try to connect to this data source
            implTryConnect();
        }

        return 0L;
    }

//.........................................................................
}   // namespace abp
//.........................................................................

<|endoftext|>


<commit_before>#include "marketorderswidget.hpp"
#include "ui_marketorderswidget.h"

#include <QSqlQuery>
#include <QListIterator>
#include <QPushButton>
#include <QTableWidget>
#include <QtXmlPatterns>
#include <QMovie>
#include "network.hpp"
#include "queries.hpp"
#include "settings.hpp"
#include "global.hpp"

MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::MarketOrdersWidget)
{
  ui->setupUi(this);
  for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) {
    MarketOrdersTable* table = i.next();
    table->setColumnCount(4);
    table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")});
    table->verticalHeader()->hide();
    table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
  }

  refreshOrStopButton = new QPushButton();
  setButtonState(RefreshState);
  ui->tabs->setCornerWidget(refreshOrStopButton);

  typeId = -1;
  connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)),
          this, SLOT(typeDropped(int)));
  connect(refreshOrStopButton, SIGNAL(clicked()),
          this, SLOT(refreshOrStop()));
}

MarketOrdersWidget::~MarketOrdersWidget()
{
  delete ui;
}

void MarketOrdersWidget::typeDropped(int typeId)
{
  this->typeId = typeId;
  QSqlQuery* typeNameQuery = Queries::getTypeNameQuery();
  typeNameQuery->bindValue(":id", typeId);
  typeNameQuery->exec();
  typeNameQuery->next();
  QString typeName = typeNameQuery->value(0).toString();
  ui->typeNameLabel->setText(QString("
%1
").arg(typeName));
  ui->infoButton->init(typeId);

  reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting());
  refreshOrStopButton->show();
  setButtonState(StopState);

  connect(reply, SIGNAL(finished()),
          this, SLOT(replyFinished()));
}

void MarketOrdersWidget::replyFinished()
{
  QString xmlString = reply->readAll();
  reply->deleteLater();
  clearTable(ui->sellOrdersTable);
  clearTable(ui->buyOrdersTable);
  parseReply(xmlString);
  setButtonState(RefreshState);
}

void MarketOrdersWidget::parseReply(const QString& xmlString)
{
  parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders");
  parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders");
}

void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName)
{
  QXmlQuery query;
  query.setFocus(xmlString);
  query.setQuery(QString("for $x in //%1/order \n"
                         "return fn:concat($x/station/text(), \"/\","
                         "                 $x/price/text(), \"/\","
                         "                 $x/vol_remain/text(), \"/\","
                         "                 $x/reported_time/text())").arg(tagName));
  QStringList strlist;
  query.evaluateTo(&strlist);
  for (int i = 0; i < strlist.size(); i++) {
    QStringList splitted = strlist[i].split("/");
    addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(),
                       splitted[2].toInt(), splitted[3]);
  }
}

void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price,
                                     int quantity, QString reportedTime)
{
  QLocale locale(QLocale::English);
  int rowId = table->rowCount();
  table->insertRow(rowId);

  QSqlQuery* stationNameQuery = Queries::getStationNameQuery();
  stationNameQuery->bindValue(":id", stationId);
  stationNameQuery->exec();
  stationNameQuery->next();
  table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString()));
  table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2)));
  table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity)));
  table->setItem(rowId, 3, new QTableWidgetItem(reportedTime));
  for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();)
    table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
}

void MarketOrdersWidget::clearTable(QTableWidget* table)
{
  while (table->rowCount())
    table->removeRow(0);
}

void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state)
{
  buttonState = state;
  switch (state) {
  case RefreshState:
    refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11")));
    break;
  case StopState:
    refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45")));
    break;
  }
}

void MarketOrdersWidget::refreshOrStop()
{
  switch (buttonState) {
  case RefreshState:
    refresh();
    break;
  case StopState:
    stop();
    break;
  }
}

void MarketOrdersWidget::refresh()
{
  typeDropped(typeId);
}

void MarketOrdersWidget::stop()
{
  reply->deleteLater();
  setButtonState(RefreshState);
}
<commit_msg>Fix a bug where the refreshOrStopButton will be shown on startup.<commit_after>#include "marketorderswidget.hpp"
#include "ui_marketorderswidget.h"

#include <QSqlQuery>
#include <QListIterator>
#include <QPushButton>
#include <QTableWidget>
#include <QtXmlPatterns>
#include <QMovie>
#include "network.hpp"
#include "queries.hpp"
#include "settings.hpp"
#include "global.hpp"

MarketOrdersWidget::MarketOrdersWidget(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::MarketOrdersWidget)
{
  ui->setupUi(this);
  for (QListIterator<MarketOrdersTable*> i({ui->sellOrdersTable, ui->buyOrdersTable}); i.hasNext();) {
    MarketOrdersTable* table = i.next();
    table->setColumnCount(4);
    table->setHorizontalHeaderLabels({tr("Station"), tr("Price"), tr("Quantity"), tr("Reported Time")});
    table->verticalHeader()->hide();
    table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
  }

  refreshOrStopButton = new QPushButton();
  setButtonState(RefreshState);
  ui->tabs->setCornerWidget(refreshOrStopButton);
  refreshOrStopButton->hide();

  typeId = -1;
  connect(ui->typePixmapLabel, SIGNAL(typeDropped(int)),
          this, SLOT(typeDropped(int)));
  connect(refreshOrStopButton, SIGNAL(clicked()),
          this, SLOT(refreshOrStop()));
}

MarketOrdersWidget::~MarketOrdersWidget()
{
  delete ui;
}

void MarketOrdersWidget::typeDropped(int typeId)
{
  this->typeId = typeId;
  QSqlQuery* typeNameQuery = Queries::getTypeNameQuery();
  typeNameQuery->bindValue(":id", typeId);
  typeNameQuery->exec();
  typeNameQuery->next();
  QString typeName = typeNameQuery->value(0).toString();
  ui->typeNameLabel->setText(QString("
%1
").arg(typeName));
  ui->infoButton->init(typeId);

  reply = Network::getOrders(typeId, Settings::getMarketOrdersTimeLimitSetting());
  refreshOrStopButton->show();
  setButtonState(StopState);

  connect(reply, SIGNAL(finished()),
          this, SLOT(replyFinished()));
}

void MarketOrdersWidget::replyFinished()
{
  QString xmlString = reply->readAll();
  reply->deleteLater();
  clearTable(ui->sellOrdersTable);
  clearTable(ui->buyOrdersTable);
  parseReply(xmlString);
  setButtonState(RefreshState);
}

void MarketOrdersWidget::parseReply(const QString& xmlString)
{
  parseReplyForTable(xmlString, ui->sellOrdersTable, "sell_orders");
  parseReplyForTable(xmlString, ui->buyOrdersTable, "buy_orders");
}

void MarketOrdersWidget::parseReplyForTable(const QString& xmlString, QTableWidget* table, const QString& tagName)
{
  QXmlQuery query;
  query.setFocus(xmlString);
  query.setQuery(QString("for $x in //%1/order \n"
                         "return fn:concat($x/station/text(), \"/\","
                         "                 $x/price/text(), \"/\","
                         "                 $x/vol_remain/text(), \"/\","
                         "                 $x/reported_time/text())").arg(tagName));
  QStringList strlist;
  query.evaluateTo(&strlist);
  for (int i = 0; i < strlist.size(); i++) {
    QStringList splitted = strlist[i].split("/");
    addTableRow(table, splitted[0].toInt(), splitted[1].toDouble(),
                       splitted[2].toInt(), splitted[3]);
  }
}

void MarketOrdersWidget::addTableRow(QTableWidget* table, int stationId, double price,
                                     int quantity, QString reportedTime)
{
  QLocale locale(QLocale::English);
  int rowId = table->rowCount();
  table->insertRow(rowId);

  QSqlQuery* stationNameQuery = Queries::getStationNameQuery();
  stationNameQuery->bindValue(":id", stationId);
  stationNameQuery->exec();
  stationNameQuery->next();
  table->setItem(rowId, 0, new QTableWidgetItem(stationNameQuery->value(0).toString()));
  table->setItem(rowId, 1, new QTableWidgetItem(locale.toString(price, 'f', 2)));
  table->setItem(rowId, 2, new QTableWidgetItem(locale.toString(quantity)));
  table->setItem(rowId, 3, new QTableWidgetItem(reportedTime));
  for (QListIterator<int> i(QList<int>({1, 2, 3})); i.hasNext();)
    table->item(rowId, i.next())->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
}

void MarketOrdersWidget::clearTable(QTableWidget* table)
{
  while (table->rowCount())
    table->removeRow(0);
}

void MarketOrdersWidget::setButtonState(MarketOrdersWidget::ButtonState state)
{
  buttonState = state;
  switch (state) {
  case RefreshState:
    refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_11")));
    break;
  case StopState:
    refreshOrStopButton->setIcon(QIcon(getIconPixmap("73_16_45")));
    break;
  }
}

void MarketOrdersWidget::refreshOrStop()
{
  switch (buttonState) {
  case RefreshState:
    refresh();
    break;
  case StopState:
    stop();
    break;
  }
}

void MarketOrdersWidget::refresh()
{
  typeDropped(typeId);
}

void MarketOrdersWidget::stop()
{
  reply->deleteLater();
  setButtonState(RefreshState);
}
<|endoftext|>