<commit_before>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "InteractiveNotifications.h"
#include <NotificationActivationCallback.h>

#include <Shellapi.h>
#include <string>
#include <iostream>
#include <SDKDDKVer.h>
#include <Windows.h>
#include <Psapi.h>
#include <strsafe.h>
#include <ShObjIdl.h>
#include <Shlobj.h>
#include <Pathcch.h>
#include <propvarutil.h>
#include <propkey.h>
#include <wchar.h>
#include <wrl.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.ui.notifications.h>

// Correct flow
// RegisterAppForNotificationSupport()
// RegisterActivator()

//  Name:     System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID
//  Type:     Guid -- VT_CLSID
//  FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26
//
//  Used to CoCreate an INotificationActivationCallback interface to notify about toast activations.
EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 };

using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

struct CoTaskMemStringTraits
{
	typedef PWSTR Type;

	inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; }

	inline static Type GetInvalidValue() throw() { return nullptr; }
};
typedef HandleT<CoTaskMemStringTraits> CoTaskMemString;

const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)";

#define __CSID "A23D2B18-8DD7-403A-B9B7-152B40A1478C"

// For the app to be activated from Action Center, it needs to provide a COM server to be called
// when the notification is activated.  The CLSID of the object needs to be registered with the
// OS via its shortcut so that it knows who to call later.
class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal
: public RuntimeClass < RuntimeClassFlags<ClassicCom>,
	INotificationActivationCallback >
{
public:
	virtual HRESULT STDMETHODCALLTYPE Activate(
		_In_ LPCWSTR appUserModelId,
		_In_ LPCWSTR invokedArgs,
		_In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data,
		ULONG dataCount) override
	{
		std::string args;

		for (int i = 0; i < dataCount; i++) {
			LPCWSTR lvalue = data[i].Value;
			LPCWSTR lkey = data[i].Key;

			std::wstring wvalue(lvalue);
			std::wstring wkey(lkey);

			std::string value(wvalue.begin(), wvalue.end());
			std::string key(wkey.begin(), wkey.end());

			args = args + "\"key\":\"" + key + "\"";
			args = args + ",\"value\":\"" + value + "\"";
		}

		std::string escapedArgs = "";
		for (char ch : args) {
			switch (ch) {
			case ' ': escapedArgs += "%20"; break;
			case '&': escapedArgs += "^&"; break;
			case '\\': escapedArgs += "^\\"; break;
			case '<': escapedArgs += "^<"; break;
			case '>': escapedArgs += "^>"; break;
			case '|': escapedArgs += "^|"; break;
			case '^': escapedArgs += "^^"; break;
			case '"': escapedArgs += "^%22"; break;
			default: escapedArgs += ch; break;
			}
		}

		std::wstring wToastArgs(invokedArgs);
		std::string toastArgs(wToastArgs.begin(), wToastArgs.end());

		// CMD needs stuff escaped, so we'll do that here
		std::string escapedToastArgs = "";
		for (char ch : toastArgs) {
			switch (ch) {
			case ' ': escapedToastArgs += "%20"; break;
			case '&': escapedToastArgs += "^&"; break;
			case '\\': escapedToastArgs += "^\\"; break;
			case '<': escapedToastArgs += "^<"; break;
			case '>': escapedToastArgs += "^>"; break;
			case '|': escapedToastArgs += "^|"; break;
			case '^': escapedToastArgs += "^^"; break;
			case '"': escapedToastArgs += "%22"; break;
			default: escapedToastArgs += ch; break;
			}
		}

		std::string cmdLine = "cmd.exe \"start slack://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]\"";
		WinExec(cmdLine.c_str(), SW_HIDE);

		return HRESULT();
	}
};
CoCreatableClass(NotificationActivator);

namespace InteractiveNotifications
{
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
	{
		CoTaskMemString appData;
		auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf());

		if (SUCCEEDED(hr))
		{
			wchar_t shortcutPath[MAX_PATH];
			// Todo: Don't hardcode the path
			hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut);

			if (SUCCEEDED(hr))
			{
				DWORD attributes = ::GetFileAttributes(shortcutPath);
				bool fileExists = attributes < 0xFFFFFFF;

				if (!fileExists)
				{
					// Todo: This is probably the wrong path bc Squirrel
					wchar_t exePath[MAX_PATH];
					DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath));
					hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError());

					if (SUCCEEDED(hr))
					{
						hr = InstallShortcut(shortcutPath, exePath, appId);
						if (SUCCEEDED(hr))
						{
							hr = RegisterComServer(exePath);
						}
					}
				}
			}
		}
		return hr;
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId)
	{
		ComPtr<IShellLink> shellLink;
		HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));

		if (!SUCCEEDED(hr)) return hr;
		hr = shellLink->SetPath(exePath);

		if (!SUCCEEDED(hr)) return hr;
		ComPtr<IPropertyStore> propertyStore;
		hr = shellLink.As(&propertyStore);

		if (!SUCCEEDED(hr)) return hr;
		PROPVARIANT propVar;
		propVar.vt = VT_LPWSTR;
		propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy
		hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar);

		if (!SUCCEEDED(hr)) return hr;
		propVar.vt = VT_CLSID;
		propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator));
		hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar);

		if (!SUCCEEDED(hr)) return hr;
		hr = propertyStore->Commit();

		if (!SUCCEEDED(hr)) return hr;
		ComPtr<IPersistFile> persistFile;
		hr = shellLink.As(&persistFile);

		if (!SUCCEEDED(hr)) return hr;
		hr = persistFile->Save(shortcutPath, TRUE);

		return hr;
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath)
	{
		// We don't need to worry about overflow here as ::GetModuleFileName won't
		// return anything bigger than the max file system path (much fewer than max of DWORD).
		DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR));
		auto key = LR"(SOFTWARE\Classes\CLSID\{A23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)";

		return HRESULT_FROM_WIN32(::RegSetKeyValue(
			HKEY_CURRENT_USER,
			key,
			nullptr,
			REG_SZ,
			reinterpret_cast<const BYTE*>(exePath),
			dataSize));
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator()
	{
		// Module<OutOfProc> needs a callback registered before it can be used.
		// Since we don't care about when it shuts down, we'll pass an empty lambda here.
		// If we need to clean up, do it here (we probably don't have to)
		Module<OutOfProc>::Create([] {});

		// If a local server process only hosts the COM object then COM expects
		// the COM server host to shutdown when the references drop to zero.
		// Since the user might still be using the program after activating the notification,
		// we don't want to shutdown immediately.  Incrementing the object count tells COM that
		// we aren't done yet.
		Module<OutOfProc>::GetModule().IncrementObjectCount();

		return Module<OutOfProc>::GetModule().RegisterObjects();
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API void UnregisterActivator()
	{
		Module<OutOfProc>::GetModule().UnregisterObjects();
		Module<OutOfProc>::GetModule().DecrementObjectCount();
	}
}

extern "C"
{
	__declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
	{
		InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId);
	}

	__declspec(dllexport) void CRegisterActivator()
	{
		InteractiveNotifications::RegisterActivator();
	}

	__declspec(dllexport) void CUnregisterActivator()
	{
		InteractiveNotifications::UnregisterActivator();
	}
}<commit_msg>:wrench: Ooops actually start<commit_after>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "InteractiveNotifications.h"
#include <NotificationActivationCallback.h>

#include <Shellapi.h>
#include <string>
#include <iostream>
#include <SDKDDKVer.h>
#include <Windows.h>
#include <Psapi.h>
#include <strsafe.h>
#include <ShObjIdl.h>
#include <Shlobj.h>
#include <Pathcch.h>
#include <propvarutil.h>
#include <propkey.h>
#include <wchar.h>
#include <wrl.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.ui.notifications.h>

// Correct flow
// RegisterAppForNotificationSupport()
// RegisterActivator()

//  Name:     System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID
//  Type:     Guid -- VT_CLSID
//  FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26
//
//  Used to CoCreate an INotificationActivationCallback interface to notify about toast activations.
EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 };

using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

struct CoTaskMemStringTraits
{
	typedef PWSTR Type;

	inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; }

	inline static Type GetInvalidValue() throw() { return nullptr; }
};
typedef HandleT<CoTaskMemStringTraits> CoTaskMemString;

const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)";

#define __CSID "A23D2B18-8DD7-403A-B9B7-152B40A1478C"

// For the app to be activated from Action Center, it needs to provide a COM server to be called
// when the notification is activated.  The CLSID of the object needs to be registered with the
// OS via its shortcut so that it knows who to call later.
class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal
: public RuntimeClass < RuntimeClassFlags<ClassicCom>,
	INotificationActivationCallback >
{
public:
	virtual HRESULT STDMETHODCALLTYPE Activate(
		_In_ LPCWSTR appUserModelId,
		_In_ LPCWSTR invokedArgs,
		_In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data,
		ULONG dataCount) override
	{
		std::string args;

		for (int i = 0; i < dataCount; i++) {
			LPCWSTR lvalue = data[i].Value;
			LPCWSTR lkey = data[i].Key;

			std::wstring wvalue(lvalue);
			std::wstring wkey(lkey);

			std::string value(wvalue.begin(), wvalue.end());
			std::string key(wkey.begin(), wkey.end());

			args = args + "\"key\":\"" + key + "\"";
			args = args + ",\"value\":\"" + value + "\"";
		}

		std::string escapedArgs = "";
		for (char ch : args) {
			switch (ch) {
			case ' ': escapedArgs += "%20"; break;
			case '&': escapedArgs += "^&"; break;
			case '\\': escapedArgs += "^\\"; break;
			case '<': escapedArgs += "^<"; break;
			case '>': escapedArgs += "^>"; break;
			case '|': escapedArgs += "^|"; break;
			case '^': escapedArgs += "^^"; break;
			case '"': escapedArgs += "^%22"; break;
			default: escapedArgs += ch; break;
			}
		}

		std::wstring wToastArgs(invokedArgs);
		std::string toastArgs(wToastArgs.begin(), wToastArgs.end());

		// CMD needs stuff escaped, so we'll do that here
		std::string escapedToastArgs = "";
		for (char ch : toastArgs) {
			switch (ch) {
			case ' ': escapedToastArgs += "%20"; break;
			case '&': escapedToastArgs += "^&"; break;
			case '\\': escapedToastArgs += "^\\"; break;
			case '<': escapedToastArgs += "^<"; break;
			case '>': escapedToastArgs += "^>"; break;
			case '|': escapedToastArgs += "^|"; break;
			case '^': escapedToastArgs += "^^"; break;
			case '"': escapedToastArgs += "%22"; break;
			default: escapedToastArgs += ch; break;
			}
		}

		std::string cmdLine = "cmd.exe /C \"start slack://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]\"";
		WinExec(cmdLine.c_str(), SW_HIDE);

		return HRESULT();
	}
};
CoCreatableClass(NotificationActivator);

namespace InteractiveNotifications
{
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
	{
		CoTaskMemString appData;
		auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf());

		if (SUCCEEDED(hr))
		{
			wchar_t shortcutPath[MAX_PATH];
			// Todo: Don't hardcode the path
			hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut);

			if (SUCCEEDED(hr))
			{
				DWORD attributes = ::GetFileAttributes(shortcutPath);
				bool fileExists = attributes < 0xFFFFFFF;

				if (!fileExists)
				{
					// Todo: This is probably the wrong path bc Squirrel
					wchar_t exePath[MAX_PATH];
					DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath));
					hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError());

					if (SUCCEEDED(hr))
					{
						hr = InstallShortcut(shortcutPath, exePath, appId);
						if (SUCCEEDED(hr))
						{
							hr = RegisterComServer(exePath);
						}
					}
				}
			}
		}
		return hr;
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId)
	{
		ComPtr<IShellLink> shellLink;
		HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));

		if (!SUCCEEDED(hr)) return hr;
		hr = shellLink->SetPath(exePath);

		if (!SUCCEEDED(hr)) return hr;
		ComPtr<IPropertyStore> propertyStore;
		hr = shellLink.As(&propertyStore);

		if (!SUCCEEDED(hr)) return hr;
		PROPVARIANT propVar;
		propVar.vt = VT_LPWSTR;
		propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy
		hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar);

		if (!SUCCEEDED(hr)) return hr;
		propVar.vt = VT_CLSID;
		propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator));
		hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar);

		if (!SUCCEEDED(hr)) return hr;
		hr = propertyStore->Commit();

		if (!SUCCEEDED(hr)) return hr;
		ComPtr<IPersistFile> persistFile;
		hr = shellLink.As(&persistFile);

		if (!SUCCEEDED(hr)) return hr;
		hr = persistFile->Save(shortcutPath, TRUE);

		return hr;
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath)
	{
		// We don't need to worry about overflow here as ::GetModuleFileName won't
		// return anything bigger than the max file system path (much fewer than max of DWORD).
		DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR));
		auto key = LR"(SOFTWARE\Classes\CLSID\{A23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)";

		return HRESULT_FROM_WIN32(::RegSetKeyValue(
			HKEY_CURRENT_USER,
			key,
			nullptr,
			REG_SZ,
			reinterpret_cast<const BYTE*>(exePath),
			dataSize));
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator()
	{
		// Module<OutOfProc> needs a callback registered before it can be used.
		// Since we don't care about when it shuts down, we'll pass an empty lambda here.
		// If we need to clean up, do it here (we probably don't have to)
		Module<OutOfProc>::Create([] {});

		// If a local server process only hosts the COM object then COM expects
		// the COM server host to shutdown when the references drop to zero.
		// Since the user might still be using the program after activating the notification,
		// we don't want to shutdown immediately.  Incrementing the object count tells COM that
		// we aren't done yet.
		Module<OutOfProc>::GetModule().IncrementObjectCount();

		return Module<OutOfProc>::GetModule().RegisterObjects();
	}

	_Use_decl_annotations_
	INTERACTIVENOTIFICATIONS_API void UnregisterActivator()
	{
		Module<OutOfProc>::GetModule().UnregisterObjects();
		Module<OutOfProc>::GetModule().DecrementObjectCount();
	}
}

extern "C"
{
	__declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
	{
		InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId);
	}

	__declspec(dllexport) void CRegisterActivator()
	{
		InteractiveNotifications::RegisterActivator();
	}

	__declspec(dllexport) void CUnregisterActivator()
	{
		InteractiveNotifications::UnregisterActivator();
	}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XmlFilterAdaptor.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2002-10-10 13:32:48 $
 *
 *  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 EXPRESSED 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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _XMLFILTERADAPTOR_HXX
#define _XMLFILTERADAPTOR_HXX

#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif

enum FilterType
{
    FILTER_IMPORT,
    FILTER_EXPORT
};

/* This component will be instantiated for both import or export. Whether it calls
 * setSourceDocument or setTargetDocument determines which Impl function the filter
 * member calls */

class XmlFilterAdaptor : public cppu::WeakImplHelper5

<

    com::sun::star::document::XFilter,

    com::sun::star::document::XExporter,

    com::sun::star::document::XImporter,

    com::sun::star::lang::XInitialization,

    com::sun::star::lang::XServiceInfo

>

{

protected:

  ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;

  ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc;

  ::rtl::OUString msFilterName;

  ::com::sun::star::uno::Sequence< ::rtl::OUString > msUserData;

   ::rtl::OUString msTemplateName;

    FilterType meType;

    sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

    sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

public:

    XmlFilterAdaptor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF)

        : mxMSF( rxMSF ) {}

    virtual ~XmlFilterAdaptor() {}

    // XFilter

    virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL cancel(  )

        throw (::com::sun::star::uno::RuntimeException);

    // XExporter

    virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )

        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XImporter

    virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )

        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XInitialization

    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )

        throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo

    virtual ::rtl::OUString SAL_CALL getImplementationName(  )

        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )

        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )

        throw (::com::sun::star::uno::RuntimeException);

};

::rtl::OUString XmlFilterAdaptor_getImplementationName()

    throw ( ::com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const ::rtl::OUString& ServiceName )

    throw ( ::com::sun::star::uno::RuntimeException );

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames(  )

    throw ( ::com::sun::star::uno::RuntimeException );

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >

SAL_CALL XmlFilterAdaptor_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)

    throw ( ::com::sun::star::uno::Exception );

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.552); FILE MERGED 2005/09/05 14:31:13 rt 1.4.552.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XmlFilterAdaptor.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:57:58 $
 *
 *  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 _XMLFILTERADAPTOR_HXX
#define _XMLFILTERADAPTOR_HXX

#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif

enum FilterType
{
    FILTER_IMPORT,
    FILTER_EXPORT
};

/* This component will be instantiated for both import or export. Whether it calls
 * setSourceDocument or setTargetDocument determines which Impl function the filter
 * member calls */

class XmlFilterAdaptor : public cppu::WeakImplHelper5

<

    com::sun::star::document::XFilter,

    com::sun::star::document::XExporter,

    com::sun::star::document::XImporter,

    com::sun::star::lang::XInitialization,

    com::sun::star::lang::XServiceInfo

>

{

protected:

  ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;

  ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc;

  ::rtl::OUString msFilterName;

  ::com::sun::star::uno::Sequence< ::rtl::OUString > msUserData;

   ::rtl::OUString msTemplateName;

    FilterType meType;

    sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

    sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

public:

    XmlFilterAdaptor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF)

        : mxMSF( rxMSF ) {}

    virtual ~XmlFilterAdaptor() {}

    // XFilter

    virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )

        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL cancel(  )

        throw (::com::sun::star::uno::RuntimeException);

    // XExporter

    virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )

        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XImporter

    virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )

        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XInitialization

    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )

        throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo

    virtual ::rtl::OUString SAL_CALL getImplementationName(  )

        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )

        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )

        throw (::com::sun::star::uno::RuntimeException);

};

::rtl::OUString XmlFilterAdaptor_getImplementationName()

    throw ( ::com::sun::star::uno::RuntimeException );

sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const ::rtl::OUString& ServiceName )

    throw ( ::com::sun::star::uno::RuntimeException );

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames(  )

    throw ( ::com::sun::star::uno::RuntimeException );

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >

SAL_CALL XmlFilterAdaptor_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)

    throw ( ::com::sun::star::uno::Exception );

#endif

<|endoftext|>


<commit_before>//
// InstanceDlg.cpp
//
// Copyright (c) 2003-2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include <wx/filename.h>

#include "InstanceDlg.h"
#include "vtdata/Content.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// InstanceDlg
//----------------------------------------------------------------------------

// WDR: event table for InstanceDlg

BEGIN_EVENT_TABLE(InstanceDlg, AutoDialog)
	EVT_INIT_DIALOG (InstanceDlg::OnInitDialog)
	EVT_RADIOBUTTON( ID_RADIO_CONTENT, InstanceDlg::OnRadio )
	EVT_RADIOBUTTON( ID_RADIO_MODEL, InstanceDlg::OnRadio )
	EVT_CHOICE( ID_CHOICE_FILE, InstanceDlg::OnChoice )
	EVT_CHOICE( ID_CHOICE_TYPE, InstanceDlg::OnChoice )
	EVT_CHOICE( ID_CHOICE_ITEM, InstanceDlg::OnChoiceItem )
	EVT_BUTTON( ID_BROWSE_MODEL_FILE, InstanceDlg::OnBrowseModelFile )
	EVT_TEXT( ID_LOCATION, InstanceDlg::OnLocationText )
END_EVENT_TABLE()

InstanceDlg::InstanceDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	// WDR: dialog function InstanceDialogFunc for InstanceDlg
	InstanceDialogFunc( this, TRUE );

	m_bContent = true;
	m_iManager = 0;
	m_iItem = 0;

	AddValidator(ID_RADIO_CONTENT, &m_bContent);
	AddValidator(ID_CHOICE_FILE, &m_iManager);
	AddValidator(ID_CHOICE_ITEM, &m_iItem);
}

void InstanceDlg::UpdateLoc()
{
	LinearUnits lu = m_proj.GetUnits();

	wxString str;
	if (lu == LU_DEGREES)
		str.Printf(_T("%lf, %lf"), m_pos.x, m_pos.y);
	else
		str.Printf(_T("%.2lf, %.2lf"), m_pos.x, m_pos.y);
	GetLocation()->SetValue(str);
}

void InstanceDlg::SetLocation(const DPoint2 &pos)
{
	m_pos = pos;
	UpdateLoc();
}

vtTagArray *InstanceDlg::GetTagArray()
{
	m_dummy.Clear();

	// Return a description of the current content item
	if (m_bContent)
	{
		vtContentManager *cman = Current();
		if (!cman)
			return NULL;
		if (m_iItem >= (int) cman->NumItems())
			return NULL;
		vtItem *item = cman->GetItem(m_iItem);
		if (!item)
			return NULL;
		m_dummy.SetValueString("itemname", item->m_name, true);
	}
	else
	{
		wxString str = GetModelFile()->GetValue();
		m_dummy.SetValueString("filename", (const char *) str.mb_str(wxConvUTF8), true);
	}
	return &m_dummy;
}

void InstanceDlg::UpdateEnabling()
{
	GetChoiceFile()->Enable(m_bContent);
	GetChoiceType()->Enable(m_bContent);
	GetChoiceItem()->Enable(m_bContent);

	GetModelFile()->Enable(!m_bContent);
	GetBrowseModelFile()->Enable(!m_bContent);
}

void InstanceDlg::UpdateContentItems()
{
	GetChoiceItem()->Clear();

//	for (int i = 0; i < m_contents.size(); i++)
//	{
		vtContentManager *mng = Current();
		if (!mng)
			return;

		wxString str;
		for (unsigned int j = 0; j < mng->NumItems(); j++)
		{
			vtItem *item = mng->GetItem(j);
			str = wxString(item->m_name, wxConvUTF8);
//			str += _T(" (");
//			str += item->GetValue("filename");
//			str += _T(")");
			GetChoiceItem()->Append(str);
		}
//	}
	GetChoiceItem()->SetSelection(0);
}

void InstanceDlg::ClearContent()
{
	m_contents.clear();
}

void InstanceDlg::AddContent(vtContentManager *mng)
{
	m_contents.push_back(mng);
}

// WDR: handler implementations for InstanceDlg

void InstanceDlg::OnInitDialog(wxInitDialogEvent& event)
{
	GetChoiceFile()->Clear();
	for (unsigned int i = 0; i < m_contents.size(); i++)
	{
		vtContentManager *mng = m_contents[i];
		vtString str = mng->GetFilename();
		wxString ws(str, wxConvUTF8);
		GetChoiceFile()->Append(ws);
	}
	GetChoiceFile()->Select(0);

	GetChoiceType()->Clear();
	GetChoiceType()->Append(_("(All)"));
	GetChoiceType()->Select(0);

	UpdateLoc();
	UpdateEnabling();
	UpdateContentItems();

	wxDialog::OnInitDialog(event);
}

void InstanceDlg::OnLocationText( wxCommandEvent &event )
{
	// todo? only for edit
}

void InstanceDlg::OnBrowseModelFile( wxCommandEvent &event )
{
	wxString filter;
	filter += _("3D Model files");
	filter += _T(" (*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive)|*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive|");
	filter += _("All files");
	filter += _T(" (*.*)|*.*");
	wxFileDialog SelectFile(this, _T("Choose model file"),
							_T(""), _T(""), filter, wxFD_OPEN);
	if (SelectFile.ShowModal() != wxID_OK)
		return;

	// If model file can be found by mimicing the search strategy implemented by
	// vtStructInstance3d::CreateNode then remove the directory part of the path
	// so that paths are not stored unnecessarily
	wxFileName TargetModel(SelectFile.GetPath());
	TargetModel.SetPath(wxT("BuildingModels"));
	vtString FoundModel = FindFileOnPaths(m_DataPaths, TargetModel.GetFullName().mb_str(wxConvUTF8));
	if ("" == FoundModel)
		FoundModel = FindFileOnPaths(m_DataPaths, wxString(TargetModel.GetPath(wxPATH_GET_SEPARATOR) + TargetModel.GetFullName()).mb_str(wxConvUTF8));
	if ("" != FoundModel)
		GetModelFile()->SetValue(TargetModel.GetFullName());
	else
		GetModelFile()->SetValue(TargetModel.GetFullPath());
}

void InstanceDlg::OnChoice( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateContentItems();
}

void InstanceDlg::OnChoiceItem( wxCommandEvent &event )
{
	TransferDataFromWindow();
}

void InstanceDlg::OnRadio( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateEnabling();
}

vtContentManager *InstanceDlg::Current()
{
	if (m_iManager < (int) m_contents.size())
		return m_contents[m_iManager];
	return NULL;
}

<commit_msg>added safety check<commit_after>//
// InstanceDlg.cpp
//
// Copyright (c) 2003-2007 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include <wx/filename.h>

#include "InstanceDlg.h"
#include "vtdata/Content.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// InstanceDlg
//----------------------------------------------------------------------------

// WDR: event table for InstanceDlg

BEGIN_EVENT_TABLE(InstanceDlg, AutoDialog)
	EVT_INIT_DIALOG (InstanceDlg::OnInitDialog)
	EVT_RADIOBUTTON( ID_RADIO_CONTENT, InstanceDlg::OnRadio )
	EVT_RADIOBUTTON( ID_RADIO_MODEL, InstanceDlg::OnRadio )
	EVT_CHOICE( ID_CHOICE_FILE, InstanceDlg::OnChoice )
	EVT_CHOICE( ID_CHOICE_TYPE, InstanceDlg::OnChoice )
	EVT_CHOICE( ID_CHOICE_ITEM, InstanceDlg::OnChoiceItem )
	EVT_BUTTON( ID_BROWSE_MODEL_FILE, InstanceDlg::OnBrowseModelFile )
	EVT_TEXT( ID_LOCATION, InstanceDlg::OnLocationText )
END_EVENT_TABLE()

InstanceDlg::InstanceDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	AutoDialog( parent, id, title, position, size, style )
{
	// WDR: dialog function InstanceDialogFunc for InstanceDlg
	InstanceDialogFunc( this, TRUE );

	m_bContent = true;
	m_iManager = 0;
	m_iItem = 0;

	AddValidator(ID_RADIO_CONTENT, &m_bContent);
	AddValidator(ID_CHOICE_FILE, &m_iManager);
	AddValidator(ID_CHOICE_ITEM, &m_iItem);
}

void InstanceDlg::UpdateLoc()
{
	LinearUnits lu = m_proj.GetUnits();

	wxString str;
	if (lu == LU_DEGREES)
		str.Printf(_T("%lf, %lf"), m_pos.x, m_pos.y);
	else
		str.Printf(_T("%.2lf, %.2lf"), m_pos.x, m_pos.y);
	GetLocation()->SetValue(str);
}

void InstanceDlg::SetLocation(const DPoint2 &pos)
{
	m_pos = pos;
	UpdateLoc();
}

vtTagArray *InstanceDlg::GetTagArray()
{
	if (m_iItem == -1)
		return NULL;

	m_dummy.Clear();

	// Return a description of the current content item
	if (m_bContent)
	{
		vtContentManager *cman = Current();
		if (!cman)
			return NULL;
		if (m_iItem >= (int) cman->NumItems())
			return NULL;
		vtItem *item = cman->GetItem(m_iItem);
		if (!item)
			return NULL;
		m_dummy.SetValueString("itemname", item->m_name, true);
	}
	else
	{
		wxString str = GetModelFile()->GetValue();
		m_dummy.SetValueString("filename", (const char *) str.mb_str(wxConvUTF8), true);
	}
	return &m_dummy;
}

void InstanceDlg::UpdateEnabling()
{
	GetChoiceFile()->Enable(m_bContent);
	GetChoiceType()->Enable(m_bContent);
	GetChoiceItem()->Enable(m_bContent);

	GetModelFile()->Enable(!m_bContent);
	GetBrowseModelFile()->Enable(!m_bContent);
}

void InstanceDlg::UpdateContentItems()
{
	GetChoiceItem()->Clear();

//	for (int i = 0; i < m_contents.size(); i++)
//	{
		vtContentManager *mng = Current();
		if (!mng)
			return;

		wxString str;
		for (unsigned int j = 0; j < mng->NumItems(); j++)
		{
			vtItem *item = mng->GetItem(j);
			str = wxString(item->m_name, wxConvUTF8);
//			str += _T(" (");
//			str += item->GetValue("filename");
//			str += _T(")");
			GetChoiceItem()->Append(str);
		}
//	}
	GetChoiceItem()->SetSelection(0);
}

void InstanceDlg::ClearContent()
{
	m_contents.clear();
}

void InstanceDlg::AddContent(vtContentManager *mng)
{
	m_contents.push_back(mng);
}

// WDR: handler implementations for InstanceDlg

void InstanceDlg::OnInitDialog(wxInitDialogEvent& event)
{
	GetChoiceFile()->Clear();
	for (unsigned int i = 0; i < m_contents.size(); i++)
	{
		vtContentManager *mng = m_contents[i];
		vtString str = mng->GetFilename();
		wxString ws(str, wxConvUTF8);
		GetChoiceFile()->Append(ws);
	}
	GetChoiceFile()->Select(0);

	GetChoiceType()->Clear();
	GetChoiceType()->Append(_("(All)"));
	GetChoiceType()->Select(0);

	UpdateLoc();
	UpdateEnabling();
	UpdateContentItems();

	wxDialog::OnInitDialog(event);
}

void InstanceDlg::OnLocationText( wxCommandEvent &event )
{
	// todo? only for edit
}

void InstanceDlg::OnBrowseModelFile( wxCommandEvent &event )
{
	wxString filter;
	filter += _("3D Model files");
	filter += _T(" (*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive)|*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive|");
	filter += _("All files");
	filter += _T(" (*.*)|*.*");
	wxFileDialog SelectFile(this, _T("Choose model file"),
							_T(""), _T(""), filter, wxFD_OPEN);
	if (SelectFile.ShowModal() != wxID_OK)
		return;

	// If model file can be found by mimicing the search strategy implemented by
	// vtStructInstance3d::CreateNode then remove the directory part of the path
	// so that paths are not stored unnecessarily
	wxFileName TargetModel(SelectFile.GetPath());
	TargetModel.SetPath(wxT("BuildingModels"));
	vtString FoundModel = FindFileOnPaths(m_DataPaths, TargetModel.GetFullName().mb_str(wxConvUTF8));
	if ("" == FoundModel)
		FoundModel = FindFileOnPaths(m_DataPaths, wxString(TargetModel.GetPath(wxPATH_GET_SEPARATOR) + TargetModel.GetFullName()).mb_str(wxConvUTF8));
	if ("" != FoundModel)
		GetModelFile()->SetValue(TargetModel.GetFullName());
	else
		GetModelFile()->SetValue(TargetModel.GetFullPath());
}

void InstanceDlg::OnChoice( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateContentItems();
}

void InstanceDlg::OnChoiceItem( wxCommandEvent &event )
{
	TransferDataFromWindow();
}

void InstanceDlg::OnRadio( wxCommandEvent &event )
{
	TransferDataFromWindow();
	UpdateEnabling();
}

vtContentManager *InstanceDlg::Current()
{
	if (m_iManager < (int) m_contents.size())
		return m_contents[m_iManager];
	return NULL;
}

<|endoftext|>


<commit_before>#include <gmock/gmock.h>

#include <deque>
#include <string>

#include <process/socket.hpp>

#include <stout/gtest.hpp>

#include "decoder.hpp"

using namespace process;
using namespace process::http;

using std::deque;
using std::string;

using process::network::Socket;

TEST(Decoder, Request)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress, gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_EQ("GET", request->method);
  EXPECT_EQ("/path/file.json", request->path);
  EXPECT_EQ("/path/file.json?key1=value1&key2=value2#fragment", request->url);
  EXPECT_EQ("fragment", request->fragment);
  EXPECT_TRUE(request->body.empty());
  EXPECT_FALSE(request->keepAlive);

  EXPECT_EQ(3, request->headers.size());
  EXPECT_SOME_EQ("localhost", request->headers.get("Host"));
  EXPECT_SOME_EQ("close", request->headers.get("Connection"));
  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));

  EXPECT_EQ(2, request->query.size());
  EXPECT_SOME_EQ("value1", request->query.get("key1"));
  EXPECT_SOME_EQ("value2", request->query.get("key2"));

  delete request;
}

TEST(Decoder, RequestHeaderContinuation)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress,"
    "                 gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_SOME_EQ("compress,                 gzip",
                 request->headers.get("Accept-Encoding"));
  delete request;
}

// This is expected to fail for now, see my TODO(bmahler) on http::Request.
TEST(Decoder, DISABLED_RequestHeaderCaseInsensitive)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "cOnnECtioN: close\r\n"
    "accept-ENCODING: compress, gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_FALSE(request->keepAlive);

  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));

  delete request;
}

TEST(Decoder, Response)
{
  ResponseDecoder decoder;

  const string& data =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 2\r\n"
    "\r\n"
    "hi";

  deque<Response*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Response* response = requests[0];

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(Response::BODY, response->type);
  EXPECT_EQ("hi", response->body);

  EXPECT_EQ(3, response->headers.size());

  delete response;
}
<commit_msg>Fixed a copy/paste naming mistake in decoder_tests.cpp.<commit_after>#include <gmock/gmock.h>

#include <deque>
#include <string>

#include <process/socket.hpp>

#include <stout/gtest.hpp>

#include "decoder.hpp"

using namespace process;
using namespace process::http;

using std::deque;
using std::string;

using process::network::Socket;

TEST(Decoder, Request)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress, gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_EQ("GET", request->method);
  EXPECT_EQ("/path/file.json", request->path);
  EXPECT_EQ("/path/file.json?key1=value1&key2=value2#fragment", request->url);
  EXPECT_EQ("fragment", request->fragment);
  EXPECT_TRUE(request->body.empty());
  EXPECT_FALSE(request->keepAlive);

  EXPECT_EQ(3, request->headers.size());
  EXPECT_SOME_EQ("localhost", request->headers.get("Host"));
  EXPECT_SOME_EQ("close", request->headers.get("Connection"));
  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));

  EXPECT_EQ(2, request->query.size());
  EXPECT_SOME_EQ("value1", request->query.get("key1"));
  EXPECT_SOME_EQ("value2", request->query.get("key2"));

  delete request;
}

TEST(Decoder, RequestHeaderContinuation)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress,"
    "                 gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_SOME_EQ("compress,                 gzip",
                 request->headers.get("Accept-Encoding"));
  delete request;
}

// This is expected to fail for now, see my TODO(bmahler) on http::Request.
TEST(Decoder, DISABLED_RequestHeaderCaseInsensitive)
{
  Try<Socket> socket = Socket::create();
  ASSERT_SOME(socket);
  DataDecoder decoder = DataDecoder(socket.get());

  const string& data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "cOnnECtioN: close\r\n"
    "accept-ENCODING: compress, gzip\r\n"
    "\r\n";

  deque<Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, requests.size());

  Request* request = requests[0];
  EXPECT_FALSE(request->keepAlive);

  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));

  delete request;
}

TEST(Decoder, Response)
{
  ResponseDecoder decoder;

  const string& data =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 2\r\n"
    "\r\n"
    "hi";

  deque<Response*> responses = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1, responses.size());

  Response* response = responses[0];

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(Response::BODY, response->type);
  EXPECT_EQ("hi", response->body);

  EXPECT_EQ(3, response->headers.size());

  delete response;
}
<|endoftext|>


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

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

// INCLUDE ---------------------------------------------------------------

#ifndef _SC_XMLTABLESOURCECONTEXT_HXX
#include "XMLTableSourceContext.hxx"
#endif
#ifndef SC_XMLIMPRT_HXX
#include "xmlimprt.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_XMLSUBTI_HXX
#include "xmlsubti.hxx"
#endif
#ifndef SC_TABLINK_HXX
#include "tablink.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XSHEETLINKABLE_HPP_
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#endif

using namespace com::sun::star;
using namespace xmloff::token;

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

ScXMLTableSourceContext::ScXMLTableSourceContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    sLink(),
    sTableName(),
    sFilterName(),
    sFilterOptions(),
    nRefresh(0),
    nMode(sheet::SheetLinkMode_NORMAL)
{
    sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
    for( sal_Int16 i=0; i < nAttrCount; ++i )
    {
        const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
        rtl::OUString aLocalName;
        sal_uInt16 nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName ));
        const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
        if(nPrefix == XML_NAMESPACE_XLINK)
        {
            if (IsXMLToken(aLocalName, XML_HREF))
                sLink = GetScImport().GetAbsoluteReference(sValue);
        }
        else if (nPrefix == XML_NAMESPACE_TABLE)
        {
            if (IsXMLToken(aLocalName, XML_TABLE_NAME))
                sTableName = sValue;
            else if (IsXMLToken(aLocalName, XML_FILTER_NAME))
                sFilterName = sValue;
            else if (IsXMLToken(aLocalName, XML_FILTER_OPTIONS))
                sFilterOptions = sValue;
            else if (IsXMLToken(aLocalName, XML_MODE))
            {
                if (IsXMLToken(sValue, XML_COPY_RESULTS_ONLY))
                    nMode = sheet::SheetLinkMode_VALUE;
            }
            else if (IsXMLToken(aLocalName, XML_REFRESH_DELAY))
            {
                double fTime;
                if( SvXMLUnitConverter::convertTime( fTime, sValue ) )
                    nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 );
            }
        }
    }
}

ScXMLTableSourceContext::~ScXMLTableSourceContext()
{
}

SvXMLImportContext *ScXMLTableSourceContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ )
{
    return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}

void ScXMLTableSourceContext::EndElement()
{
    if (sLink.getLength())
    {
        uno::Reference <sheet::XSheetLinkable> xLinkable (GetScImport().GetTables().GetCurrentXSheet(), uno::UNO_QUERY);
        ScDocument* pDoc(GetScImport().GetDocument());
        if (xLinkable.is() && pDoc)
        {
            GetScImport().LockSolarMutex();
            if (pDoc->RenameTab( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
                GetScImport().GetTables().GetCurrentSheetName(), sal_False, sal_True))
            {
                 String aFileString(sLink);
                String aFilterString(sFilterName);
                String aOptString(sFilterOptions);
                String aSheetString(sTableName);

                aFileString = ScGlobal::GetAbsDocName( aFileString, pDoc->GetDocumentShell() );
                if ( !aFilterString.Len() )
                    ScDocumentLoader::GetFilterName( aFileString, aFilterString, aOptString, FALSE );

                BYTE nLinkMode = SC_LINK_NONE;
                if ( nMode == sheet::SheetLinkMode_NORMAL )
                    nLinkMode = SC_LINK_NORMAL;
                else if ( nMode == sheet::SheetLinkMode_VALUE )
                    nLinkMode = SC_LINK_VALUE;

                pDoc->SetLink( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
                    nLinkMode, aFileString, aFilterString, aOptString,
                    aSheetString, nRefresh );
            }
            GetScImport().UnlockSolarMutex();
        }
    }
}

<commit_msg>INTEGRATION: CWS tl37 (1.13.168); FILE MERGED 2007/04/11 12:36:47 tl 1.13.168.2: RESYNC: (1.13-1.14); FILE MERGED 2007/02/06 19:22:49 nn 1.13.168.1: #i74099# UseInteractionHandler moved out of GuessFilter<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTableSourceContext.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 12:44:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

// INCLUDE ---------------------------------------------------------------

#ifndef _SC_XMLTABLESOURCECONTEXT_HXX
#include "XMLTableSourceContext.hxx"
#endif
#ifndef SC_XMLIMPRT_HXX
#include "xmlimprt.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_XMLSUBTI_HXX
#include "xmlsubti.hxx"
#endif
#ifndef SC_TABLINK_HXX
#include "tablink.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XSHEETLINKABLE_HPP_
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#endif

using namespace com::sun::star;
using namespace xmloff::token;

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

ScXMLTableSourceContext::ScXMLTableSourceContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    sLink(),
    sTableName(),
    sFilterName(),
    sFilterOptions(),
    nRefresh(0),
    nMode(sheet::SheetLinkMode_NORMAL)
{
    sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
    for( sal_Int16 i=0; i < nAttrCount; ++i )
    {
        const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
        rtl::OUString aLocalName;
        sal_uInt16 nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName ));
        const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
        if(nPrefix == XML_NAMESPACE_XLINK)
        {
            if (IsXMLToken(aLocalName, XML_HREF))
                sLink = GetScImport().GetAbsoluteReference(sValue);
        }
        else if (nPrefix == XML_NAMESPACE_TABLE)
        {
            if (IsXMLToken(aLocalName, XML_TABLE_NAME))
                sTableName = sValue;
            else if (IsXMLToken(aLocalName, XML_FILTER_NAME))
                sFilterName = sValue;
            else if (IsXMLToken(aLocalName, XML_FILTER_OPTIONS))
                sFilterOptions = sValue;
            else if (IsXMLToken(aLocalName, XML_MODE))
            {
                if (IsXMLToken(sValue, XML_COPY_RESULTS_ONLY))
                    nMode = sheet::SheetLinkMode_VALUE;
            }
            else if (IsXMLToken(aLocalName, XML_REFRESH_DELAY))
            {
                double fTime;
                if( SvXMLUnitConverter::convertTime( fTime, sValue ) )
                    nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 );
            }
        }
    }
}

ScXMLTableSourceContext::~ScXMLTableSourceContext()
{
}

SvXMLImportContext *ScXMLTableSourceContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ )
{
    return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}

void ScXMLTableSourceContext::EndElement()
{
    if (sLink.getLength())
    {
        uno::Reference <sheet::XSheetLinkable> xLinkable (GetScImport().GetTables().GetCurrentXSheet(), uno::UNO_QUERY);
        ScDocument* pDoc(GetScImport().GetDocument());
        if (xLinkable.is() && pDoc)
        {
            GetScImport().LockSolarMutex();
            if (pDoc->RenameTab( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
                GetScImport().GetTables().GetCurrentSheetName(), sal_False, sal_True))
            {
                 String aFileString(sLink);
                String aFilterString(sFilterName);
                String aOptString(sFilterOptions);
                String aSheetString(sTableName);

                aFileString = ScGlobal::GetAbsDocName( aFileString, pDoc->GetDocumentShell() );
                if ( !aFilterString.Len() )
                    ScDocumentLoader::GetFilterName( aFileString, aFilterString, aOptString, FALSE, FALSE );

                BYTE nLinkMode = SC_LINK_NONE;
                if ( nMode == sheet::SheetLinkMode_NORMAL )
                    nLinkMode = SC_LINK_NORMAL;
                else if ( nMode == sheet::SheetLinkMode_VALUE )
                    nLinkMode = SC_LINK_VALUE;

                pDoc->SetLink( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
                    nLinkMode, aFileString, aFilterString, aOptString,
                    aSheetString, nRefresh );
            }
            GetScImport().UnlockSolarMutex();
        }
    }
}

<|endoftext|>


<commit_before>#include "Component.h"

std::vector<Component*>Component::components;

Component::Component()
	: position(0.f, 0.f, 0.f)
	, isVisible(true)
{
	components.push_back(this);
}
Component::Component(float x, float y, float z)
	: position(x, y, z)
{
	components.push_back(this);
}
Component::~Component()
{
}
<commit_msg>IsVisible dans le deuxieme constructeur de Component<commit_after>#include "Component.h"

std::vector<Component*>Component::components;

Component::Component()
	: position(0.f, 0.f, 0.f)
	, isVisible(true)
{
	components.push_back(this);
}
Component::Component(float x, float y, float z)
	: position(x, y, z)
	, isVisible(true)
{
	components.push_back(this);
}
Component::~Component()
{
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	IP address 定義 @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "common/format.hpp"
#include "common/input.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ip_address クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ip_address {

		union address_t {
			uint32_t	dword;
			uint8_t		bytes[4];  // IPv4 address
			address_t(uint32_t v = 0) : dword(v) { }
			address_t(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) {
				bytes[0] = v0;
				bytes[1] = v1;
				bytes[2] = v2;
				bytes[3] = v3;
			}
		};

		address_t	address_;
		char		str_[4*4+1];

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	dword	32bits IP
		*/
		//-----------------------------------------------------------------//
		ip_address(uint32_t dword = 0) : address_(dword), str_{ 0 } { }

		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	first	IP 1ST
			@param[in]	second	IP 2ND
			@param[in]	third	IP 3RD
			@param[in]	fourth	IP 4TH
		*/
		//-----------------------------------------------------------------//
		ip_address(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) :
			address_(first, second, third, fourth) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  配列から設定
			@param[in]	address	配列
		*/
		//-----------------------------------------------------------------//
		void set(const uint8_t* address) {
			if(address == nullptr) {
				address_ = 0;
				return;
			}
			address_.bytes[0] = address[0];
			address_.bytes[1] = address[1];
			address_.bytes[2] = address[2];
			address_.bytes[3] = address[3];
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  バイト列取得
			@return バイト配列
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get() const { return address_.bytes; }

		//-----------------------------------------------------------------//
		/*!
			@brief  文字列から設定
			@param[in]	address	配列
		*/
		//-----------------------------------------------------------------//
		bool from_string(const char *address) {
			if(address == nullptr) return false;
			int a, b, c, d;
			auto f = (utils::input("%d.%d.%d.%d", address) % a % b % c % d).status();
			if(f) {
				if(a >= 0 && a <= 255) address_.bytes[0] = a;
				if(a >= 0 && b <= 255) address_.bytes[1] = b;
				if(a >= 0 && c <= 255) address_.bytes[2] = c;
				if(a >= 0 && d <= 255) address_.bytes[3] = d;
			}
			return f;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  型変換キャスト演算子（uint32_t 型）
		*/
		//-----------------------------------------------------------------//
		operator uint32_t() const { return address_.dword; };

		bool operator==(const ip_address& addr) const {
			return address_.dword == addr.address_.dword;
		}

		bool operator == (const uint8_t* addr) const {
			if(addr == nullptr) return false;
			return (address_.bytes[0] == addr[0]
				 && address_.bytes[1] == addr[1]
				 && address_.bytes[2] == addr[2]
				 && address_.bytes[3] == addr[3]);
		}

		uint8_t operator [] (int index) const { return address_.bytes[index]; };

		uint8_t& operator [] (int index) { return address_.bytes[index]; };

		ip_address& operator = (const uint8_t* address) {
			address_.bytes[0] = address[0];
			address_.bytes[1] = address[1];
			address_.bytes[2] = address[2];
			address_.bytes[3] = address[3];
			return *this;
		}

		ip_address& operator = (uint32_t address) {
			address_.dword = address;
			return *this;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  文字列で取得
			@param[in]	spch	分離キャラクター（通常「.」）
			@return 文字列
		*/
		//-----------------------------------------------------------------//
		const char* get_str(char spch = '.') {
			utils::format("%d%c%d%c%d%c%d", str_, sizeof(str_))
				% static_cast<int>(address_.bytes[0]) % spch
				% static_cast<int>(address_.bytes[1]) % spch
				% static_cast<int>(address_.bytes[2]) % spch
				% static_cast<int>(address_.bytes[3]);
			return str_;
		}
	};
}

<commit_msg>update api name<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	IP address 定義 @n
			Copyright 2017 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "common/format.hpp"
#include "common/input.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ip_address クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class ip_address {

		union address_t {
			uint32_t	dword;
			uint8_t		bytes[4];  // IPv4 address
			address_t(uint32_t v = 0) : dword(v) { }
			address_t(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) {
				bytes[0] = v0;
				bytes[1] = v1;
				bytes[2] = v2;
				bytes[3] = v3;
			}
		};

		address_t	address_;
		char		str_[4*4+1];

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	dword	32bits IP
		*/
		//-----------------------------------------------------------------//
		ip_address(uint32_t dword = 0) : address_(dword), str_{ 0 } { }

		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	first	IP 1ST
			@param[in]	second	IP 2ND
			@param[in]	third	IP 3RD
			@param[in]	fourth	IP 4TH
		*/
		//-----------------------------------------------------------------//
		ip_address(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) :
			address_(first, second, third, fourth) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  配列から設定
			@param[in]	address	配列
		*/
		//-----------------------------------------------------------------//
		void set(const uint8_t* address) {
			if(address == nullptr) {
				address_ = 0;
				return;
			}
			address_.bytes[0] = address[0];
			address_.bytes[1] = address[1];
			address_.bytes[2] = address[2];
			address_.bytes[3] = address[3];
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  バイト列取得
			@return バイト配列
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get() const { return address_.bytes; }

		//-----------------------------------------------------------------//
		/*!
			@brief  文字列から設定
			@param[in]	address	配列
		*/
		//-----------------------------------------------------------------//
		bool from_string(const char *address) {
			if(address == nullptr) return false;
			int a, b, c, d;
			auto f = (utils::input("%d.%d.%d.%d", address) % a % b % c % d).status();
			if(f) {
				if(a >= 0 && a <= 255) address_.bytes[0] = a;
				if(a >= 0 && b <= 255) address_.bytes[1] = b;
				if(a >= 0 && c <= 255) address_.bytes[2] = c;
				if(a >= 0 && d <= 255) address_.bytes[3] = d;
			}
			return f;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  型変換キャスト演算子（uint32_t 型）
		*/
		//-----------------------------------------------------------------//
		operator uint32_t() const { return address_.dword; };

		bool operator==(const ip_address& addr) const {
			return address_.dword == addr.address_.dword;
		}

		bool operator == (const uint8_t* addr) const {
			if(addr == nullptr) return false;
			return (address_.bytes[0] == addr[0]
				 && address_.bytes[1] == addr[1]
				 && address_.bytes[2] == addr[2]
				 && address_.bytes[3] == addr[3]);
		}

		uint8_t operator [] (int index) const { return address_.bytes[index]; };

		uint8_t& operator [] (int index) { return address_.bytes[index]; };

		ip_address& operator = (const uint8_t* address) {
			address_.bytes[0] = address[0];
			address_.bytes[1] = address[1];
			address_.bytes[2] = address[2];
			address_.bytes[3] = address[3];
			return *this;
		}

		ip_address& operator = (uint32_t address) {
			address_.dword = address;
			return *this;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  文字列で取得
			@param[in]	spch	分離キャラクター（通常「.」）
			@return 文字列
		*/
		//-----------------------------------------------------------------//
		const char* c_str(char spch = '.') {
			utils::format("%d%c%d%c%d%c%d", str_, sizeof(str_))
				% static_cast<int>(address_.bytes[0]) % spch
				% static_cast<int>(address_.bytes[1]) % spch
				% static_cast<int>(address_.bytes[2]) % spch
				% static_cast<int>(address_.bytes[3]);
			return str_;
		}
	};
}

<|endoftext|>


<commit_before>/*
 * BuildingObjectImplementation.cpp
 *
 *  Created on: 23/07/2009
 *      Author: TheAnswer
 */

#include "BuildingObject.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/structure/StructureObject.h"

#include "server/zone/templates/tangible/SharedBuildingObjectTemplate.h"
#include "server/zone/templates/appearance/PortalLayout.h"
#include "server/zone/objects/tangible/terminal/structure/StructureTerminal.h"

#include "server/zone/objects/player/sui/listbox/SuiListBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"

#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/packets/tangible/TangibleObjectMessage3.h"
#include "server/zone/packets/tangible/TangibleObjectMessage6.h"
#include "server/zone/packets/cell/UpdateCellPermissionsMessage.h"
#include "server/zone/objects/scene/components/ContainerComponent.h"
#include "server/zone/managers/object/ObjectManager.h"

void BuildingObjectImplementation::initializeTransientMembers() {
	StructureObjectImplementation::initializeTransientMembers();

	setLoggingName("BuildingObject");
}

void BuildingObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
	StructureObjectImplementation::loadTemplateData(templateData);

	SharedBuildingObjectTemplate* buildingData = dynamic_cast<SharedBuildingObjectTemplate*>(templateData);

	containerVolumeLimit = 0xFFFFFFFF;

	containerType = 2;

	totalCellNumber = buildingData->getTotalCellNumber();
	PortalLayout* portalLayout = templateData->getPortalLayout();

	if (portalLayout != NULL)
		totalCellNumber = portalLayout->getFloorMeshNumber() - 1; //remove the exterior floor

	optionsBitmask = 0x00000100;

	publicStructure = buildingData->isPublicStructure();
}

void BuildingObjectImplementation::createContainerComponent() {
	TangibleObjectImplementation::createContainerComponent();
}

void BuildingObjectImplementation::notifyLoadFromDatabase() {
	SceneObjectImplementation::notifyLoadFromDatabase();

	if (isInQuadTree()) {
		for (int i = 0; i < cells.size(); ++i) {
			CellObject* cell = cells.get(i);

			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* containerObject = cell->getContainerObject(j);

				containerObject->insertToZone(getZone());
			}
		}
	}
}

int BuildingObjectImplementation::getCurrentNumerOfPlayerItems() {
	int items = 0;

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		items += cell->getCurrentNumerOfPlayerItems();
	}

	return items;
}

void BuildingObjectImplementation::createCellObjects() {
	for (int i = 0; i < totalCellNumber; ++i) {
		SceneObject* newCell = getZoneServer()->createObject(0xAD431713, getPersistenceLevel());

		if (!addObject(newCell, -1))
			error("could not add cell");
	}

	updateToDatabase();
}

void BuildingObjectImplementation::sendContainerObjectsTo(SceneObject* player) {
	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		if (cell->getParent() == NULL)
			cell->setParent(_this);

		cell->setCellNumber(i + 1);
		cell->sendTo(player, true);
	}
}

void BuildingObjectImplementation::sendTo(SceneObject* player, bool doClose) {
	info("building sendto..");

	if (!isStaticBuilding()) { // send Baselines etc..
		info("sending building object create");

		SceneObjectImplementation::sendTo(player, doClose);
	} else { // just send the objects that are in the building, without the cells because they are static in the client
		for (int i = 0; i < cells.size(); ++i) {
			CellObject* cell = cells.get(i);

			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* childStub = cell->getContainerObject(j);

				if (!childStub->isInQuadTree())
					childStub->sendTo(player, true);
			}
		}
	}
}

Vector3 BuildingObjectImplementation::getEjectionPoint() {
	/*
	PortalLayout* portalLayout = templateObject->getPortalLayout();

	if (portalLayout == NULL)
		return;

	FloorMesh* floorMesh = portalLayout->getFloorMesh(0);

	if (floorMesh == NULL)
		return;
	 */

	Vector3 ejectionPoint = getWorldPosition();

	float x = ejectionPoint.getX();
	float y = ejectionPoint.getY();

	float halfLength = ((float) (length) * 8.0f) / 2.0f; //Half the length of the structure in meters.
	float radians = getDirection()->getRadians() + Math::deg2rad(270); //Ejection point should be on south side of structure.

	ejectionPoint.setX(x + (Math::cos(radians) * halfLength));
	ejectionPoint.setY(y + (Math::sin(radians) * halfLength));

	return ejectionPoint;
}

void BuildingObjectImplementation::removeFromZone() {
	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		//cell->resetCurrentNumerOfPlayerItems();

		while (cell->getContainerObjectsSize() > 0) {
			ManagedReference<SceneObject*> obj = cell->getContainerObject(0);

			obj->removeFromZone();

			cell->removeObject(obj);

			VectorMap<uint64, ManagedReference<SceneObject*> >* cont = cell->getContainerObjects();

			//cont->drop(obj->getObjectID());

			if (cont->size() > 0) {
				SceneObject* test = cell->getContainerObject(0);

				if (test == obj) {
					cont->remove(0);
				}
			}
		}

		if (signObject != NULL) {
			signObject->removeFromZone();
		}
	}

	TangibleObjectImplementation::removeFromZone();
}

void BuildingObjectImplementation::sendDestroyTo(SceneObject* player) {
	if (!isStaticBuilding()) {
		info("sending building object destroy");

		SceneObjectImplementation::destroy(player->getClient());
	}
}

void BuildingObjectImplementation::sendBaselinesTo(SceneObject* player) {
	//send buios here
	info("sending building baselines");

	BaseMessage* buio3 = new TangibleObjectMessage3(_this);
	player->sendMessage(buio3);

	BaseMessage* buio6 = new TangibleObjectMessage6(_this);
	player->sendMessage(buio6);
}

void BuildingObjectImplementation::notifyInsertToZone(SceneObject* object) {
	//info("BuildingObjectImplementation::notifyInsertToZone");

	for (int i = 0; i < inRangeObjectCount(); ++i) {
		QuadTreeEntry* obj = getInRangeObject(i);

		object->addInRangeObject(obj, true);
		obj->addInRangeObject(object, true);
	}

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		if (isStaticBuilding()) {
			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* child = cell->getContainerObject(j);

				//if (childStub->isInRange(object, 128)) {
				child->addInRangeObject(object, false);

				if (child != object) {
					object->notifyInsert(child);
					//child->sendTo(object, true);
				}

				object->addInRangeObject(child, false);

				if (child != object) {
					//object->sendTo(childStub, true);
					child->notifyInsert(object);
				}

				//}
			}
		}
	}

	object->addInRangeObject(_this, false);
	addInRangeObject(object, false);
	//this->sendTo(object, true);
}

void BuildingObjectImplementation::notifyInsert(QuadTreeEntry* obj) {
	//info("BuildingObjectImplementation::notifyInsert");
	SceneObject* scno = (SceneObject*) obj;

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
			SceneObject* child = cell->getContainerObject(j);

			/*if (childStub->isCreatureObject()
					|| (scno->getRootParent() == _this) && (scno->isInRange(childStub, 128))) {*/

			if (isStaticBuilding()) {
				child->addInRangeObject(obj, false);
				obj->addInRangeObject(child, false);
			}
			//}
		}
	}
}

void BuildingObjectImplementation::notifyDissapear(QuadTreeEntry* obj) {
	SceneObject* scno = (SceneObject*) obj;

	removeNotifiedSentObject(scno);

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
			SceneObject* child = cell->getContainerObject(j);

			child->removeInRangeObject(obj);
			obj->removeInRangeObject(child);
		}
	}
}

void BuildingObjectImplementation::insert(QuadTreeEntry* entry) {
	quadTree->insert(entry);
}

void BuildingObjectImplementation::remove(QuadTreeEntry* entry) {
	if (entry->isInQuadTree())
		quadTree->remove(entry);
}

void BuildingObjectImplementation::update(QuadTreeEntry* entry) {
	quadTree->update(entry);
}

void BuildingObjectImplementation::inRange(QuadTreeEntry* entry, float range) {
	quadTree->inRange(entry, range);
}

void BuildingObjectImplementation::addCell(CellObject* cell) {
	cells.add(cell);

	cell->setCellNumber(cells.size());

	/*if (!addObject(cell, -1))
		error("could not add cell");*/
}

void BuildingObjectImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	StructureObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);

	if (!destroyContainedObjects)
		return;

	ManagedReference<SceneObject*> deed = getZoneServer()->getObject(deedObjectID);

	if (deed != NULL)
		deed->destroyObjectFromDatabase(true);

	if (signObject != NULL)
		signObject->destroyObjectFromDatabase(true);

	//Loop through the cells and delete all objects from the database.
}

void BuildingObjectImplementation::updateCellPermissionsTo(SceneObject* player) {
	/*	if (!player->isInRange(_this, 256))
		return;*/

	bool allowEntry = true;

	if (!isPublicStructure() && (!isOnEntryList(player) && !isOnAccessList(player)))
		allowEntry = false;

	if (isOnBanList(player))
		allowEntry = false;

	//If they don't have permission to be inside, kick them out.
	if (!allowEntry && player->getParentRecursively(SceneObject::BUILDING) == _this) {
		Vector3 ejectionPoint = getEjectionPoint();
		player->teleport(ejectionPoint.getX(), getZone()->getHeight(ejectionPoint.getX(), ejectionPoint.getY()), ejectionPoint.getY(), 0);
	}

	//Always allow privileged players to enter any structure.
	if (player->isPlayerCreature() && ((PlayerCreature*) player)->getPlayerObject()->isPrivileged())
		allowEntry = true;

	for (int i = 0; i < cells.size(); ++i) {
		ManagedReference<CellObject*> cell = getCell(i);

		if (cell == NULL)
			continue;

		BaseMessage* perm = new UpdateCellPermissionsMessage(cell->getObjectID(), allowEntry);
		player->sendMessage(perm);
	}
}

void BuildingObjectImplementation::onEnter(PlayerCreature* player) {
	if (getZone() == NULL)
		return;

	if (isStaticObject())
		return;

	Vector3 ejectionPoint = getEjectionPoint();
	float x = ejectionPoint.getX();
	float y = ejectionPoint.getY();

	if (isinf(x) || isnan(x) || isinf(y) || isnan(y))
		return;

	float z = getZone()->getHeight(x, y);

	//Locker _locker(zone);

	if (isOnBanList(player)) {
		player->teleport(x, z, y, 0);
		return;
	}

	if (!isPublicStructure()) {
		if (!isOnEntryList(player))
			player->teleport(x, z, y, 0);
	} else {
		if (getAccessFee() > 0 && !isOnAccessList(player)) {
			//Send access fee popup menu.

			//Kick the player out.
			player->teleport(x, z, y, 0);
		}
	}
}

uint32 BuildingObjectImplementation::getMaximumNumberOfPlayerItems() {
	SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(templateObject.get());

	if (ssot == NULL)
		return 0;

	uint8 lots = ssot->getLotSize();

	//Buildings that don't cost lots have MAXPLAYERITEMS storage space.
	if (lots == 0)
		return MAXPLAYERITEMS;

	return MIN(MAXPLAYERITEMS, lots * 100);
}

bool BuildingObjectImplementation::addObject(SceneObject* object, int containmentType, bool notifyClient) {
	if (object->isCellObject()) {
		addCell((CellObject*) object);
		//return true;
	}

	return StructureObjectImplementation::addObject(object, containmentType, notifyClient);
}
<commit_msg>[fixed] zone loading<commit_after>/*
 * BuildingObjectImplementation.cpp
 *
 *  Created on: 23/07/2009
 *      Author: TheAnswer
 */

#include "BuildingObject.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/structure/StructureObject.h"

#include "server/zone/templates/tangible/SharedBuildingObjectTemplate.h"
#include "server/zone/templates/appearance/PortalLayout.h"
#include "server/zone/objects/tangible/terminal/structure/StructureTerminal.h"

#include "server/zone/objects/player/sui/listbox/SuiListBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"

#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/packets/tangible/TangibleObjectMessage3.h"
#include "server/zone/packets/tangible/TangibleObjectMessage6.h"
#include "server/zone/packets/cell/UpdateCellPermissionsMessage.h"
#include "server/zone/objects/scene/components/ContainerComponent.h"
#include "server/zone/managers/object/ObjectManager.h"

void BuildingObjectImplementation::initializeTransientMembers() {
	StructureObjectImplementation::initializeTransientMembers();

	setLoggingName("BuildingObject");
}

void BuildingObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
	StructureObjectImplementation::loadTemplateData(templateData);

	SharedBuildingObjectTemplate* buildingData = dynamic_cast<SharedBuildingObjectTemplate*>(templateData);

	containerVolumeLimit = 0xFFFFFFFF;

	containerType = 2;

	totalCellNumber = buildingData->getTotalCellNumber();
	PortalLayout* portalLayout = templateData->getPortalLayout();

	if (portalLayout != NULL)
		totalCellNumber = portalLayout->getFloorMeshNumber() - 1; //remove the exterior floor

	optionsBitmask = 0x00000100;

	publicStructure = buildingData->isPublicStructure();
}

void BuildingObjectImplementation::createContainerComponent() {
	TangibleObjectImplementation::createContainerComponent();
}

void BuildingObjectImplementation::notifyLoadFromDatabase() {
	SceneObjectImplementation::notifyLoadFromDatabase();

	if (isInQuadTree()) {
		for (int i = 0; i < cells.size(); ++i) {
			CellObject* cell = cells.get(i);

			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* containerObject = cell->getContainerObject(j);

				containerObject->insertToZone(getZone());
			}
		}
	}
}

int BuildingObjectImplementation::getCurrentNumerOfPlayerItems() {
	int items = 0;

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		items += cell->getCurrentNumerOfPlayerItems();
	}

	return items;
}

void BuildingObjectImplementation::createCellObjects() {
	for (int i = 0; i < totalCellNumber; ++i) {
		SceneObject* newCell = getZoneServer()->createObject(0xAD431713, getPersistenceLevel());

		if (!addObject(newCell, -1))
			error("could not add cell");
	}

	updateToDatabase();
}

void BuildingObjectImplementation::sendContainerObjectsTo(SceneObject* player) {
	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		if (cell->getParent() == NULL)
			cell->setParent(_this);

		cell->setCellNumber(i + 1);
		cell->sendTo(player, true);
	}
}

void BuildingObjectImplementation::sendTo(SceneObject* player, bool doClose) {
	info("building sendto..");

	if (!isStaticBuilding()) { // send Baselines etc..
		info("sending building object create");

		SceneObjectImplementation::sendTo(player, doClose);
	} else { // just send the objects that are in the building, without the cells because they are static in the client
		for (int i = 0; i < cells.size(); ++i) {
			CellObject* cell = cells.get(i);

			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* childStub = cell->getContainerObject(j);

				if (!childStub->isInQuadTree())
					childStub->sendTo(player, true);
			}
		}
	}
}

Vector3 BuildingObjectImplementation::getEjectionPoint() {
	/*
	PortalLayout* portalLayout = templateObject->getPortalLayout();

	if (portalLayout == NULL)
		return;

	FloorMesh* floorMesh = portalLayout->getFloorMesh(0);

	if (floorMesh == NULL)
		return;
	 */

	Vector3 ejectionPoint = getWorldPosition();

	float x = ejectionPoint.getX();
	float y = ejectionPoint.getY();

	float halfLength = ((float) (length) * 8.0f) / 2.0f; //Half the length of the structure in meters.
	float radians = getDirection()->getRadians() + Math::deg2rad(270); //Ejection point should be on south side of structure.

	ejectionPoint.setX(x + (Math::cos(radians) * halfLength));
	ejectionPoint.setY(y + (Math::sin(radians) * halfLength));

	return ejectionPoint;
}

void BuildingObjectImplementation::removeFromZone() {
	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		//cell->resetCurrentNumerOfPlayerItems();

		while (cell->getContainerObjectsSize() > 0) {
			ManagedReference<SceneObject*> obj = cell->getContainerObject(0);

			obj->removeFromZone();

			cell->removeObject(obj);

			VectorMap<uint64, ManagedReference<SceneObject*> >* cont = cell->getContainerObjects();

			//cont->drop(obj->getObjectID());

			if (cont->size() > 0) {
				SceneObject* test = cell->getContainerObject(0);

				if (test == obj) {
					cont->remove(0);
				}
			}
		}

		if (signObject != NULL) {
			signObject->removeFromZone();
		}
	}

	TangibleObjectImplementation::removeFromZone();
}

void BuildingObjectImplementation::sendDestroyTo(SceneObject* player) {
	if (!isStaticBuilding()) {
		info("sending building object destroy");

		SceneObjectImplementation::destroy(player->getClient());
	}
}

void BuildingObjectImplementation::sendBaselinesTo(SceneObject* player) {
	//send buios here
	info("sending building baselines");

	BaseMessage* buio3 = new TangibleObjectMessage3(_this);
	player->sendMessage(buio3);

	BaseMessage* buio6 = new TangibleObjectMessage6(_this);
	player->sendMessage(buio6);
}

void BuildingObjectImplementation::notifyInsertToZone(SceneObject* object) {
	//info("BuildingObjectImplementation::notifyInsertToZone");

	for (int i = 0; i < inRangeObjectCount(); ++i) {
		QuadTreeEntry* obj = getInRangeObject(i);

		object->addInRangeObject(obj, false);
		obj->addInRangeObject(object, false);
	}

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		if (isStaticBuilding()) {
			for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
				SceneObject* child = cell->getContainerObject(j);

				//if (childStub->isInRange(object, 128)) {
				child->addInRangeObject(object, false);

				if (child != object) {
					object->notifyInsert(child);
					//child->sendTo(object, true);
				}

				object->addInRangeObject(child, false);

				if (child != object) {
					//object->sendTo(childStub, true);
					child->notifyInsert(object);
				}

				//}
			}
		}
	}

	object->addInRangeObject(_this, false);
	addInRangeObject(object, false);
	//this->sendTo(object, true);
}

void BuildingObjectImplementation::notifyInsert(QuadTreeEntry* obj) {
	//info("BuildingObjectImplementation::notifyInsert");
	SceneObject* scno = (SceneObject*) obj;

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
			SceneObject* child = cell->getContainerObject(j);

			/*if (childStub->isCreatureObject()
					|| (scno->getRootParent() == _this) && (scno->isInRange(childStub, 128))) {*/

			if (isStaticBuilding()) {
				child->addInRangeObject(obj, false);
				obj->addInRangeObject(child, false);
			}
			//}
		}
	}
}

void BuildingObjectImplementation::notifyDissapear(QuadTreeEntry* obj) {
	SceneObject* scno = (SceneObject*) obj;

	removeNotifiedSentObject(scno);

	for (int i = 0; i < cells.size(); ++i) {
		CellObject* cell = cells.get(i);

		for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
			SceneObject* child = cell->getContainerObject(j);

			child->removeInRangeObject(obj);
			obj->removeInRangeObject(child);
		}
	}
}

void BuildingObjectImplementation::insert(QuadTreeEntry* entry) {
	quadTree->insert(entry);
}

void BuildingObjectImplementation::remove(QuadTreeEntry* entry) {
	if (entry->isInQuadTree())
		quadTree->remove(entry);
}

void BuildingObjectImplementation::update(QuadTreeEntry* entry) {
	quadTree->update(entry);
}

void BuildingObjectImplementation::inRange(QuadTreeEntry* entry, float range) {
	quadTree->inRange(entry, range);
}

void BuildingObjectImplementation::addCell(CellObject* cell) {
	cells.add(cell);

	cell->setCellNumber(cells.size());

	/*if (!addObject(cell, -1))
		error("could not add cell");*/
}

void BuildingObjectImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	StructureObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);

	if (!destroyContainedObjects)
		return;

	ManagedReference<SceneObject*> deed = getZoneServer()->getObject(deedObjectID);

	if (deed != NULL)
		deed->destroyObjectFromDatabase(true);

	if (signObject != NULL)
		signObject->destroyObjectFromDatabase(true);

	//Loop through the cells and delete all objects from the database.
}

void BuildingObjectImplementation::updateCellPermissionsTo(SceneObject* player) {
	/*	if (!player->isInRange(_this, 256))
		return;*/

	bool allowEntry = true;

	if (!isPublicStructure() && (!isOnEntryList(player) && !isOnAccessList(player)))
		allowEntry = false;

	if (isOnBanList(player))
		allowEntry = false;

	//If they don't have permission to be inside, kick them out.
	if (!allowEntry && player->getParentRecursively(SceneObject::BUILDING) == _this) {
		Vector3 ejectionPoint = getEjectionPoint();
		player->teleport(ejectionPoint.getX(), getZone()->getHeight(ejectionPoint.getX(), ejectionPoint.getY()), ejectionPoint.getY(), 0);
	}

	//Always allow privileged players to enter any structure.
	if (player->isPlayerCreature() && ((PlayerCreature*) player)->getPlayerObject()->isPrivileged())
		allowEntry = true;

	for (int i = 0; i < cells.size(); ++i) {
		ManagedReference<CellObject*> cell = getCell(i);

		if (cell == NULL)
			continue;

		BaseMessage* perm = new UpdateCellPermissionsMessage(cell->getObjectID(), allowEntry);
		player->sendMessage(perm);
	}
}

void BuildingObjectImplementation::onEnter(PlayerCreature* player) {
	if (getZone() == NULL)
		return;

	if (isStaticObject())
		return;

	Vector3 ejectionPoint = getEjectionPoint();
	float x = ejectionPoint.getX();
	float y = ejectionPoint.getY();

	if (isinf(x) || isnan(x) || isinf(y) || isnan(y))
		return;

	float z = getZone()->getHeight(x, y);

	//Locker _locker(zone);

	if (isOnBanList(player)) {
		player->teleport(x, z, y, 0);
		return;
	}

	if (!isPublicStructure()) {
		if (!isOnEntryList(player))
			player->teleport(x, z, y, 0);
	} else {
		if (getAccessFee() > 0 && !isOnAccessList(player)) {
			//Send access fee popup menu.

			//Kick the player out.
			player->teleport(x, z, y, 0);
		}
	}
}

uint32 BuildingObjectImplementation::getMaximumNumberOfPlayerItems() {
	SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(templateObject.get());

	if (ssot == NULL)
		return 0;

	uint8 lots = ssot->getLotSize();

	//Buildings that don't cost lots have MAXPLAYERITEMS storage space.
	if (lots == 0)
		return MAXPLAYERITEMS;

	return MIN(MAXPLAYERITEMS, lots * 100);
}

bool BuildingObjectImplementation::addObject(SceneObject* object, int containmentType, bool notifyClient) {
	if (object->isCellObject()) {
		addCell((CellObject*) object);
		//return true;
	}

	return StructureObjectImplementation::addObject(object, containmentType, notifyClient);
}
<|endoftext|>