<commit_before>#include "NotificationMessages.h"
#include "client_server_lib/module/client_server_module.h"
#include "tunnel_lib/module/tunnel_module.h"

/*******************************************************************************************/
/*                                 NotificationMessage                                     */
/*******************************************************************************************/
NotificationMessage::NotificationMessage(Twainet::Module module, NotificationType type)
	: m_type(type), m_module(module)
{
}

NotificationMessage::~NotificationMessage()
{
}

/*******************************************************************************************/
/*                               ClientServerConnected                                     */
/*******************************************************************************************/
ClientServerConnected::ClientServerConnected(Twainet::Module module, const std::string& sessionId, bool bClient)
	: NotificationMessage(module, bClient ? CLIENT_CONNECTED : SERVER_CONNECTED), m_sessionId(sessionId)
{
}

ClientServerConnected::~ClientServerConnected()
{
}

void ClientServerConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	std::string name;
	if(m_type == SERVER_CONNECTED)
	{
		if(callbacks.OnServerConnected)
			callbacks.OnServerConnected(m_module, m_sessionId.c_str());
		name = ClientServerModule::m_serverIPCName;
	}
	else
	{
		if(callbacks.OnClientConnected)
			callbacks.OnClientConnected(m_module, m_sessionId.c_str());
		name = ClientServerModule::m_clientIPCName;
	}

	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, m_sessionId.c_str());
#else
	strcpy(retName.m_name, name.c_str());
	strcpy(retName.m_host, m_sessionId.c_str());
#endif/*WIN32*/
	callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                   ModuleConnected                                       */
/*******************************************************************************************/
ModuleConnected::ModuleConnected(Twainet::Module module, const std::string& moduleName)
	: NotificationMessage(module, MODULE_CONNECTED), m_moduleName(moduleName)
{
}

ModuleConnected::~ModuleConnected()
{
}

void ModuleConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	IPCObjectName name = IPCObjectName::GetIPCName(m_moduleName);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, name.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, name.conn_id().c_str());
#else
	strcpy(retName.m_name, name.module_name().c_str());
	strcpy(retName.m_host, name.host_name().c_str());
	strcpy(retName.m_connId, name.conn_id().c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleConnected)
		callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                ModuleDisconnected                                       */
/*******************************************************************************************/
ModuleDisconnected::ModuleDisconnected(Twainet::Module module, const std::string& id)
	: NotificationMessage(m_module, MODULE_DISCONNECTED), m_id(id)
{
}

ModuleDisconnected::~ModuleDisconnected()
{
}

void ModuleDisconnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	IPCObjectName idName = IPCObjectName::GetIPCName(m_id);
	if(idName.module_name() == ClientServerModule::m_clientIPCName)
	{
		if(callbacks.OnClientDisconnected)
			callbacks.OnClientDisconnected(m_module, idName.host_name().c_str());
	}
	else if(idName.module_name() == ClientServerModule::m_serverIPCName)
	{
		if(callbacks.OnServerDisconnected)
			callbacks.OnServerDisconnected(m_module);
	}
	else if(idName.module_name() == TunnelModule::m_tunnelIPCName)
	{
		if(callbacks.OnTunnelDisconnected)
			callbacks.OnTunnelDisconnected(m_module, idName.host_name().c_str());
	}

	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy(retName.m_name, idName.module_name().c_str());
	strcpy(retName.m_host, idName.host_name().c_str());
	strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleDisconnected)
		callbacks.OnModuleDisconnected(m_module, retName);
}

/*******************************************************************************************/
/*                                   TunnelConnected                                       */
/*******************************************************************************************/
TunnelConnected::TunnelConnected(Twainet::Module module, const std::string& sessionId, TunnelConnector::TypeConnection type)
	: NotificationMessage(module, TUNNEL_CONNECTED), m_sessionId(sessionId), m_typeConnection(type)
{
}

TunnelConnected::~TunnelConnected()
{
}

void TunnelConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnTunnelConnected)
		callbacks.OnTunnelConnected(m_module, m_sessionId.c_str(), (Twainet::TypeConnection)m_typeConnection);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, TunnelModule::m_tunnelIPCName.c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, m_sessionId.c_str());
#else
	strcpy(retName.m_name, TunnelModule::m_tunnelIPCName.c_str());
	strcpy(retName.m_host, m_sessionId.c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleConnected)
		callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                  ConnectionFailed                                       */
/*******************************************************************************************/
ConnectionFailed::ConnectionFailed(Twainet::Module module, const std::string& id)
	: NotificationMessage(module, MODULE_CONNECT_FAILED), m_id(id)
{
}

ConnectionFailed::~ConnectionFailed()
{
}

void ConnectionFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(m_id == ClientServerModule::m_serverIPCName)
	{
		if(callbacks.OnClientConnectionFailed)
			callbacks.OnClientConnectionFailed(m_module);
	}
	else
	{
		IPCObjectName idName = IPCObjectName::GetIPCName(m_id);
		Twainet::ModuleName retName = {0};
#ifdef WIN32
		strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
		strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
		strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
		strcpy(retName.m_name, idName.module_name().c_str());
		strcpy(retName.m_host, idName.host_name().c_str());
		strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
		if(callbacks.OnModuleConnectionFailed)
			callbacks.OnModuleConnectionFailed(m_module, retName);
	}
}

/*******************************************************************************************/
/*                                      GetMessage                                         */
/*******************************************************************************************/
GettingMessage::GettingMessage(Twainet::Module module, const std::string& messageName, const std::vector<std::string>& path, const std::string& data)
	: NotificationMessage(module, GET_MESSAGE), m_messageName(messageName), m_path(path)
{
	m_data.resize(data.size());
	memcpy((void*)m_data.c_str(), data.c_str(), data.size());
}

GettingMessage::~GettingMessage()
{
}

void GettingMessage::HandleMessage(Twainet::TwainetCallback callbacks)
{
	Twainet::Message msg = {0};
	msg.m_data = m_data.c_str();
	msg.m_dataLen = m_data.size();
	msg.m_typeMessage = m_messageName.c_str();
	IPCObjectName idName = IPCObjectName::GetIPCName(m_path[0]);
#ifdef WIN32
	strcpy_s((char*)msg.m_target.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s((char*)msg.m_target.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s((char*)msg.m_target.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy((char*)msg.m_target.m_name, idName.module_name().c_str());
	strcpy((char*)msg.m_target.m_host, idName.host_name().c_str());
	strcpy((char*)msg.m_target.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/

	if(callbacks.OnMessageRecv)
		callbacks.OnMessageRecv(m_module, msg);
}

/*******************************************************************************************/
/*                                  CreationFailed                                         */
/*******************************************************************************************/
CreationFailed::CreationFailed(Twainet::Module module, CreationFailed::CreationType type)
	: NotificationMessage(module, NotificationType(MODULE_CREATION_FAILED + type))
	, m_type(type)
{
}

CreationFailed::~CreationFailed()
{
}

void CreationFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(m_type == MODULE && callbacks.OnModuleCreationFailed)
		callbacks.OnModuleCreationFailed(m_module);
	if(m_type == SERVER && callbacks.OnServerCreationFailed)
		callbacks.OnServerCreationFailed(m_module);
}

/*******************************************************************************************/
/*                                TunnelCreationFailed                                     */
/*******************************************************************************************/
TunnelCreationFailed::TunnelCreationFailed(Twainet::Module module, const std::string& sessionId)
	: CreationFailed(module, TUNNEL), m_sessionId(sessionId)
{
}

TunnelCreationFailed::~TunnelCreationFailed()
{
}

void TunnelCreationFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnTunnelCreationFailed)
		callbacks.OnTunnelCreationFailed(m_module, m_sessionId.c_str());
}

/*******************************************************************************************/
/*                                        AuthFailed                                       */
/*******************************************************************************************/
AuthFailed::AuthFailed(Twainet::Module module)
	: NotificationMessage(m_module, CLIENT_AUTH_FAILED)
{
}

AuthFailed::~AuthFailed()
{
}

void AuthFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnClientAuthFailed)
		callbacks.OnClientAuthFailed(m_module);
}

/*******************************************************************************************/
/*                           InternalConnectionStatusChanged                               */
/*******************************************************************************************/
InternalConnectionStatusChanged::InternalConnectionStatusChanged(Twainet::Module module, const std::string& moduleName,
								ConnectionStatus status, int port)
	: NotificationMessage(module, INTERNAL_CONNECTION_STATUS), m_moduleName(moduleName)
	, m_status(status), m_port(port)
{
}

InternalConnectionStatusChanged::~InternalConnectionStatusChanged()
{
}

void InternalConnectionStatusChanged::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnInternalConnectionStatusChanged)
		callbacks.OnInternalConnectionStatusChanged(m_module, m_moduleName.c_str(),
							   (Twainet::InternalConnectionStatus)m_status, m_port);
	IPCObjectName idName = IPCObjectName::GetIPCName(m_moduleName);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy(retName.m_name, idName.module_name().c_str());
	strcpy(retName.m_host, idName.host_name().c_str());
	strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
	if((Twainet::InternalConnectionStatus)m_status == Twainet::OPEN && callbacks.OnModuleConnected)
	{
		callbacks.OnModuleConnected(m_module, retName);
	}
	else if((Twainet::InternalConnectionStatus)m_status == Twainet::CLOSE && callbacks.OnModuleDisconnected)
	{
		callbacks.OnModuleDisconnected(m_module, retName);
	}
}

/*******************************************************************************************/
/*                                   ModuleListChanged                                     */
/*******************************************************************************************/
ModuleListChanged::ModuleListChanged(Twainet::Module module)
	: NotificationMessage(module, MODULE_LIST_CHANGED)
{
}
ModuleListChanged::~ModuleListChanged()
{
}

void ModuleListChanged::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnModuleListChanged)
		callbacks.OnModuleListChanged(m_module);
}
<commit_msg>fix module object id in disconnected notification message<commit_after>#include "NotificationMessages.h"
#include "client_server_lib/module/client_server_module.h"
#include "tunnel_lib/module/tunnel_module.h"

/*******************************************************************************************/
/*                                 NotificationMessage                                     */
/*******************************************************************************************/
NotificationMessage::NotificationMessage(Twainet::Module module, NotificationType type)
	: m_type(type), m_module(module)
{
}

NotificationMessage::~NotificationMessage()
{
}

/*******************************************************************************************/
/*                               ClientServerConnected                                     */
/*******************************************************************************************/
ClientServerConnected::ClientServerConnected(Twainet::Module module, const std::string& sessionId, bool bClient)
	: NotificationMessage(module, bClient ? CLIENT_CONNECTED : SERVER_CONNECTED), m_sessionId(sessionId)
{
}

ClientServerConnected::~ClientServerConnected()
{
}

void ClientServerConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	std::string name;
	if(m_type == SERVER_CONNECTED)
	{
		if(callbacks.OnServerConnected)
			callbacks.OnServerConnected(m_module, m_sessionId.c_str());
		name = ClientServerModule::m_serverIPCName;
	}
	else
	{
		if(callbacks.OnClientConnected)
			callbacks.OnClientConnected(m_module, m_sessionId.c_str());
		name = ClientServerModule::m_clientIPCName;
	}

	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, m_sessionId.c_str());
#else
	strcpy(retName.m_name, name.c_str());
	strcpy(retName.m_host, m_sessionId.c_str());
#endif/*WIN32*/
	callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                   ModuleConnected                                       */
/*******************************************************************************************/
ModuleConnected::ModuleConnected(Twainet::Module module, const std::string& moduleName)
	: NotificationMessage(module, MODULE_CONNECTED), m_moduleName(moduleName)
{
}

ModuleConnected::~ModuleConnected()
{
}

void ModuleConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	IPCObjectName name = IPCObjectName::GetIPCName(m_moduleName);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, name.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, name.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, name.conn_id().c_str());
#else
	strcpy(retName.m_name, name.module_name().c_str());
	strcpy(retName.m_host, name.host_name().c_str());
	strcpy(retName.m_connId, name.conn_id().c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleConnected)
		callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                ModuleDisconnected                                       */
/*******************************************************************************************/
ModuleDisconnected::ModuleDisconnected(Twainet::Module module, const std::string& id)
	: NotificationMessage(module, MODULE_DISCONNECTED), m_id(id)
{
}

ModuleDisconnected::~ModuleDisconnected()
{
}

void ModuleDisconnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	IPCObjectName idName = IPCObjectName::GetIPCName(m_id);
	if(idName.module_name() == ClientServerModule::m_clientIPCName)
	{
		if(callbacks.OnClientDisconnected)
			callbacks.OnClientDisconnected(m_module, idName.host_name().c_str());
	}
	else if(idName.module_name() == ClientServerModule::m_serverIPCName)
	{
		if(callbacks.OnServerDisconnected)
			callbacks.OnServerDisconnected(m_module);
	}
	else if(idName.module_name() == TunnelModule::m_tunnelIPCName)
	{
		if(callbacks.OnTunnelDisconnected)
			callbacks.OnTunnelDisconnected(m_module, idName.host_name().c_str());
	}

	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy(retName.m_name, idName.module_name().c_str());
	strcpy(retName.m_host, idName.host_name().c_str());
	strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleDisconnected)
		callbacks.OnModuleDisconnected(m_module, retName);
}

/*******************************************************************************************/
/*                                   TunnelConnected                                       */
/*******************************************************************************************/
TunnelConnected::TunnelConnected(Twainet::Module module, const std::string& sessionId, TunnelConnector::TypeConnection type)
	: NotificationMessage(module, TUNNEL_CONNECTED), m_sessionId(sessionId), m_typeConnection(type)
{
}

TunnelConnected::~TunnelConnected()
{
}

void TunnelConnected::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnTunnelConnected)
		callbacks.OnTunnelConnected(m_module, m_sessionId.c_str(), (Twainet::TypeConnection)m_typeConnection);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, TunnelModule::m_tunnelIPCName.c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, m_sessionId.c_str());
#else
	strcpy(retName.m_name, TunnelModule::m_tunnelIPCName.c_str());
	strcpy(retName.m_host, m_sessionId.c_str());
#endif/*WIN32*/
	if(callbacks.OnModuleConnected)
		callbacks.OnModuleConnected(m_module, retName);
}

/*******************************************************************************************/
/*                                  ConnectionFailed                                       */
/*******************************************************************************************/
ConnectionFailed::ConnectionFailed(Twainet::Module module, const std::string& id)
	: NotificationMessage(module, MODULE_CONNECT_FAILED), m_id(id)
{
}

ConnectionFailed::~ConnectionFailed()
{
}

void ConnectionFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(m_id == ClientServerModule::m_serverIPCName)
	{
		if(callbacks.OnClientConnectionFailed)
			callbacks.OnClientConnectionFailed(m_module);
	}
	else
	{
		IPCObjectName idName = IPCObjectName::GetIPCName(m_id);
		Twainet::ModuleName retName = {0};
#ifdef WIN32
		strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
		strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
		strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
		strcpy(retName.m_name, idName.module_name().c_str());
		strcpy(retName.m_host, idName.host_name().c_str());
		strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
		if(callbacks.OnModuleConnectionFailed)
			callbacks.OnModuleConnectionFailed(m_module, retName);
	}
}

/*******************************************************************************************/
/*                                      GetMessage                                         */
/*******************************************************************************************/
GettingMessage::GettingMessage(Twainet::Module module, const std::string& messageName, const std::vector<std::string>& path, const std::string& data)
	: NotificationMessage(module, GET_MESSAGE), m_messageName(messageName), m_path(path)
{
	m_data.resize(data.size());
	memcpy((void*)m_data.c_str(), data.c_str(), data.size());
}

GettingMessage::~GettingMessage()
{
}

void GettingMessage::HandleMessage(Twainet::TwainetCallback callbacks)
{
	Twainet::Message msg = {0};
	msg.m_data = m_data.c_str();
	msg.m_dataLen = m_data.size();
	msg.m_typeMessage = m_messageName.c_str();
	IPCObjectName idName = IPCObjectName::GetIPCName(m_path[0]);
#ifdef WIN32
	strcpy_s((char*)msg.m_target.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s((char*)msg.m_target.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s((char*)msg.m_target.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy((char*)msg.m_target.m_name, idName.module_name().c_str());
	strcpy((char*)msg.m_target.m_host, idName.host_name().c_str());
	strcpy((char*)msg.m_target.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/

	if(callbacks.OnMessageRecv)
		callbacks.OnMessageRecv(m_module, msg);
}

/*******************************************************************************************/
/*                                  CreationFailed                                         */
/*******************************************************************************************/
CreationFailed::CreationFailed(Twainet::Module module, CreationFailed::CreationType type)
	: NotificationMessage(module, NotificationType(MODULE_CREATION_FAILED + type))
	, m_type(type)
{
}

CreationFailed::~CreationFailed()
{
}

void CreationFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(m_type == MODULE && callbacks.OnModuleCreationFailed)
		callbacks.OnModuleCreationFailed(m_module);
	if(m_type == SERVER && callbacks.OnServerCreationFailed)
		callbacks.OnServerCreationFailed(m_module);
}

/*******************************************************************************************/
/*                                TunnelCreationFailed                                     */
/*******************************************************************************************/
TunnelCreationFailed::TunnelCreationFailed(Twainet::Module module, const std::string& sessionId)
	: CreationFailed(module, TUNNEL), m_sessionId(sessionId)
{
}

TunnelCreationFailed::~TunnelCreationFailed()
{
}

void TunnelCreationFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnTunnelCreationFailed)
		callbacks.OnTunnelCreationFailed(m_module, m_sessionId.c_str());
}

/*******************************************************************************************/
/*                                        AuthFailed                                       */
/*******************************************************************************************/
AuthFailed::AuthFailed(Twainet::Module module)
	: NotificationMessage(m_module, CLIENT_AUTH_FAILED)
{
}

AuthFailed::~AuthFailed()
{
}

void AuthFailed::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnClientAuthFailed)
		callbacks.OnClientAuthFailed(m_module);
}

/*******************************************************************************************/
/*                           InternalConnectionStatusChanged                               */
/*******************************************************************************************/
InternalConnectionStatusChanged::InternalConnectionStatusChanged(Twainet::Module module, const std::string& moduleName,
								ConnectionStatus status, int port)
	: NotificationMessage(module, INTERNAL_CONNECTION_STATUS), m_moduleName(moduleName)
	, m_status(status), m_port(port)
{
}

InternalConnectionStatusChanged::~InternalConnectionStatusChanged()
{
}

void InternalConnectionStatusChanged::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnInternalConnectionStatusChanged)
		callbacks.OnInternalConnectionStatusChanged(m_module, m_moduleName.c_str(),
							   (Twainet::InternalConnectionStatus)m_status, m_port);
	IPCObjectName idName = IPCObjectName::GetIPCName(m_moduleName);
	Twainet::ModuleName retName = {0};
#ifdef WIN32
	strcpy_s(retName.m_name, MAX_NAME_LENGTH, idName.module_name().c_str());
	strcpy_s(retName.m_host, MAX_NAME_LENGTH, idName.host_name().c_str());
	strcpy_s(retName.m_connId, MAX_NAME_LENGTH, idName.conn_id().c_str());
#else
	strcpy(retName.m_name, idName.module_name().c_str());
	strcpy(retName.m_host, idName.host_name().c_str());
	strcpy(retName.m_connId, idName.conn_id().c_str());
#endif/*WIN32*/
	if((Twainet::InternalConnectionStatus)m_status == Twainet::OPEN && callbacks.OnModuleConnected)
	{
		callbacks.OnModuleConnected(m_module, retName);
	}
	else if((Twainet::InternalConnectionStatus)m_status == Twainet::CLOSE && callbacks.OnModuleDisconnected)
	{
		callbacks.OnModuleDisconnected(m_module, retName);
	}
}

/*******************************************************************************************/
/*                                   ModuleListChanged                                     */
/*******************************************************************************************/
ModuleListChanged::ModuleListChanged(Twainet::Module module)
	: NotificationMessage(module, MODULE_LIST_CHANGED)
{
}
ModuleListChanged::~ModuleListChanged()
{
}

void ModuleListChanged::HandleMessage(Twainet::TwainetCallback callbacks)
{
	if(callbacks.OnModuleListChanged)
		callbacks.OnModuleListChanged(m_module);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: client.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:17:27 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <so3/ipobj.hxx>
#include <so3/persist.hxx>
#include <so3/embobj.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

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

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel ) :
    SfxInPlaceClient( pViewShell, pDraw ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    SvEmbeddedObject* pMyObj = GetEmbedObj();
    SvInfoObject* pInfoObj = GetViewShell()->GetViewFrame()->GetObjectShell()->Find( pMyObj );
    SdrOle2Obj* pOle2Obj = NULL;
//  String aName = pMyObj->GetName()->GetName();

    String aName;

    if ( pInfoObj )
        aName = pInfoObj->GetObjName();
    else
        DBG_ERROR( "IP-Object not found :-/" );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestObjAreaPixel( const Rectangle& rObjRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("RequestObjAreaPixel: das ist nicht meine ViewShell");
        SfxInPlaceClient::RequestObjAreaPixel( rObjRect );
        return;
    }

    //  Position anpassen

    Rectangle aRect = rObjRect;
    Window* pWin = pViewSh->GetActiveWin();
    Rectangle aLogicRect( pWin->PixelToLogic( aRect.TopLeft() ),
                            pWin->PixelToLogic( aRect.GetSize() ) );

    BOOL bChange = FALSE;
    SCTAB nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if (pPage)
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
            bChange = TRUE;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
            bChange = TRUE;
        }
    }
    else
        DBG_ERROR("RequestObjAreaPixel: Page ist weg");

        //  wieder in Pixel umrechnen

    if (bChange)
        aRect = Rectangle( pWin->LogicToPixel( aLogicRect.TopLeft() ),
                            pWin->LogicToPixel( aLogicRect.GetSize() ) );

    //  Basisklasse

    SfxInPlaceClient::RequestObjAreaPixel( aRect );

    //  Position und Groesse ins Dokument uebernehmen

    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        //  das ist schon das skalierte Rechteck (wie im Draw-Model)

        Rectangle aOld = pDrawObj->GetLogicRect();
        if ( aLogicRect != aOld )
        {
            //  #56590# Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied
            //  (getrennt fuer Position und Groesse)

            Size aOnePixel = pWin->PixelToLogic( Size(1,1) );
            Size aLogicSize = aLogicRect.GetSize();
            Rectangle aNew = aOld;
            Size aNewSize = aNew.GetSize();

            if ( Abs( aLogicRect.Left() - aOld.Left() ) >= aOnePixel.Width() )
                aNew.SetPos( Point( aLogicRect.Left(), aNew.Top() ) );
            if ( Abs( aLogicRect.Top() - aOld.Top() ) >= aOnePixel.Height() )
                aNew.SetPos( Point( aNew.Left(), aLogicRect.Top() ) );

            if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() )
                aNewSize.Width() = aLogicSize.Width();
            if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() )
                aNewSize.Height() = aLogicSize.Height();
            aNew.SetSize( aNewSize );

            if ( aNew != aOld )                     // veraendert nur, wenn mindestens 1 Pixel
            {
                pDrawObj->SetLogicRect( aNew );

                //  set document modified (SdrModel::SetChanged is not used)
                SfxViewShell* pSfxViewSh = GetViewShell();
                ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
                if (pViewSh)
                    pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }

    //
    //  evtl. scrollen, um Objekt sichtbar zu halten
    //

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged( USHORT nAspect )
{
    SfxInPlaceClient::ViewChanged( nAspect );

    SvEmbeddedObject* pObj = GetEmbedObj();
    Rectangle aObjVisArea = OutputDevice::LogicToLogic( pObj->GetVisArea(),
                                                pObj->GetMapUnit(), MAP_100TH_MM );
    Size aVisSize = aObjVisArea.GetSize();

    //  Groesse ins Dokument uebernehmen

    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();

//      SvClientData* pClientData = GetEnv();
        SvClientData* pClientData = GetClientData();
        if (pClientData)
        {
            Fraction aFractX = pClientData->GetScaleWidth();
            Fraction aFractY = pClientData->GetScaleHeight();
            aFractX *= aVisSize.Width();
            aFractY *= aVisSize.Height();
            aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

                //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
                //  falschen Skalierungen ausgerechnet werden:

            Rectangle aObjArea = aLogicRect;
            aObjArea.SetSize( aObjVisArea.GetSize() );          // Dokument-Groesse vom Server
            pClientData->SetObjArea( aObjArea );
        }

        //  Set size in draw model (scale is recalculated) - only if there was a visible
        //  change (in pixels)

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeViewData()
{
    SfxInPlaceClient::MakeViewData();

    SvClientData* pClientData = GetClientData();
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pClientData && pDrawObj)
    {
        //  Groesse und Scale wie in tabvwshb

        Rectangle aRect = pDrawObj->GetLogicRect();
        Size aDrawSize = aRect.GetSize();
        Size aOleSize = GetEmbedObj()->GetVisArea().GetSize();

            // sichtbarer Ausschnitt wird nur inplace veraendert!
        aRect.SetSize( aOleSize );
        pClientData->SetObjArea( aRect );

        Fraction aScaleWidth (aDrawSize.Width(),  aOleSize.Width() );
        Fraction aScaleHeight(aDrawSize.Height(), aOleSize.Height() );
        aScaleWidth.ReduceInaccurate(10);       // kompatibel zum SdrOle2Obj
        aScaleHeight.ReduceInaccurate(10);
        pClientData->SetSizeScale(aScaleWidth,aScaleHeight);
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

#if 0

//  Mit Optimierung gibt es Abstuerze beim Deaktivieren von Grafik-Image-Objekten

#ifdef WNT
#pragma optimize ( "", off )
#endif

void lcl_ReplaceObject( SdrOle2Obj* pGrafOle, SdrGrafObj* pGrafObj,
                        SfxViewShell* pSfxViewSh )
{
    //  das Ole-Objekt wieder durch das Grafikobjekt ersetzen

    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (pViewSh)
    {
        SdrView* pSdrView = pViewSh->GetSdrView();
        SdrPageView* pPV = pSdrView->GetPageViewPvNum(0);

        if ( pGrafOle )
        {
            SvInPlaceObjectRef aIPObj = pGrafOle->GetObjRef();
            Rectangle          aRect  = pGrafOle->GetLogicRect();

            // #41302# ReplaceObject ohne zu markieren, weil's aus dem
            // MarkListHasChanged heraus gerufen wird
            pSdrView->ReplaceObject( pGrafOle, *pPV, pGrafObj, FALSE );
            pSdrView->EndUndo();
            pGrafObj->SetLogicRect(aRect);
            pGrafObj->SetGraphic(SimDLL::GetGraphic(aIPObj));
        }
        else                            // zwischendurch geloescht ?
        {
            DBG_ERROR("Grafik-Ole-Objekt ist weg");

            pSdrView->EndUndo();        //  damit das Undo nicht offen bleibt
                                        //! anderen Text fuer Undo setzen ???
        }
    }
}

#ifdef WNT
#pragma optimize ( "", on )
#endif

#endif

void __EXPORT ScClient::UIActivate( BOOL bActivate )
{
    SvInPlaceClientRef aIPClient( this );   // nicht aus versehen zwischendrin loeschen

    SfxInPlaceClient::UIActivate(bActivate);

#if 0
    //! remove this along with the pGrafEdit member!

    if ( !bActivate && pGrafEdit )          // wurde eine Grafik bearbeitet?
    {
        SdrOle2Obj* pGrafOle = GetDrawObj();
        SdrGrafObj* pGrafObj = pGrafEdit;
        pGrafEdit = NULL;                   // vor lcl_ReplaceObject

        lcl_ReplaceObject( pGrafOle, pGrafObj, GetViewShell() );
    }
#endif

    if ( !bActivate )       //  Chart-Daten-Hervorhebung aufheben
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
        {
            pViewSh->ClearHighlightRanges();

            //  Move an der ViewShell soll eigentlich vom Sfx gerufen werden, wenn sich
            //  das Frame-Window wegen unterschiedlicher Toolboxen o.ae. verschiebt
            //  (um nicht aus Versehen z.B. Zeichenobjekte zu verschieben, #56515#).
            //  Dieser Mechanismus funktioniert aber momentan nicht, darum hier der Aufruf
            //  per Hand (im Move wird verglichen, ob die Position wirklich geaendert ist).
            pViewSh->ForceMove();
        }
    }
}

<commit_msg>INTEGRATION: CWS mav09 (1.9.82); FILE MERGED 2004/07/16 15:51:00 mba 1.9.82.9: #i27773#: SetObjArea was superfluous 2004/07/15 10:41:07 mba 1.9.82.8: #i27773#: cleaning up todos 2004/07/09 02:21:05 mav 1.9.82.7: RESYNC: (1.9-1.10); FILE MERGED 2004/06/14 14:45:08 mba 1.9.82.6: #i27773#: new handling for resizing of active objects 2004/06/01 08:10:20 mba 1.9.82.5: #i27773#: new embedding API 2004/05/20 19:51:21 mba 1.9.82.4: #i27773#: some API changes 2004/05/16 17:26:39 mba 1.9.82.3: #i27773#: new EmbeddedObjectContainer 2004/05/10 08:09:48 mba 1.9.82.2: #i27773#: let client always connect to object 2004/05/04 14:01:38 mba 1.9.82.1: #i27773#: remove so3<commit_after>/*************************************************************************
 *
 *  $RCSfile: client.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 20:12:30 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

using namespace com::sun::star;

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

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel, SdrOle2Obj* pObj ) :
    SfxInPlaceClient( pViewShell, pDraw, pObj->GetAspect() ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
    SetObject( pObj->GetObjRef() );
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    SdrOle2Obj* pOle2Obj = NULL;
    String aName = GetViewShell()->GetObjectShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xObj );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestNewObjectArea( Rectangle& aLogicRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    BOOL bChange = FALSE;
    USHORT nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if (pPage)
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
            bChange = TRUE;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
            bChange = TRUE;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
            bChange = TRUE;
        }
    }
}

void __EXPORT ScClient::ObjectAreaChanged()
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    //  Position und Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        pDrawObj->SetLogicRect( GetScaledObjArea() );

        //  set document modified (SdrModel::SetChanged is not used)
        // TODO/LATER: is there a reason that this code is not executed in Draw?
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
    }

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    awt::Size aSz = xObj->getVisualAreaSize( GetAspect() );
    MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( GetAspect() ) );
    Size aVisSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aMapUnit, MAP_100TH_MM );

    //  Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();
        Fraction aFractX = GetScaleWidth();
        Fraction aFractY = GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

        //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
        //  falschen Skalierungen ausgerechnet werden:
        //Rectangle aObjArea = aLogicRect;
        //aObjArea.SetSize( aVisSize );          // Dokument-Groesse vom Server
        //SetObjArea( aObjArea );

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

<|endoftext|>


<commit_before>///
/// @file  pi_deleglise_rivat_parallel2.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime
///        counting algorithm with the improvements of Deleglise and
///        Rivat. In this implementation the easy leaves have been
///        split up into clustered easy leaves and sparse easy leaves.
///        This implementation is based on the paper:
///        Tomás Oliveira e Silva, Computing pi(x): the combinatorial
///        method, Revista do DETUA, vol. 4, no. 6, March 2006,
///        pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <balance_S2_load.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>

#include <stdint.h>
#include <algorithm>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low)
{
  next.reserve(size);
  next.push_back(0);

  for (int64_t b = 1; b < size; b++)
  {
    int64_t prime = primes[b];
    int64_t next_multiple = ((low + prime - 1) / prime) * prime;
    next_multiple += prime * (~next_multiple & 1);
    next.push_back(next_multiple);
  }
}

template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
  int64_t segment_size = sieve.size();
  int64_t k = next_multiple;

  for (; k < high; k += prime * 2)
  {
    if (sieve[k - low])
    {
      sieve.unset(k - low);
      cnt_update(counters, k - low, segment_size);
    }
  }
  next_multiple = k;
}

/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
                  int64_t y,
                  int64_t z,
                  int64_t c,
                  int64_t segment_size,
                  int64_t segments_per_thread,
                  int64_t thread_num,
                  int64_t low,
                  int64_t limit,
                  vector<int32_t>& pi,
                  vector<int32_t>& primes,
                  vector<int32_t>& lpf,
                  vector<int32_t>& mu,
                  vector<int64_t>& mu_sum,
                  vector<int64_t>& phi)
{
  low += segment_size * segments_per_thread * thread_num;
  limit = min(low + segment_size * segments_per_thread, limit);
  int64_t pi_y = pi[y];
  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t max_prime = min(isqrt(x / low), y);
  int64_t max_index = pi[max_prime];
  int64_t phi_size = pi[min(isqrt(z), max_prime)] + 1;
  int64_t S2_thread = 0;

  BitSieve sieve(segment_size);
  vector<int32_t> counters(segment_size);
  vector<int64_t> next;
  init_next_multiples(next, primes, phi_size, low);
  phi.resize(phi_size, 0);
  mu_sum.resize(phi_size, 0);

  // Process the segments assigned to the current thread
  for (; low < limit; low += segment_size)
  {
    // Current segment = interval [low, high[
    int64_t high = min(low + segment_size, limit);
    int64_t b = c + 1;

    // check if we need the sieve
    if (c < phi_size)
    {
      sieve.memset(low);

      // phi(y, i) nodes with i <= c do not contribute to S2, so we
      // simply sieve out the multiples of the first c primes
      for (int64_t i = 2; i <= c; i++)
      {
        int64_t k = next[i];
        for (int64_t prime = primes[i]; k < high; k += prime * 2)
          sieve.unset(k - low);
        next[i] = k;
      }

      // Initialize special tree data structure from sieve
      cnt_finit(sieve, counters, segment_size);
    }

    // For c + 1 <= b <= pi_sqrty
    // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
    // which satisfy: low <= (x / n) < high
    for (int64_t end = min(pi_sqrty, max_index); b <= end; b++)
    {
      int64_t prime = primes[b];
      int64_t min_m = max(x / (prime * high), y / prime);
      int64_t max_m = min(x / (prime * low), y);

      if (prime >= max_m)
        goto next_segment;

      for (int64_t m = max_m; m > min_m; m--)
      {
        if (mu[m] != 0 && prime < lpf[m])
        {
          int64_t n = prime * m;
          int64_t count = cnt_query(counters, (x / n) - low);
          int64_t phi_xn = phi[b] + count;
          S2_thread -= mu[m] * phi_xn;
          mu_sum[b] -= mu[m];
        }
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    // For pi_sqrty <= b < pi_y
    // Find all special leaves: n = primes[b] * primes[l]
    // which satisfy: low <= (x / n) < high
    for (int64_t end = min(pi_y, max_index + 1); b < end; b++)
    {
      int64_t prime = primes[b];
      int64_t l = pi[min(x / (prime * low), y)];

      if (prime >= primes[l])
        goto next_segment;

      int64_t min_m = max(x / (prime * high), y / prime);
      min_m = in_between(prime, min_m, y);
      int64_t min_trivial_leaf = pi[min(x / (prime * prime), y)];
      int64_t min_clustered_easy_leaf = pi[min(isqrt(x / prime), y)];
      int64_t min_sparse_easy_leaf = pi[min(z / prime, y)];
      int64_t min_hard_leaf = pi[min_m];

      min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
      min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
      min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);

      // For max(x / primes[b]^2, primes[b]) < primes[l] <= y
      // Find all trivial leaves which satisfy:
      // phi(x / (primes[b] * primes[l]), b - 1) = 1
      if (l > min_trivial_leaf)
      {
        S2_thread += l - min_trivial_leaf;
        l = min_trivial_leaf;
      }

      // For max(sqrt(x / primes[b]), primes[b]) < primes[l] <= x / primes[b]^2
      // Find all clustered easy leaves which satisfy:
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      // And phi(x / n, b - 1) == phi(x / m, b - 1)
      while (l > min_clustered_easy_leaf)
      {
        int64_t n = prime * primes[l];
        int64_t phi_xn = pi[x / n] - b + 2;
        int64_t m = prime * primes[b + phi_xn - 1];
        int64_t l2 = pi[x / m];
        l2 = max(l2, min_clustered_easy_leaf);
        S2_thread += phi_xn * (l - l2);
        l = l2;
      }

      // For max(z / primes[b], primes[b]) < primes[l] <= sqrt(x / primes[b])
      // Find all sparse easy leaves which satisfy:
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      for (; l > min_sparse_easy_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        S2_thread += pi[xn] - b + 2;
      }

      if (b < phi_size)
      {
        // For max(x / (primes[b] * high), primes[b]) < primes[l] <= z / primes[b]
        // Find all hard leaves which satisfy:
        // low <= (x / n) < high
        for (; l > min_hard_leaf; l--)
        {
          int64_t n = prime * primes[l];
          int64_t xn = x / n;
          int64_t count = cnt_query(counters, xn - low);
          int64_t phi_xn = phi[b] + count;
          S2_thread += phi_xn;
          mu_sum[b]++;
        }

        phi[b] += cnt_query(counters, (high - 1) - low);
        cross_off(prime, low, high, next[b], sieve, counters);
      }
    }

    next_segment:;
  }

  return S2_thread;
}

/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
           int64_t y,
           int64_t z,
           int64_t c,
           vector<int32_t>& primes,
           vector<int32_t>& lpf,
           vector<int32_t>& mu,
           int threads)
{
  int64_t limit = z + 1;
  threads = validate_threads(threads, limit);

  int64_t S2_total = 0;
  int64_t low = 1;
  int64_t sqrt_limit = isqrt(limit);
  int64_t logx = max(1, ilog(x));
  int64_t min_segment_size = 1 << 6;
  int64_t segments_per_thread = 1;
  int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
  segment_size = max(segment_size, min_segment_size);
  double relative_standard_deviation = 30;

  vector<int32_t> pi = make_pi(y);
  vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);

  while (low < limit)
  {
    int64_t segments = (limit - low + segment_size - 1) / segment_size;
    threads = in_between(1, threads, segments);
    segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);

    aligned_vector<vector<int64_t> > phi(threads);
    aligned_vector<vector<int64_t> > mu_sum(threads);
    aligned_vector<double> timings(threads);

    #pragma omp parallel for num_threads(threads) reduction(+: S2_total)
    for (int i = 0; i < threads; i++)
    {
      timings[i] = get_wtime();
      S2_total += S2_thread(x, y, z, c, segment_size, segments_per_thread,
          i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);
      timings[i] = get_wtime() - timings[i];
    }

    // Once all threads have finished reconstruct and add the
    // missing contribution of all special leaves. This must
    // be done in order as each thread (i) requires the sum of
    // the phi values from the previous threads.
    //
    for (int i = 0; i < threads; i++)
    {
      for (size_t j = 1; j < phi[i].size(); j++)
      {
        S2_total += phi_total[j] * mu_sum[i][j];
        phi_total[j] += phi[i][j];
      }
    }

    low += segments_per_thread * threads * segment_size;
    balance_S2_load(&segment_size, &segments_per_thread, min_segment_size,
        sqrt_limit, &relative_standard_deviation, timings);
  }

  return S2_total;
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads)
{
  if (x < 2)
    return 0;

  // alpha is a tuning factor
  double d = (double) x;
  double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = x / y;

  vector<int32_t> mu = make_moebius(y);
  vector<int32_t> lpf = make_least_prime_factor(y);
  vector<int32_t> primes;
  primes.push_back(0);
  primesieve::generate_primes(y, &primes);

  int64_t pi_y = pi_bsearch(primes, y);
  int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
  int64_t s1 = S1(x, y, c, primes, lpf , mu);
  int64_t s2 = S2(x, y, z, c, primes, lpf , mu, threads);
  int64_t p2 = P2(x, y, threads);
  int64_t phi = s1 + s2;
  int64_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace primecount
<commit_msg>Refactoring<commit_after>///
/// @file  pi_deleglise_rivat_parallel2.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime
///        counting algorithm with the improvements of Deleglise and
///        Rivat. In this implementation the easy leaves have been
///        split up into clustered easy leaves and sparse easy leaves.
///        This implementation is based on the paper:
///        Tomás Oliveira e Silva, Computing pi(x): the combinatorial
///        method, Revista do DETUA, vol. 4, no. 6, March 2006,
///        pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <balance_S2_load.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>

#include <stdint.h>
#include <algorithm>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low)
{
  next.reserve(size);
  next.push_back(0);

  for (int64_t b = 1; b < size; b++)
  {
    int64_t prime = primes[b];
    int64_t next_multiple = ((low + prime - 1) / prime) * prime;
    next_multiple += prime * (~next_multiple & 1);
    next.push_back(next_multiple);
  }
}

template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
  int64_t segment_size = sieve.size();
  int64_t k = next_multiple;

  for (; k < high; k += prime * 2)
  {
    if (sieve[k - low])
    {
      sieve.unset(k - low);
      cnt_update(counters, k - low, segment_size);
    }
  }
  next_multiple = k;
}

/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
                  int64_t y,
                  int64_t z,
                  int64_t c,
                  int64_t segment_size,
                  int64_t segments_per_thread,
                  int64_t thread_num,
                  int64_t low,
                  int64_t limit,
                  vector<int32_t>& pi,
                  vector<int32_t>& primes,
                  vector<int32_t>& lpf,
                  vector<int32_t>& mu,
                  vector<int64_t>& mu_sum,
                  vector<int64_t>& phi)
{
  low += segment_size * segments_per_thread * thread_num;
  limit = min(low + segment_size * segments_per_thread, limit);
  int64_t pi_y = pi[y];
  int64_t pi_sqrty = pi[isqrt(y)];
  int64_t max_prime = min(isqrt(x / low), y);
  int64_t max_index = pi[max_prime];
  int64_t phi_size = pi[min(isqrt(z), max_prime)] + 1;
  int64_t S2_thread = 0;

  BitSieve sieve(segment_size);
  vector<int32_t> counters(segment_size);
  vector<int64_t> next;
  init_next_multiples(next, primes, phi_size, low);
  phi.resize(phi_size, 0);
  mu_sum.resize(phi_size, 0);

  // Process the segments assigned to the current thread
  for (; low < limit; low += segment_size)
  {
    // Current segment = interval [low, high[
    int64_t high = min(low + segment_size, limit);
    int64_t b = c + 1;

    // check if we need the sieve
    if (c < phi_size)
    {
      sieve.memset(low);

      // phi(y, i) nodes with i <= c do not contribute to S2, so we
      // simply sieve out the multiples of the first c primes
      for (int64_t i = 2; i <= c; i++)
      {
        int64_t k = next[i];
        for (int64_t prime = primes[i]; k < high; k += prime * 2)
          sieve.unset(k - low);
        next[i] = k;
      }

      // Initialize special tree data structure from sieve
      cnt_finit(sieve, counters, segment_size);
    }

    // For c + 1 <= b <= pi_sqrty
    // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
    // which satisfy: low <= (x / n) < high
    for (int64_t end = min(pi_sqrty, max_index); b <= end; b++)
    {
      int64_t prime = primes[b];
      int64_t min_m = max(x / (prime * high), y / prime);
      int64_t max_m = min(x / (prime * low), y);

      if (prime >= max_m)
        goto next_segment;

      for (int64_t m = max_m; m > min_m; m--)
      {
        if (mu[m] != 0 && prime < lpf[m])
        {
          int64_t n = prime * m;
          int64_t count = cnt_query(counters, (x / n) - low);
          int64_t phi_xn = phi[b] + count;
          S2_thread -= mu[m] * phi_xn;
          mu_sum[b] -= mu[m];
        }
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    // For pi_sqrty <= b < pi_y
    // Find all special leaves: n = primes[b] * primes[l]
    // which satisfy: low <= (x / n) < high
    for (int64_t end = min(pi_y, max_index + 1); b < end; b++)
    {
      int64_t prime = primes[b];
      int64_t l = pi[min(x / (prime * low), y)];

      if (prime >= primes[l])
        goto next_segment;

      int64_t min_hard_leaf = max(x / (prime * high), y / prime);
      min_hard_leaf = in_between(prime, min_hard_leaf, y);
      int64_t min_trivial_leaf = min(x / (prime * prime), y);
      int64_t min_clustered_easy_leaf = min(isqrt(x / prime), y);
      int64_t min_sparse_easy_leaf = min(z / prime, y);

      min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
      min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
      min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);

      // Find all trivial leaves which satisfy:
      // phi(x / (primes[b] * primes[l]), b - 1) = 1
      if (primes[l] > min_trivial_leaf)
      {
        int64_t l_min = pi[min_trivial_leaf];
        S2_thread += l - l_min;
        l = l_min;
      }

      // Find all clustered easy leaves which satisfy:
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      // And phi(x / n, b - 1) == phi(x / m, b - 1)
      while (primes[l] > min_clustered_easy_leaf)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        int64_t phi_xn = pi[xn] - b + 2;
        int64_t m = prime * primes[b + phi_xn - 1];
        int64_t xm = max(x / m, min_clustered_easy_leaf);
        int64_t l2 = pi[xm];
        S2_thread += phi_xn * (l - l2);
        l = l2;
      }

      // Find all sparse easy leaves which satisfy:
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      for (; primes[l] > min_sparse_easy_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        S2_thread += pi[xn] - b + 2;
      }

      if (b < phi_size)
      {
        // Find all hard leaves which satisfy:
        // low <= (x / n) < high
        for (; primes[l] > min_hard_leaf; l--)
        {
          int64_t n = prime * primes[l];
          int64_t xn = x / n;
          int64_t count = cnt_query(counters, xn - low);
          int64_t phi_xn = phi[b] + count;
          S2_thread += phi_xn;
          mu_sum[b]++;
        }

        phi[b] += cnt_query(counters, (high - 1) - low);
        cross_off(prime, low, high, next[b], sieve, counters);
      }
    }

    next_segment:;
  }

  return S2_thread;
}

/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
           int64_t y,
           int64_t z,
           int64_t c,
           vector<int32_t>& primes,
           vector<int32_t>& lpf,
           vector<int32_t>& mu,
           int threads)
{
  int64_t limit = z + 1;
  threads = validate_threads(threads, limit);

  int64_t S2_total = 0;
  int64_t low = 1;
  int64_t sqrt_limit = isqrt(limit);
  int64_t logx = max(1, ilog(x));
  int64_t min_segment_size = 1 << 6;
  int64_t segments_per_thread = 1;
  int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
  segment_size = max(segment_size, min_segment_size);
  double relative_standard_deviation = 30;

  vector<int32_t> pi = make_pi(y);
  vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);

  while (low < limit)
  {
    int64_t segments = (limit - low + segment_size - 1) / segment_size;
    threads = in_between(1, threads, segments);
    segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);

    aligned_vector<vector<int64_t> > phi(threads);
    aligned_vector<vector<int64_t> > mu_sum(threads);
    aligned_vector<double> timings(threads);

    #pragma omp parallel for num_threads(threads) reduction(+: S2_total)
    for (int i = 0; i < threads; i++)
    {
      timings[i] = get_wtime();
      S2_total += S2_thread(x, y, z, c, segment_size, segments_per_thread,
          i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);
      timings[i] = get_wtime() - timings[i];
    }

    // Once all threads have finished reconstruct and add the
    // missing contribution of all special leaves. This must
    // be done in order as each thread (i) requires the sum of
    // the phi values from the previous threads.
    //
    for (int i = 0; i < threads; i++)
    {
      for (size_t j = 1; j < phi[i].size(); j++)
      {
        S2_total += phi_total[j] * mu_sum[i][j];
        phi_total[j] += phi[i][j];
      }
    }

    low += segments_per_thread * threads * segment_size;
    balance_S2_load(&segment_size, &segments_per_thread, min_segment_size,
        sqrt_limit, &relative_standard_deviation, timings);
  }

  return S2_total;
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads)
{
  if (x < 2)
    return 0;

  // alpha is a tuning factor
  double d = (double) x;
  double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = x / y;

  vector<int32_t> mu = make_moebius(y);
  vector<int32_t> lpf = make_least_prime_factor(y);
  vector<int32_t> primes;
  primes.push_back(0);
  primesieve::generate_primes(y, &primes);

  int64_t pi_y = pi_bsearch(primes, y);
  int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
  int64_t s1 = S1(x, y, c, primes, lpf , mu);
  int64_t s2 = S2(x, y, z, c, primes, lpf , mu, threads);
  int64_t p2 = P2(x, y, threads);
  int64_t phi = s1 + s2;
  int64_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace primecount
<|endoftext|>


<commit_before>// $Id$

AliEmcalJetTask* AddTaskEmcalJet(
  const char *nTracks        = "Tracks",
  const char *nClusters      = "CaloClusters",
  const Int_t algo           = 1,
  const Double_t radius      = 0.4,
  const Int_t type           = 0,
  const Double_t minTrPt     = 0.15,
  const Double_t minClPt     = 0.15
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskAliEmcalJet", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskAliEmcalJet", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  Double_t minJetPt = 0;

  char *algoString;
  if (algo == 0) {
    algoString = "KT";
    minJetPt = 0.1;
  } else if (algo == 1) {
    algoString = "AKT";
    minJetPt = 1.0;
  }

  char *typeString;
  if (type == 0)
    typeString = "Full";
  else if (type == 1)
    typeString = "Charged";
  else if (type == 2)
    typeString = "Neutral";

  char radiusString[200];
  sprintf(radiusString,"R0%2.0f",radius*100.0);

  char pTString[200];
  if (minTrPt<1.0)
    sprintf(pTString,"pT0%3.0f",minTrPt*1000.0);
  else if (minTrPt>=1.0)
    sprintf(pTString,"pT%4.0f",minTrPt*1000.0);

  char ETString[200];
  if (minClPt<1.0)
    sprintf(ETString,"ET0%3.0f",minClPt*1000.0);
  else if (minClPt>=1.0)
    sprintf(ETString,"ET%4.0f",minClPt*1000.0);

  TString name;
  if (type == 0)
    name = TString(Form("Jet_%s%sR%s_%s_%s_%s_%s",
                        algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString));
  else if (type == 1)
    name = TString(Form("Jet_%s%sR%s_%s_%s",
                        algoString,typeString,radiusString,nTracks,pTString));
  else if (type == 2)
    name = TString(Form("Jet_%s%sR%s_%s_%s",
                        algoString,typeString,radiusString,nClusters,ETString));

  AliEmcalJetTask* mgrTask = mgr->GetTask(name.Data());
  if (mgrTask)
    return mgrTask;

  AliEmcalJetTask* jetTask = new AliEmcalJetTask(name);
  jetTask->SetTracksName(nTracks);
  jetTask->SetClusName(nClusters);
  jetTask->SetJetsName(name);
  jetTask->SetAlgo(algo);
  jetTask->SetMinJetTrackPt(minTrPt);
  jetTask->SetMinJetClusPt(minClPt);
  jetTask->SetMinJetPt(minJetPt);
  jetTask->SetRadius(radius);
  jetTask->SetType(type);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(jetTask);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer()  ;
  mgr->ConnectInput  (jetTask, 0, cinput);

  return jetTask;
}
<commit_msg>removing rosi<commit_after>// $Id$

AliEmcalJetTask* AddTaskEmcalJet(
  const char *nTracks        = "Tracks",
  const char *nClusters      = "CaloClusters",
  const Int_t algo           = 1,
  const Double_t radius      = 0.4,
  const Int_t type           = 0,
  const Double_t minTrPt     = 0.15,
  const Double_t minClPt     = 0.15
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskAliEmcalJet", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskAliEmcalJet", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  Double_t minJetPt = 0;

  char *algoString;
  if (algo == 0) {
    algoString = "KT";
    minJetPt = 0.1;
  } else if (algo == 1) {
    algoString = "AKT";
    minJetPt = 1.0;
  }

  char *typeString;
  if (type == 0)
    typeString = "Full";
  else if (type == 1)
    typeString = "Charged";
  else if (type == 2)
    typeString = "Neutral";

  char radiusString[200];
  sprintf(radiusString,"R0%2.0f",radius*100.0);

  char pTString[200];
  if (minTrPt<1.0)
    sprintf(pTString,"pT0%3.0f",minTrPt*1000.0);
  else if (minTrPt>=1.0)
    sprintf(pTString,"pT%4.0f",minTrPt*1000.0);

  char ETString[200];
  if (minClPt<1.0)
    sprintf(ETString,"ET0%3.0f",minClPt*1000.0);
  else if (minClPt>=1.0)
    sprintf(ETString,"ET%4.0f",minClPt*1000.0);

  TString name;
  if (type == 0)
    name = TString(Form("Jet_%s%s%s_%s_%s_%s_%s",
                        algoString,typeString,radiusString,nTracks,pTString,nClusters,ETString));
  else if (type == 1)
    name = TString(Form("Jet_%s%s%s_%s_%s",
                        algoString,typeString,radiusString,nTracks,pTString));
  else if (type == 2)
    name = TString(Form("Jet_%s%s%s_%s_%s",
                        algoString,typeString,radiusString,nClusters,ETString));

  AliEmcalJetTask* mgrTask = mgr->GetTask(name.Data());
  if (mgrTask)
    return mgrTask;

  AliEmcalJetTask* jetTask = new AliEmcalJetTask(name);
  jetTask->SetTracksName(nTracks);
  jetTask->SetClusName(nClusters);
  jetTask->SetJetsName(name);
  jetTask->SetAlgo(algo);
  jetTask->SetMinJetTrackPt(minTrPt);
  jetTask->SetMinJetClusPt(minClPt);
  jetTask->SetMinJetPt(minJetPt);
  jetTask->SetRadius(radius);
  jetTask->SetType(type);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(jetTask);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer()  ;
  mgr->ConnectInput  (jetTask, 0, cinput);

  return jetTask;
}
<|endoftext|>


<commit_before><commit_msg>so *that's* where the hello/world we're coming from<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <experimental/string_view>

namespace auth {

namespace meta {

namespace roles_table {

constexpr stdx::string_view name{"roles", 5};

stdx::string_view qualified_name() noexcept;

constexpr stdx::string_view role_col_name{"role", 4};

}

}

}
<commit_msg>auth: Include missing header<commit_after>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <experimental/string_view>

#include "stdx.hh"

namespace auth {

namespace meta {

namespace roles_table {

constexpr stdx::string_view name{"roles", 5};

stdx::string_view qualified_name() noexcept;

constexpr stdx::string_view role_col_name{"role", 4};

}

}

}
<|endoftext|>