<commit_before>// Copyright (c) 2015 The Brick Authors.

#include "brick/request_util.h"

#include "include/cef_request.h"
#include "include/cef_parser.h"

namespace request_util {

  CefRefPtr<CefPostData>
  PostFormToCefPost(const PostFormMap& form) {
    std::string data;
    for (const auto &element : form) {
      data += "&" + CefURIEncode(element.first, false).ToString() + "=" + CefURIEncode(element.second, false).ToString();
    }

    CefRefPtr<CefPostDataElement> postDataElement(CefPostDataElement::Create());
    postDataElement->SetToBytes(data.length(), data.c_str());
    CefRefPtr<CefPostData> result = CefPostData::Create();
    result->AddElement(postDataElement);
    return result;
  }

  CookiesMap
  GetCookies(const CefResponse::HeaderMap& headers) {
    CookiesMap result;
    for (const auto &it : headers) {
      if (it.first == "Set-Cookie") {
        ParseCookie(it.second, result);
      }
    }
    return result;
  }

  void
  ParseCookie(const std::string& header, CookiesMap& destination) {
    size_t separator = header.find_first_of("=");
    size_t end_value = header.find_first_of(";");
    if (separator == std::string::npos) {
      return;
    }

    std::string key = header.substr(0, separator);
    CefString value;
    if (end_value != std::string::npos) {
      value = CefURIDecode(
          header.substr(separator + 1, end_value - separator - 1),
          false,
          static_cast<cef_uri_unescape_rule_t>(
            UU_SPACES | UU_URL_SPECIAL_CHARS)
          );
    } else {
      value = CefURIDecode(
          header.substr(separator + 1),
          false,
          static_cast<cef_uri_unescape_rule_t>(
              UU_SPACES | UU_URL_SPECIAL_CHARS)
      );
    }

    destination[key] = value;
  }

  std::string
  GetErrorString(CefURLRequest::ErrorCode code) {
    // Case condition that returns |code| as a string.
    #define CASE(code, explain) case code: \
     return std::string(explain) + " (" + #code  + "/" + std::to_string(abs(code)) + ").";

    switch (code) {
      CASE(ERR_NONE,
           "ERR_NONE");
      CASE(ERR_FAILED,
           "A generic failure occurred");
      CASE(ERR_ABORTED,
           "An operation was aborted");
      CASE(ERR_INVALID_ARGUMENT,
           "An argument to the function is incorrect");
      CASE(ERR_INVALID_HANDLE,
           "The handle or file descriptor is invalid");
      CASE(ERR_FILE_NOT_FOUND,
           "The file or directory cannot be found");
      CASE(ERR_TIMED_OUT,
           "An operation timed out");
      CASE(ERR_FILE_TOO_BIG,
           "The file is too large");
      CASE(ERR_UNEXPECTED,
           "An unexpected error");
      CASE(ERR_ACCESS_DENIED,
           "Permission to access a resource, other than the network, was denied");
      CASE(ERR_NOT_IMPLEMENTED,
           "The operation failed because of unimplemented functionality");
      CASE(ERR_CONNECTION_CLOSED,
           "A connection was closed");
      CASE(ERR_CONNECTION_RESET,
           "A connection was reset");
      CASE(ERR_CONNECTION_REFUSED,
           "A connection attempt was refused");
      CASE(ERR_CONNECTION_ABORTED,
           "A connection timed out");
      CASE(ERR_CONNECTION_FAILED,
           "A connection attempt failed");
      CASE(ERR_NAME_NOT_RESOLVED,
           "The host name could not be resolved");
      CASE(ERR_INTERNET_DISCONNECTED,
           "The Internet connection has been lost");
      CASE(ERR_SSL_PROTOCOL_ERROR,
           "An SSL protocol error occurred");
      CASE(ERR_ADDRESS_INVALID,
           "The IP address or port number is invalid");
      CASE(ERR_ADDRESS_UNREACHABLE,
           "The IP address is unreachable");
      CASE(ERR_SSL_CLIENT_AUTH_CERT_NEEDED,
           "The server requested a client certificate for SSL client authentication");
      CASE(ERR_TUNNEL_CONNECTION_FAILED,
           "A tunnel connection through the proxy could not be established");
      CASE(ERR_NO_SSL_VERSIONS_ENABLED,
           "No SSL protocol versions are enabled");
      CASE(ERR_SSL_VERSION_OR_CIPHER_MISMATCH,
           "The client and server don't support a common SSL protocol version or cipher suite");
      CASE(ERR_SSL_RENEGOTIATION_REQUESTED,
           "The server requested a renegotiation (rehandshake)");
      CASE(ERR_CERT_COMMON_NAME_INVALID,
           "The certificate common name did not match the host name");
      CASE(ERR_CERT_DATE_INVALID,
           "The certificate appears to either not yet be valid or to have expired");
      CASE(ERR_CERT_AUTHORITY_INVALID,
           "The certificate is signed by an untrusted authority");
      CASE(ERR_CERT_CONTAINS_ERRORS,
           "The certificate contains errors");
      CASE(ERR_CERT_NO_REVOCATION_MECHANISM,
           "The certificate has no mechanism for determining if it is revoked");
      CASE(ERR_CERT_UNABLE_TO_CHECK_REVOCATION,
           "Revocation information for the security certificate for this site is not available");
      CASE(ERR_CERT_REVOKED,
           "The certificate has been revoked");
      CASE(ERR_CERT_INVALID,
           "The certificate is invalid");
      CASE(ERR_CERT_END,
           "The value immediately past the last certificate error code");
      CASE(ERR_INVALID_URL,
           "The URL is invalid");
      CASE(ERR_DISALLOWED_URL_SCHEME,
           "The scheme of the URL is disallowed");
      CASE(ERR_UNKNOWN_URL_SCHEME,
           "The scheme of the URL is unknown");
      CASE(ERR_TOO_MANY_REDIRECTS,
          "Attempting to load an URL resulted in too many redirects");
      CASE(ERR_UNSAFE_REDIRECT,
           "Attempting to load an URL resulted in an unsafe redirect");
      CASE(ERR_UNSAFE_PORT,
           "Attempting to load an URL with an unsafe port number");
      CASE(ERR_INVALID_RESPONSE,
           "The server's response was invalid");
      CASE(ERR_INVALID_CHUNKED_ENCODING,
           "Error in chunked transfer encoding");
      CASE(ERR_METHOD_NOT_SUPPORTED,
           "The server did not support the request method");
      CASE(ERR_UNEXPECTED_PROXY_AUTH,
           "Proxy authentication required for request without proxy");
      CASE(ERR_EMPTY_RESPONSE,
           "The server closed the connection without sending any data");
      CASE(ERR_RESPONSE_HEADERS_TOO_BIG,
           "The headers section of the response is too large");
      CASE(ERR_CACHE_MISS,
           "The cache does not have the requested entry");
      CASE(ERR_INSECURE_RESPONSE,
           "The server's response was insecure");
      default:
        return "UNKNOWN";
    }
  }

  std::string
  ParseDownloadFilename(const std::string& url) {
    std::string result;

    auto start_pos = url.find("fileName=");
    if (start_pos == std::string::npos) {
      return "undefined";
    }
    start_pos += sizeof("fileName=") - 1;

    auto end_pos = url.find_first_of("&#", start_pos);
    if (end_pos == std::string::npos) {
      result = url.substr(start_pos);
    } else {
      result = url.substr(start_pos, end_pos - start_pos);
    }

    return CefURIDecode(
        result,
        true,
        static_cast<cef_uri_unescape_rule_t>(
            UU_SPACES | UU_URL_SPECIAL_CHARS | UU_REPLACE_PLUS_WITH_SPACE)
    );
  }

}  // namespace request_util
<commit_msg>Minor cookies parsing optimization<commit_after>// Copyright (c) 2015 The Brick Authors.

#include "brick/request_util.h"

#include "include/cef_request.h"
#include "include/cef_parser.h"

namespace request_util {

  CefRefPtr<CefPostData>
  PostFormToCefPost(const PostFormMap& form) {
    std::string data;
    for (const auto &element : form) {
      data += "&" + CefURIEncode(element.first, false).ToString() + "=" + CefURIEncode(element.second, false).ToString();
    }

    CefRefPtr<CefPostDataElement> postDataElement(CefPostDataElement::Create());
    postDataElement->SetToBytes(data.length(), data.c_str());
    CefRefPtr<CefPostData> result = CefPostData::Create();
    result->AddElement(postDataElement);
    return result;
  }

  CookiesMap
  GetCookies(const CefResponse::HeaderMap& headers) {
    CookiesMap result;
    const auto range = headers.equal_range("Set-Cookie");
    for (auto it = range.first; it != range.second; ++it) {
      ParseCookie(it->second, result);
    }
    return result;
  }

  void
  ParseCookie(const std::string& header, CookiesMap& destination) {
    size_t separator = header.find_first_of("=");
    size_t end_value = header.find_first_of(";");
    if (separator == std::string::npos) {
      return;
    }

    std::string key = header.substr(0, separator);
    CefString value;
    if (end_value != std::string::npos) {
      value = CefURIDecode(
          header.substr(separator + 1, end_value - separator - 1),
          false,
          static_cast<cef_uri_unescape_rule_t>(
            UU_SPACES | UU_URL_SPECIAL_CHARS)
          );
    } else {
      value = CefURIDecode(
          header.substr(separator + 1),
          false,
          static_cast<cef_uri_unescape_rule_t>(
              UU_SPACES | UU_URL_SPECIAL_CHARS)
      );
    }

    destination[key] = value;
  }

  std::string
  GetErrorString(CefURLRequest::ErrorCode code) {
    // Case condition that returns |code| as a string.
    #define CASE(code, explain) case code: \
     return std::string(explain) + " (" + #code  + "/" + std::to_string(abs(code)) + ").";

    switch (code) {
      CASE(ERR_NONE,
           "ERR_NONE");
      CASE(ERR_FAILED,
           "A generic failure occurred");
      CASE(ERR_ABORTED,
           "An operation was aborted");
      CASE(ERR_INVALID_ARGUMENT,
           "An argument to the function is incorrect");
      CASE(ERR_INVALID_HANDLE,
           "The handle or file descriptor is invalid");
      CASE(ERR_FILE_NOT_FOUND,
           "The file or directory cannot be found");
      CASE(ERR_TIMED_OUT,
           "An operation timed out");
      CASE(ERR_FILE_TOO_BIG,
           "The file is too large");
      CASE(ERR_UNEXPECTED,
           "An unexpected error");
      CASE(ERR_ACCESS_DENIED,
           "Permission to access a resource, other than the network, was denied");
      CASE(ERR_NOT_IMPLEMENTED,
           "The operation failed because of unimplemented functionality");
      CASE(ERR_CONNECTION_CLOSED,
           "A connection was closed");
      CASE(ERR_CONNECTION_RESET,
           "A connection was reset");
      CASE(ERR_CONNECTION_REFUSED,
           "A connection attempt was refused");
      CASE(ERR_CONNECTION_ABORTED,
           "A connection timed out");
      CASE(ERR_CONNECTION_FAILED,
           "A connection attempt failed");
      CASE(ERR_NAME_NOT_RESOLVED,
           "The host name could not be resolved");
      CASE(ERR_INTERNET_DISCONNECTED,
           "The Internet connection has been lost");
      CASE(ERR_SSL_PROTOCOL_ERROR,
           "An SSL protocol error occurred");
      CASE(ERR_ADDRESS_INVALID,
           "The IP address or port number is invalid");
      CASE(ERR_ADDRESS_UNREACHABLE,
           "The IP address is unreachable");
      CASE(ERR_SSL_CLIENT_AUTH_CERT_NEEDED,
           "The server requested a client certificate for SSL client authentication");
      CASE(ERR_TUNNEL_CONNECTION_FAILED,
           "A tunnel connection through the proxy could not be established");
      CASE(ERR_NO_SSL_VERSIONS_ENABLED,
           "No SSL protocol versions are enabled");
      CASE(ERR_SSL_VERSION_OR_CIPHER_MISMATCH,
           "The client and server don't support a common SSL protocol version or cipher suite");
      CASE(ERR_SSL_RENEGOTIATION_REQUESTED,
           "The server requested a renegotiation (rehandshake)");
      CASE(ERR_CERT_COMMON_NAME_INVALID,
           "The certificate common name did not match the host name");
      CASE(ERR_CERT_DATE_INVALID,
           "The certificate appears to either not yet be valid or to have expired");
      CASE(ERR_CERT_AUTHORITY_INVALID,
           "The certificate is signed by an untrusted authority");
      CASE(ERR_CERT_CONTAINS_ERRORS,
           "The certificate contains errors");
      CASE(ERR_CERT_NO_REVOCATION_MECHANISM,
           "The certificate has no mechanism for determining if it is revoked");
      CASE(ERR_CERT_UNABLE_TO_CHECK_REVOCATION,
           "Revocation information for the security certificate for this site is not available");
      CASE(ERR_CERT_REVOKED,
           "The certificate has been revoked");
      CASE(ERR_CERT_INVALID,
           "The certificate is invalid");
      CASE(ERR_CERT_END,
           "The value immediately past the last certificate error code");
      CASE(ERR_INVALID_URL,
           "The URL is invalid");
      CASE(ERR_DISALLOWED_URL_SCHEME,
           "The scheme of the URL is disallowed");
      CASE(ERR_UNKNOWN_URL_SCHEME,
           "The scheme of the URL is unknown");
      CASE(ERR_TOO_MANY_REDIRECTS,
          "Attempting to load an URL resulted in too many redirects");
      CASE(ERR_UNSAFE_REDIRECT,
           "Attempting to load an URL resulted in an unsafe redirect");
      CASE(ERR_UNSAFE_PORT,
           "Attempting to load an URL with an unsafe port number");
      CASE(ERR_INVALID_RESPONSE,
           "The server's response was invalid");
      CASE(ERR_INVALID_CHUNKED_ENCODING,
           "Error in chunked transfer encoding");
      CASE(ERR_METHOD_NOT_SUPPORTED,
           "The server did not support the request method");
      CASE(ERR_UNEXPECTED_PROXY_AUTH,
           "Proxy authentication required for request without proxy");
      CASE(ERR_EMPTY_RESPONSE,
           "The server closed the connection without sending any data");
      CASE(ERR_RESPONSE_HEADERS_TOO_BIG,
           "The headers section of the response is too large");
      CASE(ERR_CACHE_MISS,
           "The cache does not have the requested entry");
      CASE(ERR_INSECURE_RESPONSE,
           "The server's response was insecure");
      default:
        return "UNKNOWN";
    }
  }

  std::string
  ParseDownloadFilename(const std::string& url) {
    std::string result;

    auto start_pos = url.find("fileName=");
    if (start_pos == std::string::npos) {
      return "undefined";
    }
    start_pos += sizeof("fileName=") - 1;

    auto end_pos = url.find_first_of("&#", start_pos);
    if (end_pos == std::string::npos) {
      result = url.substr(start_pos);
    } else {
      result = url.substr(start_pos, end_pos - start_pos);
    }

    return CefURIDecode(
        result,
        true,
        static_cast<cef_uri_unescape_rule_t>(
            UU_SPACES | UU_URL_SPECIAL_CHARS | UU_REPLACE_PLUS_WITH_SPACE)
    );
  }

}  // namespace request_util
<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html

IGNORE:
struct DUMMY { // dummy class for auto indentation

handle_scope:Object:
  uint64_t      on       (const ::std::string &type, ::Aida::EventHandlerF handler) { return this->RemoteHandle::__event_attach__ (type, handler); }
  void          off      (uint64_t *connection_id)                                  { this->off (*connection_id); *connection_id = 0; }
  void          off      (uint64_t connection_id)
  {
    if (connection_id && !this->RemoteHandle::__event_detach__ (connection_id))
      Bse::warning ("Bse::Object.off(): unknown handler id: %u", connection_id);
  }

interface_scope:Object:
  void          trigger  (const ::Aida::Event &event)                               { return this->ImplicitBase::__event_emit__ (event); }
  uint64_t      on       (const ::std::string &type, ::Aida::EventHandlerF handler) { return this->ImplicitBase::__event_attach__ (type, handler); }
  void          off      (uint64_t *connection_id)                                  { this->off (*connection_id); *connection_id = 0; }
  void          off      (uint64_t connection_id)
  {
    if (connection_id && !this->ImplicitBase::__event_detach__ (connection_id))
      Bse::warning ("Bse::ObjectIface.off(): unknown handler id: %u", connection_id);
  }
  // as<BseObjectPtr>()
  template<class BseObjectPtr, typename ::std::enable_if<std::is_pointer<BseObjectPtr>::value, bool>::type = true>
  BseObjectPtr           as ()
  {
    static_assert (std::is_pointer<BseObjectPtr>::value, "'BseObject*' required");
    typedef typename std::remove_pointer<BseObjectPtr>::type BseObjectT;
    static_assert (std::is_base_of<GObject, BseObjectT>::value, "'BseObject*' required");
    return (BseObjectPtr) this->as_bse_object();
  }
  // DERIVES_shared_ptr (uses void_t to prevent errors for T without shared_ptr's typedefs)
  template<class T, typename = void> struct DERIVES_shared_ptr : std::false_type {};
  template<class T> struct DERIVES_shared_ptr<T, Bse::void_t< typename T::element_type > > :
  std::is_base_of< std::shared_ptr<typename T::element_type>, T > {};
  // as<shared_ptr<T>>()
  template<class ObjectImplP, typename ::std::enable_if<DERIVES_shared_ptr<ObjectImplP>::value, bool>::type = true>
  ObjectImplP            as ()
  {
    typedef typename ObjectImplP::element_type ObjectImplT;
    static_assert (std::is_base_of<Aida::ImplicitBase, ObjectImplT>::value, "");
    ObjectImplT *impl = dynamic_cast<ObjectImplT*> (this);
    return impl ? Bse::shared_ptr_cast<ObjectImplT> (impl) : NULL;
  }
protected:
  virtual BseObject* as_bse_object() = 0;

IGNORE: // close last _scope
}; // DUMMY
<commit_msg>BSE: bseapi-inserts: remove trigger alias for aida event internals<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html

IGNORE:
struct DUMMY { // dummy class for auto indentation

handle_scope:Object:
  uint64_t      on       (const ::std::string &type, ::Aida::EventHandlerF handler) { return this->RemoteHandle::__event_attach__ (type, handler); }
  void          off      (uint64_t *connection_id)                                  { this->off (*connection_id); *connection_id = 0; }
  void          off      (uint64_t connection_id)
  {
    if (connection_id && !this->RemoteHandle::__event_detach__ (connection_id))
      Bse::warning ("Bse::Object.off(): unknown handler id: %u", connection_id);
  }

interface_scope:Object:
  uint64_t      on       (const ::std::string &type, ::Aida::EventHandlerF handler) { return this->ImplicitBase::__event_attach__ (type, handler); }
  void          off      (uint64_t *connection_id)                                  { this->off (*connection_id); *connection_id = 0; }
  void          off      (uint64_t connection_id)
  {
    if (connection_id && !this->ImplicitBase::__event_detach__ (connection_id))
      Bse::warning ("Bse::ObjectIface.off(): unknown handler id: %u", connection_id);
  }
  // as<BseObjectPtr>()
  template<class BseObjectPtr, typename ::std::enable_if<std::is_pointer<BseObjectPtr>::value, bool>::type = true>
  BseObjectPtr           as ()
  {
    static_assert (std::is_pointer<BseObjectPtr>::value, "'BseObject*' required");
    typedef typename std::remove_pointer<BseObjectPtr>::type BseObjectT;
    static_assert (std::is_base_of<GObject, BseObjectT>::value, "'BseObject*' required");
    return (BseObjectPtr) this->as_bse_object();
  }
  // DERIVES_shared_ptr (uses void_t to prevent errors for T without shared_ptr's typedefs)
  template<class T, typename = void> struct DERIVES_shared_ptr : std::false_type {};
  template<class T> struct DERIVES_shared_ptr<T, Bse::void_t< typename T::element_type > > :
  std::is_base_of< std::shared_ptr<typename T::element_type>, T > {};
  // as<shared_ptr<T>>()
  template<class ObjectImplP, typename ::std::enable_if<DERIVES_shared_ptr<ObjectImplP>::value, bool>::type = true>
  ObjectImplP            as ()
  {
    typedef typename ObjectImplP::element_type ObjectImplT;
    static_assert (std::is_base_of<Aida::ImplicitBase, ObjectImplT>::value, "");
    ObjectImplT *impl = dynamic_cast<ObjectImplT*> (this);
    return impl ? Bse::shared_ptr_cast<ObjectImplT> (impl) : NULL;
  }
protected:
  virtual BseObject* as_bse_object() = 0;

IGNORE: // close last _scope
}; // DUMMY
<|endoftext|>


<commit_before>#include <iostream>                     // std::cout ...

#include "logMsg.h"                     // lmInit, LM_*
#include "traceLevels.h"                // Trace Levels
#include <dlfcn.h>
#include <sys/types.h>
#include <dirent.h>

#include "Message.h"                    // Message
#include "Macros.h"                     // EXIT, ...
#include "Packet.h"                     // ss::Packet
#include "Network.h"                    // NetworkInterface
#include "Endpoint.h"                   // Endpoint
#include "CommandLine.h"                // CommandLine
#include "SamsonWorker.h"               // Own interfce
#include "SamsonSetup.h"				// ss::SamsonSetup
#include "Format.h"						// au::Format

#include "MemoryManager.h"				// ss::SharedMemory
#include "FileManager.h"				// ss::FileManager
#include "ProcessManager.h"				// ss::ProcessManager

namespace ss {

	void* run_runStatusUpdate(void *p)
	{
		((SamsonWorker *)p)->runStatusUpdate();
		return NULL;
	}

/* ****************************************************************************
*
* Constructor
*/
SamsonWorker::SamsonWorker( NetworkInterface* network ) :  taskManager(this) , loadDataManager(this)
{
	this->network = network;
	network->setPacketReceiver(this);

	srand( (unsigned int) time(NULL) );

	// Create a thread to run "runStatusUpdate"
	pthread_t t;
	pthread_create(&t, NULL, run_runStatusUpdate, this);
}

/* ****************************************************************************
*
* run -
*/
void SamsonWorker::runStatusUpdate()
{
	// Report periodically status to the controller

	while (true)
	{
		if( network->ready() )
		{
			sendWorkerStatus();

			// Send a message to receive a complete list of the queues ( to remove old files )
			{
				Packet*           p = new Packet();
				network::Command* c = p->message.mutable_command();
				c->set_command( "ls" );
				p->message.set_delilah_id( 0 ); // At the moment no sence at the controller
				//copyEnviroment( &environment , c->mutable_environment() );
				network->send(this, network->controllerGetIdentifier(), Message::Command, p);
			}

		}
		sleep(3);
	}

}

/* ****************************************************************************
*
* SamsonWorker::sendWorkerStatus -
*/
void SamsonWorker::sendWorkerStatus(void)
{
	Packet*                  p  = new Packet();
	network::WorkerStatus*   ws = p->message.mutable_worker_status();

	// Fill to all data related with task manager
	taskManager.fill(ws);

	// Fill information related with file manager and disk manager
	DiskManager::shared()->fill( ws );
	FileManager::shared()->fill( ws );
	MemoryManager::shared()->fill( ws );
	ProcessManager::shared()->fill( ws );

	loadDataManager.fill( ws );

	ws->set_used_memory( MemoryManager::shared()->get_used_memory() );

	network->send(this, network->controllerGetIdentifier(), Message::WorkerStatus, p);
}

/* ****************************************************************************
*
* SamsonWorker::receive -
*/
int SamsonWorker::receive(int fromId, Message::MessageCode msgCode, Packet* packet)
{
	if (msgCode == Message::WorkerTask)
	{
		// A packet with a particular command is received (controller expect to send a confirmation message)
		LM_T(LmtTask, ("Got a WorkerTask message"));

		if( packet->message.worker_task().operation() == "reload_modules" )
		{
			// Spetial operation to reload modules
			ModulesManager::shared()->reloadModules();
			return 0;
		}

		// add task to the task manager
		taskManager.addTask( packet->message.worker_task() );
		return 0;
	}

	if (msgCode == Message::WorkerTaskKill)
	{
		// A packet with a particular command is received (controller expect to send a confirmation message)
		LM_T(LmtTask, ("Got a WorkerTaskKill message"));

		// add task to the task manager
		taskManager.killTask( packet->message.worker_task_kill() );
		return 0;
	}

	// List of local file ( remove unnecessary files )
	if (msgCode == Message::CommandResponse)
	{
		processListOfFiles( packet->message.command_response().queue_list() );
		return 0;
	}

	// Load data files to be latter confirmed to controller
	if (msgCode == Message::UploadDataFile)
	{
		loadDataManager.addUploadItem(fromId, packet->message.upload_data_file(), packet->message.delilah_id() , packet->buffer );
		return 0;
	}

	// Download data files
	if (msgCode == Message::DownloadDataFile)
	{
		loadDataManager.addDownloadItem(fromId, packet->message.download_data_file() , packet->message.delilah_id() );
		return 0;
	}

	/**
	 Data packets go directly to the DataBuffer to be joined and flushed to disk
	 DataManager is notifyed when created a new file or finish everything
	 */

	if( msgCode == Message::WorkerDataExchange )
	{
		// New data packet for a particular queue inside a particular task environment

		size_t task_id = packet->message.data().task_id();
		network::Queue queue = packet->message.data().queue();

		bool txt = false;
		if( packet->message.data().has_txt() && packet->message.data().txt() )
			txt = true;

		taskManager.addBuffer( task_id , queue, packet->buffer , txt );

		return 0;
	}

	/**
	 Data Close message is sent to notify that no more data will be generated
	 We have to wait for "N" messages ( one per worker )
	 */

	if( msgCode == Message::WorkerDataExchangeClose )
	{

		size_t task_id = packet->message.data_close().task_id();
		taskManager.finishWorker( task_id );
		return 0;
	}

	return 0;
	}

	/**
	 Process the list of files removing unnecessary files
	 */

	void SamsonWorker::processListOfFiles( const ::ss::network::QueueList& ql)
	{
		// Generate list of local files ( to not remove them )
		std::set<std::string> files;
		std::set<size_t> load_id;

		for (int q = 0 ; q < ql.queue_size() ; q++)
		{
			const network::FullQueue& queue = ql.queue(q);
			for (int f = 0 ; f < queue.file_size() ; f++)
			{
				const network::File &file =  queue.file(f);
				if( file.worker() == _myWorkerId )
				{
					files.insert( file.name() );
				}
			}
		}

		// Get the files from the active tasks to not remove them
		for (int t = 0 ; t < ql.tasks_size() ; t++)
			for (int f = 0 ; f < ql.tasks(t).filename_size() ; f++)
				files.insert( ql.tasks(t).filename(f)  );

		// Get the list of active load_ids to not remove temporal files of these upload operations
		for (int t = 0 ; t < ql.load_id_size() ; t++)
			load_id.insert(ql.load_id(t));

		// Get the list of files to be removed

		std::set< std::string > remove_files;

		DIR *dp;
		struct dirent *dirp;
		if((dp  = opendir( SamsonSetup::shared()->dataDirectory.c_str() )) == NULL) {

			// LOG and error to indicate that data directory cannot be access
			return;
		}

		while ((dirp = readdir(dp)) != NULL) {

			std::string path = SamsonSetup::shared()->dataDirectory + "/" + dirp->d_name;

			struct ::stat info;
			stat(path.c_str(), &info);

			if( S_ISREG(info.st_mode) )
			{

				// Get modification date to see if it was just created
				time_t now;
				time (&now);
				double age = difftime ( now , info.st_mtime );

				if( age > 60 ) // Get some time to avoid cross-message between controller and worker
				{

					// Get the task from the file name
					std::string file_name = dirp->d_name;
					size_t pos = file_name.find("_");
					size_t task = 0;
					if( pos != std::string::npos )
						task = atoll( file_name.substr( 0 , pos ).c_str() );

					if( files.find( file_name ) == files.end() )
					{
						// If the file is not in the list remove this

						if( file_name.substr( 0 , 14 ) == "file_updaload_" )
						{
							// Exception: temporal upload files
							size_t pos = file_name.find("_" , 14);
							size_t _load_id = atoll( file_name.substr(14 , pos).c_str() );
							if( load_id.find(_load_id ) == load_id.end() )
							{
								LM_M(("Removing file %s since the id (%lu) is not in the list of active load operations (size:%d)", file_name.c_str() , _load_id , load_id.size() ));
								remove_files.insert( path );
							}
						}
						else
						{
							LM_M(("Remove file %s since it is not in any queue", file_name.c_str()));
							remove_files.insert( path );
						}
					}
				}
			}
		}
		closedir(dp);

		// Remove the selected files
		for ( std::set< std::string >::iterator f = remove_files.begin() ; f != remove_files.end() ; f++)
		{
			LM_TODO(("Check if the remove operation was OK"));
			remove( f->c_str() );
		}

	}

}
<commit_msg>I mis-committed Rev 801<commit_after>#include <iostream>                     // std::cout ...

#include "logMsg.h"                     // lmInit, LM_*
#include "traceLevels.h"                // Trace Levels
#include <dlfcn.h>
#include <sys/types.h>
#include <dirent.h>

#include "Message.h"                    // Message
#include "Macros.h"                     // EXIT, ...
#include "Packet.h"                     // ss::Packet
#include "Network.h"                    // NetworkInterface
#include "Endpoint.h"                   // Endpoint
#include "CommandLine.h"                // CommandLine
#include "SamsonWorker.h"               // Own interfce
#include "SamsonSetup.h"				// ss::SamsonSetup
#include "Format.h"						// au::Format

#include "MemoryManager.h"				// ss::SharedMemory
#include "FileManager.h"				// ss::FileManager
#include "ProcessManager.h"				// ss::ProcessManager

namespace ss {

	void* run_runStatusUpdate(void *p)
	{
		((SamsonWorker *)p)->runStatusUpdate();
		return NULL;
	}

/* ****************************************************************************
*
* Constructor
*/
SamsonWorker::SamsonWorker( NetworkInterface* network ) :  taskManager(this) , loadDataManager(this)
{
	this->network = network;
	network->setPacketReceiver(this);

	srand( (unsigned int) time(NULL) );

	// Create a thread to run "runStatusUpdate"
	pthread_t t;
	pthread_create(&t, NULL, run_runStatusUpdate, this);
}

/* ****************************************************************************
*
* run -
*/
void SamsonWorker::runStatusUpdate()
{
	// Report periodically status to the controller

	while (true)
	{
		if( network->ready() )
		{
			sendWorkerStatus();

			// Send a message to receive a complete list of the queues ( to remove old files )
			{
				Packet*           p = new Packet();
				network::Command* c = p->message.mutable_command();
				c->set_command( "ls" );
				p->message.set_delilah_id( 0 ); // At the moment no sence at the controller
				//copyEnviroment( &environment , c->mutable_environment() );
				network->send(this, network->controllerGetIdentifier(), Message::Command, p);
			}

		}
		sleep(3);
	}

}

/* ****************************************************************************
*
* SamsonWorker::sendWorkerStatus -
*/
void SamsonWorker::sendWorkerStatus(void)
{
	Packet*                  p  = new Packet();
	network::WorkerStatus*   ws = p->message.mutable_worker_status();

	// Fill to all data related with task manager
	taskManager.fill(ws);

	// Fill information related with file manager and disk manager
	DiskManager::shared()->fill( ws );
	FileManager::shared()->fill( ws );
	MemoryManager::shared()->fill( ws );
	ProcessManager::shared()->fill( ws );

	loadDataManager.fill( ws );

	ws->set_used_memory( MemoryManager::shared()->get_used_memory() );

	network->send(this, network->controllerGetIdentifier(), Message::WorkerStatus, p);
}

/* ****************************************************************************
*
* SamsonWorker::receive -
*/
int SamsonWorker::receive(int fromId, Message::MessageCode msgCode, Packet* packet)
{
	if (msgCode == Message::WorkerTask)
	{
		// A packet with a particular command is received (controller expect to send a confirmation message)
		LM_T(LmtTask, ("Got a WorkerTask message"));

		if( packet->message.worker_task().operation() == "reload_modules" )
		{
			// Spetial operation to reload modules
			ModulesManager::shared()->reloadModules();
			return 0;
		}

		// add task to the task manager
		taskManager.addTask( packet->message.worker_task() );
		return 0;
	}

	if (msgCode == Message::WorkerTaskKill)
	{
		// A packet with a particular command is received (controller expect to send a confirmation message)
		LM_T(LmtTask, ("Got a WorkerTaskKill message"));

		// add task to the task manager
		taskManager.killTask( packet->message.worker_task_kill() );
		return 0;
	}

	// List of local file ( remove unnecessary files )
	if (msgCode == Message::CommandResponse)
	{
		processListOfFiles( packet->message.command_response().queue_list() );
		return 0;
	}

	// Load data files to be latter confirmed to controller
	if (msgCode == Message::UploadDataFile)
	{
		loadDataManager.addUploadItem(fromId, packet->message.upload_data_file(), packet->message.delilah_id() , packet->buffer );
		return 0;
	}

	// Download data files
	if (msgCode == Message::DownloadDataFile)
	{
		loadDataManager.addDownloadItem(fromId, packet->message.download_data_file() , packet->message.delilah_id() );
		return 0;
	}

	/**
	 Data packets go directly to the DataBuffer to be joined and flushed to disk
	 DataManager is notifyed when created a new file or finish everything
	 */

	if( msgCode == Message::WorkerDataExchange )
	{
		// New data packet for a particular queue inside a particular task environment

		size_t task_id = packet->message.data().task_id();
		network::Queue queue = packet->message.data().queue();

		bool txt = false;
		if( packet->message.data().has_txt() && packet->message.data().txt() )
			txt = true;

		taskManager.addBuffer( task_id , queue, packet->buffer , txt );

		return 0;
	}

	/**
	 Data Close message is sent to notify that no more data will be generated
	 We have to wait for "N" messages ( one per worker )
	 */

	if( msgCode == Message::WorkerDataExchangeClose )
	{

		size_t task_id = packet->message.data_close().task_id();
		taskManager.finishWorker( task_id );
		return 0;
	}

	return 0;
	}

	/**
	 Process the list of files removing unnecessary files
	 */

	void SamsonWorker::processListOfFiles( const ::ss::network::QueueList& ql)
	{
		// Generate list of local files ( to not remove them )
		std::set<std::string> files;
		std::set<size_t> load_id;

		for (int q = 0 ; q < ql.queue_size() ; q++)
		{
			const network::FullQueue& queue = ql.queue(q);
			for (int f = 0 ; f < queue.file_size() ; f++)
			{
				const network::File &file =  queue.file(f);
				if( file.worker() == _myWorkerId )
				{
					files.insert( file.name() );
				}
			}
		}

		// Get the files from the active tasks to not remove them
		for (int t = 0 ; t < ql.tasks_size() ; t++)
			for (int f = 0 ; f < ql.tasks(t).filename_size() ; f++)
				files.insert( ql.tasks(t).filename(f)  );

		// Get the list of active load_ids to not remove temporal files of these upload operations
		for (int t = 0 ; t < ql.load_id_size() ; t++)
			load_id.insert(ql.load_id(t));

		// Get the list of files to be removed

		std::set< std::string > remove_files;

		DIR *dp;
		struct dirent *dirp;
		if((dp  = opendir( SamsonSetup::shared()->dataDirectory.c_str() )) == NULL) {

			// LOG and error to indicate that data directory cannot be access
			return;
		}

		while ((dirp = readdir(dp)) != NULL) {

			std::string path = SamsonSetup::shared()->dataDirectory + "/" + dirp->d_name;

			struct ::stat info;
			stat(path.c_str(), &info);

			if( S_ISREG(info.st_mode) )
			{

				// Get modification date to see if it was just created
				time_t now;
				time (&now);
				double age = difftime ( now , info.st_mtime );

				if( age > 60 ) // Get some time to avoid cross-message between controller and worker
				{

					// Get the task from the file name
					std::string file_name = dirp->d_name;
					size_t pos = file_name.find("_");
					size_t task = 0;
					if( pos != std::string::npos )
						task = atoll( file_name.substr( 0 , pos ).c_str() );

					if( files.find( file_name ) == files.end() )
					{
						// If the file is not in the list remove this

						if( file_name.substr( 0 , 14 ) == "file_updaload_" )
						{
							// Exception: temporal upload files
							size_t pos = file_name.find("_" , 14);
							size_t _load_id = atoll( file_name.substr(14 , pos).c_str() );
							if( load_id.find(_load_id ) == load_id.end() )
							{
								//LM_M(("Removing file %s since the id (%lu) is not in the list of active load operations (size:%d)", file_name.c_str() , _load_id , load_id.size() ));
								remove_files.insert( path );
							}
						}
						else
						{
							//LM_M(("Remove file %s since it is not in any queue", file_name.c_str()));
							remove_files.insert( path );
						}
					}
				}
			}
		}
		closedir(dp);

		// Remove the selected files
		for ( std::set< std::string >::iterator f = remove_files.begin() ; f != remove_files.end() ; f++)
		{
			LM_TODO(("Check if the remove operation was OK"));
			remove( f->c_str() );
		}

	}

}
<|endoftext|>


<commit_before>//===--- SILValue.cpp - Implementation for SILValue -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"

using namespace swift;

void SILValue::replaceAllUsesWith(SILValue V) {
  assert(*this != V && "Cannot RAUW a value with itself");
  assert(getType() == V.getType() && "Invalid type");
  while (!use_empty())
    (**use_begin()).set(V);
}

static bool isRCIdentityPreservingCast(ValueKind Kind) {
  switch (Kind) {
  case ValueKind::UpcastInst:
  case ValueKind::AddressToPointerInst:
  case ValueKind::PointerToAddressInst:
  case ValueKind::UncheckedRefCastInst:
  case ValueKind::UncheckedAddrCastInst:
  case ValueKind::RefToRawPointerInst:
  case ValueKind::RawPointerToRefInst:
  case ValueKind::UnconditionalCheckedCastInst:
  case ValueKind::UncheckedRefBitCastInst:
    return true;
  default:
    return false;
  }
}

// Similar to isRCIdentityPreservingCast, but does not
// allow for UnconditionalCheckedCastInst, which may
// perform downcasts.
static bool isUpcastPreservingCast(ValueKind Kind) {
  switch (Kind) {
  case ValueKind::UpcastInst:
  case ValueKind::AddressToPointerInst:
  case ValueKind::PointerToAddressInst:
  case ValueKind::UncheckedRefCastInst:
  case ValueKind::UncheckedAddrCastInst:
  case ValueKind::RefToRawPointerInst:
  case ValueKind::RawPointerToRefInst:
  case ValueKind::UncheckedRefBitCastInst:
    return true;
  default:
    return false;
  }
}

/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
static SILValue stripSinglePredecessorArgs(SILValue V) {
  while (true) {
    auto *A = dyn_cast<SILArgument>(V);
    if (!A)
      return V;

    SILBasicBlock *BB = A->getParent();

    // First try and grab the single predecessor of our parent BB. If we don't
    // have one, bail.
    SILBasicBlock *Pred = BB->getSinglePredecessor();
    if (!Pred)
      return V;

    // Then grab the terminator of Pred...
    TermInst *PredTI = Pred->getTerminator();

    // And attempt to find our matching argument.
    if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
      V = BI->getArg(A->getIndex());
      continue;
    }

    if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
      if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
        V = Arg;
        continue;
      }
    }

    return V;
  }
}

SILValue SILValue::stripCasts() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    auto K = V->getKind();
    if (isRCIdentityPreservingCast(K) ||
        K == ValueKind::UncheckedTrivialBitCastInst) {
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    }

    return V;
  }
}

SILValue SILValue::stripUpCasts() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    auto K = V->getKind();
    if (isUpcastPreservingCast(K) ||
        K == ValueKind::UncheckedTrivialBitCastInst) {
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    }

    return V;
  }
}

SILValue SILValue::stripAddressProjections() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    switch (V->getKind()) {
    case ValueKind::StructElementAddrInst:
    case ValueKind::TupleElementAddrInst:
    case ValueKind::RefElementAddrInst:
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    default:
      return V;
    }
  }
}

SILValue SILValue::stripAggregateProjections() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    switch (V->getKind()) {
    case ValueKind::StructExtractInst:
    case ValueKind::TupleExtractInst:
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    default:
      return V;
    }
  }
}

SILValue SILValue::stripIndexingInsts() {
  SILValue V = *this;
  while (true) {
    if (!isa<IndexingInst>(V.getDef()))
      return V;
    V = cast<IndexingInst>(V)->getBase();
  }
}

SILBasicBlock *ValueBase::getParentBB() {
  if (auto Inst = dyn_cast<SILInstruction>(this))
    return Inst->getParent();
  if (auto Arg = dyn_cast<SILArgument>(this))
    return Arg->getParent();
  return nullptr;
}
<commit_msg>These casts are not rc identity preserving we can't strip them<commit_after>//===--- SILValue.cpp - Implementation for SILValue -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"

using namespace swift;

void SILValue::replaceAllUsesWith(SILValue V) {
  assert(*this != V && "Cannot RAUW a value with itself");
  assert(getType() == V.getType() && "Invalid type");
  while (!use_empty())
    (**use_begin()).set(V);
}

static bool isRCIdentityPreservingCast(ValueKind Kind) {
  switch (Kind) {
  case ValueKind::UpcastInst:
  case ValueKind::UncheckedRefCastInst:
  case ValueKind::UncheckedAddrCastInst:
  case ValueKind::UnconditionalCheckedCastInst:
  case ValueKind::UncheckedRefBitCastInst:
    return true;
  default:
    return false;
  }
}

// Similar to isRCIdentityPreservingCast, but does not
// allow for UnconditionalCheckedCastInst, which may
// perform downcasts.
static bool isUpcastPreservingCast(ValueKind Kind) {
  switch (Kind) {
  case ValueKind::UpcastInst:
  case ValueKind::UncheckedRefCastInst:
  case ValueKind::UncheckedAddrCastInst:
  case ValueKind::UncheckedRefBitCastInst:
    return true;
  default:
    return false;
  }
}

/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
static SILValue stripSinglePredecessorArgs(SILValue V) {
  while (true) {
    auto *A = dyn_cast<SILArgument>(V);
    if (!A)
      return V;

    SILBasicBlock *BB = A->getParent();

    // First try and grab the single predecessor of our parent BB. If we don't
    // have one, bail.
    SILBasicBlock *Pred = BB->getSinglePredecessor();
    if (!Pred)
      return V;

    // Then grab the terminator of Pred...
    TermInst *PredTI = Pred->getTerminator();

    // And attempt to find our matching argument.
    if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
      V = BI->getArg(A->getIndex());
      continue;
    }

    if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
      if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
        V = Arg;
        continue;
      }
    }

    return V;
  }
}

SILValue SILValue::stripCasts() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    auto K = V->getKind();
    if (isRCIdentityPreservingCast(K) ||
        K == ValueKind::UncheckedTrivialBitCastInst) {
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    }

    return V;
  }
}

SILValue SILValue::stripUpCasts() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    auto K = V->getKind();
    if (isUpcastPreservingCast(K) ||
        K == ValueKind::UncheckedTrivialBitCastInst) {
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    }

    return V;
  }
}

SILValue SILValue::stripAddressProjections() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    switch (V->getKind()) {
    case ValueKind::StructElementAddrInst:
    case ValueKind::TupleElementAddrInst:
    case ValueKind::RefElementAddrInst:
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    default:
      return V;
    }
  }
}

SILValue SILValue::stripAggregateProjections() {
  SILValue V = *this;

  while (true) {
    V = stripSinglePredecessorArgs(V);

    switch (V->getKind()) {
    case ValueKind::StructExtractInst:
    case ValueKind::TupleExtractInst:
      V = cast<SILInstruction>(V.getDef())->getOperand(0);
      continue;
    default:
      return V;
    }
  }
}

SILValue SILValue::stripIndexingInsts() {
  SILValue V = *this;
  while (true) {
    if (!isa<IndexingInst>(V.getDef()))
      return V;
    V = cast<IndexingInst>(V)->getBase();
  }
}

SILBasicBlock *ValueBase::getParentBB() {
  if (auto Inst = dyn_cast<SILInstruction>(this))
    return Inst->getParent();
  if (auto Arg = dyn_cast<SILArgument>(this))
    return Arg->getParent();
  return nullptr;
}
<|endoftext|>


<commit_before>/*
 * XYZLoader.cpp
 *
 * Copyright (C) 2010 by University of Stuttgart (VISUS).
 * All rights reserved.
 */

#include "stdafx.h"
#include "XYZLoader.h"
#include "ParticleDataCall.h"
#include "moldyn/MultiParticleDataCall.h"
#include "param/FilePathParam.h"
#include "param/IntParam.h"
#include "param/BoolParam.h"
#include "vislib/ArrayAllocator.h"
#include "vislib/Log.h"
#include "vislib/mathfunctions.h"
#include "vislib/MemmappedFile.h"
#include "vislib/SmartPtr.h"
#include "vislib/types.h"
#include "vislib/sysfunctions.h"
#include "vislib/StringConverter.h"
#include "vislib/StringTokeniser.h"
#include "vislib/ASCIIFileBuffer.h"
#include "vislib/Quaternion.h"
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <fstream>

#define USE_RANDOM_ROT_TRANS

using namespace megamol;
using namespace megamol::core;
using namespace megamol::protein;

/*
 * protein::XYZLoader::XYZLoader
 */
XYZLoader::XYZLoader(void) : megamol::core::Module(),
        filenameSlot( "filename", "The path to the XYZ data file to be loaded"),
        dataOutSlot( "dataout", "The slot providing the loaded data"),
        bbox(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f), datahash(0),
        particleCount( 0), particles( 0), colors( 0), charges( 0) {

    this->filenameSlot << new param::FilePathParam("");
    this->MakeSlotAvailable( &this->filenameSlot);

    this->dataOutSlot.SetCallback( ParticleDataCall::ClassName(), ParticleDataCall::FunctionName(ParticleDataCall::CallForGetData), &XYZLoader::getData);
    this->dataOutSlot.SetCallback( ParticleDataCall::ClassName(), ParticleDataCall::FunctionName(ParticleDataCall::CallForGetExtent), &XYZLoader::getExtent);

    this->dataOutSlot.SetCallback("MultiParticleDataCall", "GetData", &XYZLoader::getData);
    this->dataOutSlot.SetCallback("MultiParticleDataCall", "GetExtent", &XYZLoader::getExtent);
    this->MakeSlotAvailable( &this->dataOutSlot);

}

/*
 * protein::XYZLoader::~XYZLoader
 */
XYZLoader::~XYZLoader(void) {
    this->Release ();
}

/*
 * XYZLoader::create
 */
bool XYZLoader::create(void) {
    // intentionally empty
    return true;
}

/*
 * XYZLoader::getData
 */
bool XYZLoader::getData( core::Call& call) {
    using vislib::sys::Log;
    using namespace megamol::core::moldyn;

    ParticleDataCall *dc = dynamic_cast<ParticleDataCall*>( &call);
    MultiParticleDataCall *mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
    if ( dc == NULL && mpdc == NULL) return false;

    if ( this->filenameSlot.IsDirty() ) {
        this->filenameSlot.ResetDirty();
        if (mpdc != NULL) {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value(), false);
        } else {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value());
        }
    }

    if (dc != NULL) {
        dc->SetDataHash( this->datahash);

        // set values to call
        dc->SetParticleCount( this->particleCount);
        dc->SetParticles( this->particles);
        dc->SetColors( this->colors);
        dc->SetCharges( this->charges);
    } else {
        mpdc->SetDataHash( this->datahash);
        mpdc->SetFrameCount(1);
        // set values to call
        mpdc->SetParticleListCount(1);
        mpdc->AccessParticles(0).SetCount(this->particleCount);
        mpdc->AccessParticles(0).SetVertexData(SimpleSphericalParticles::VERTDATA_FLOAT_XYZR, this->particles);
        mpdc->AccessParticles(0).SetColourData(SimpleSphericalParticles::COLDATA_FLOAT_RGB, this->colors);
    }
    return true;
}

/*
 * XYZLoader::getExtent
 */
bool XYZLoader::getExtent( core::Call& call) {
    // get data call
    using namespace megamol::core::moldyn;
    ParticleDataCall *dc = dynamic_cast<ParticleDataCall*>( &call);
    MultiParticleDataCall *mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
    if ( dc == NULL && mpdc == NULL) return false;

    if ( this->filenameSlot.IsDirty() ) {
        this->filenameSlot.ResetDirty();
        if (mpdc != NULL) {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value(), false);
        } else {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value());
        }
    }

    if (dc != NULL) {
        dc->AccessBoundingBoxes().Clear();
        dc->AccessBoundingBoxes().SetObjectSpaceBBox( this->bbox);
        dc->AccessBoundingBoxes().SetObjectSpaceClipBox( this->bbox);

        dc->SetDataHash( this->datahash);
    } else {
        mpdc->SetFrameCount(1);
        mpdc->AccessBoundingBoxes().Clear();
        mpdc->AccessBoundingBoxes().SetObjectSpaceBBox( this->bbox);
        mpdc->AccessBoundingBoxes().SetObjectSpaceClipBox( this->bbox);

        mpdc->SetDataHash( this->datahash);
    }
    return true;
}

/*
 * XYZLoader::release
 */
void XYZLoader::release(void) {

}

/*
 * XYZLoader::loadFile
 */
void XYZLoader::loadFile( const vislib::TString& filename, bool doElectrostatics) {
    using vislib::sys::Log;

    this->bbox.Set( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);

    this->datahash++;

#ifdef USE_RANDOM_ROT_TRANS
    srand( static_cast<unsigned int>(time( NULL)));
    vislib::math::Vector<float, 3> rotAxis( static_cast<float>(rand()),
        static_cast<float>(rand()), static_cast<float>(rand()));
    rotAxis.Normalise();
    vislib::math::Vector<float, 3> trans( static_cast<float>(rand()),
        static_cast<float>(rand()), static_cast<float>(rand()));
    trans.Normalise();
    float angle = float( rand()) / float( RAND_MAX);
#endif

    vislib::StringA line, name;
    unsigned int cnt, pCnt;

    time_t t = clock(); // DEBUG

    vislib::sys::ASCIIFileBuffer file;
    vislib::Array<vislib::StringA> entries;
    vislib::math::Cuboid<float> sphereBBox;

    vislib::math::Vector<float, 3> color;
    vislib::math::Vector<float, 3> charge;

    // try to load the file
    if( file.LoadFile( T2A( filename) ) ) {
        // get particle count
        pCnt = atoi( file.Line( 0).Pointer());
        this->particleCount = pCnt;
        // resize arrays
        if( this->particles )
            delete[] this->particles;
        this->particles = new float[pCnt * 4];
        if( this->colors )
            delete[] this->colors;
        this->colors = new float[pCnt * 3];
        if( this->charges )
            delete[] this->charges;
        this->charges = new float[pCnt * 3];
        for( cnt = 0; cnt < pCnt; ++cnt ) {
            // get the current line from the file
            line = file.Line( cnt + 2);
            entries = vislib::StringTokeniser<vislib::CharTraitsA>::Split( line, " ", true);
            if( entries.Count() > 3 ) {
                // position
                this->particles[cnt*4+0] = static_cast<float>(atof( entries[1]));
                this->particles[cnt*4+1] = static_cast<float>(atof( entries[2]));
                this->particles[cnt*4+2] = static_cast<float>(atof( entries[3]));
                // radius
                this->particles[cnt*4+3] = this->getElementRadius( entries[0]);
                //color
                color = this->getElementColor( entries[0]);
                this->colors[cnt*3+0] = color.X();
                this->colors[cnt*3+1] = color.Y();
                this->colors[cnt*3+2] = color.Z();
                // charges
                if( entries.Count() > 4 )
                    this->charges[cnt*3+0] = static_cast<float>(atof( entries[4]));
                if( entries.Count() > 5 )
                    this->charges[cnt*3+1] = static_cast<float>(atof( entries[5]));
                if( entries.Count() > 6 )
                    this->charges[cnt*3+2] = static_cast<float>(atof( entries[6]));
                // update the bounding box
                sphereBBox.Set(
                    this->particles[cnt*4+0] - this->particles[cnt*4+3],
                    this->particles[cnt*4+1] - this->particles[cnt*4+3],
                    this->particles[cnt*4+2] - this->particles[cnt*4+3],
                    this->particles[cnt*4+0] + this->particles[cnt*4+3],
                    this->particles[cnt*4+1] + this->particles[cnt*4+3],
                    this->particles[cnt*4+2] + this->particles[cnt*4+3] );
                if( cnt == 0 ) {
                    this->bbox = sphereBBox;
                } else {
                    this->bbox.Union( sphereBBox);
                }
            }
        }

        if (doElectrostatics) {
            float edge = this->bbox.LongestEdge() * 5.0f;
            this->bbox.Grow( edge, edge, edge);

#ifdef USE_RANDOM_ROT_TRANS
            vislib::math::Vector<float, 3> center( 0, 0, 0);
            for( unsigned int i = 0; i < this->particleCount; i++ ) {
                center += vislib::math::Vector<float, 3>( this->particles[i*4+0], this->particles[i*4+1], this->particles[i*4+2]);
            }
            center /= float( this->particleCount);
            vislib::math::Quaternion<float> quart( angle, rotAxis);
            for( unsigned int i = 0; i < this->particleCount; i++ ) {
                vislib::math::Vector<float, 3> part( this->particles[i*4+0], this->particles[i*4+1], this->particles[i*4+2]);
                part -= center;
                part = quart * part;
                part += center;
                part += trans;
                this->particles[i*4+0] = part.X();
                this->particles[i*4+1] = part.Y();
                this->particles[i*4+2] = part.Z();
            }
#endif
        }
        Log::DefaultLog.WriteMsg( Log::LEVEL_INFO, "Time for loading file %s: %f", static_cast<const char*>(T2A( filename)), ( double( clock() - t) / double( CLOCKS_PER_SEC) )); // DEBUG
    } else {
        Log::DefaultLog.WriteMsg( Log::LEVEL_ERROR, "Could not load file %s", static_cast<const char*>(T2A( filename))); // DEBUG
    }
}

/*
 * Get the radius of the element
 */
float XYZLoader::getElementRadius( vislib::StringA name) {
    // extract the element symbol from the name
    unsigned int cnt = 0;
    vislib::StringA element;
    while( cnt < static_cast<unsigned int>(name.Length()) && vislib::CharTraitsA::IsDigit( name[cnt]) ) {
        cnt++;
    }

    // --- van der Waals radii ---
    if( cnt < static_cast<unsigned int>(name.Length()) ) {
        if( name[cnt] == 'H' )
            return 1.2f;
        else if( name[cnt] == 'C' ) {
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                if( name[cnt+1] == 'l' )
                    return 1.75f; // chlorine
            return 1.7f; // carbon
        } else if( name[cnt] == 'O' )
            return 1.52f;
        else if( name[cnt] == 'S' )
            return 1.8f;
        else if( name[cnt] == 'P' )
            return 1.8f;
        else if( name[cnt] == 'C' )
            return 1.7f;
        else if( name[cnt] == 'N' ) {
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                if( name[cnt+1] == 'i' )
                    return 1.63f; // nickel
            return 1.55f; // nitrogen
        }
    }

    return 1.5f;
}

/*
 * Get the color of the element
 */
vislib::math::Vector<float, 3> XYZLoader::getElementColor( vislib::StringA name) {
    // extract the element symbol from the name
    unsigned int cnt = 0;
    vislib::StringA element;
    while( cnt < static_cast<unsigned int>(name.Length()) && vislib::CharTraitsA::IsDigit( name[cnt]) ) {
        cnt++;
    }

    // default color
    vislib::math::Vector<unsigned char, 3> col( 191, 191, 191);
    vislib::math::Vector<float, 3> colFloat;

    // check element
    if( cnt < static_cast<unsigned int>(name.Length()) ) {
        if( name[cnt] == 'H' ) // white or light grey
            col.Set( 240, 240, 240);
        else if( name[cnt] == 'C' ) {
            // Carbon: (dark) grey or green
            col.Set( 125, 125, 125);
            //col.Set( 90, 175, 50);
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                // Chlorine: yellowgreen
                col.Set( 173, 255, 47);
        } else if( name[cnt] == 'N' ) // blue
            //col.Set( 37, 136, 195);
            col.Set( 37, 136, 195);
        else if( name[cnt] == 'O' ) // red
            //col.Set( 250, 94, 82);
            col.Set( 206, 34, 34);
        else if( name[cnt] == 'S' ) // yellow
            //col.Set( 250, 230, 50);
            col.Set( 255, 215, 0);
        else if( name[cnt] == 'P' ) // orange
            col.Set( 255, 128, 64);
    }

    colFloat.Set( float( col.X()) / 255.0f, float( col.Y()) / 255.0f, float( col.Z()) / 255.0f);
    return colFloat;
}
<commit_msg>- taught the XYZLoader to read Nickel<commit_after>/*
 * XYZLoader.cpp
 *
 * Copyright (C) 2010 by University of Stuttgart (VISUS).
 * All rights reserved.
 */

#include "stdafx.h"
#include "XYZLoader.h"
#include "ParticleDataCall.h"
#include "moldyn/MultiParticleDataCall.h"
#include "param/FilePathParam.h"
#include "param/IntParam.h"
#include "param/BoolParam.h"
#include "vislib/ArrayAllocator.h"
#include "vislib/Log.h"
#include "vislib/mathfunctions.h"
#include "vislib/MemmappedFile.h"
#include "vislib/SmartPtr.h"
#include "vislib/types.h"
#include "vislib/sysfunctions.h"
#include "vislib/StringConverter.h"
#include "vislib/StringTokeniser.h"
#include "vislib/ASCIIFileBuffer.h"
#include "vislib/Quaternion.h"
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <fstream>

#define USE_RANDOM_ROT_TRANS

using namespace megamol;
using namespace megamol::core;
using namespace megamol::protein;

/*
 * protein::XYZLoader::XYZLoader
 */
XYZLoader::XYZLoader(void) : megamol::core::Module(),
        filenameSlot( "filename", "The path to the XYZ data file to be loaded"),
        dataOutSlot( "dataout", "The slot providing the loaded data"),
        bbox(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f), datahash(0),
        particleCount( 0), particles( 0), colors( 0), charges( 0) {

    this->filenameSlot << new param::FilePathParam("");
    this->MakeSlotAvailable( &this->filenameSlot);

    this->dataOutSlot.SetCallback( ParticleDataCall::ClassName(), ParticleDataCall::FunctionName(ParticleDataCall::CallForGetData), &XYZLoader::getData);
    this->dataOutSlot.SetCallback( ParticleDataCall::ClassName(), ParticleDataCall::FunctionName(ParticleDataCall::CallForGetExtent), &XYZLoader::getExtent);

    this->dataOutSlot.SetCallback("MultiParticleDataCall", "GetData", &XYZLoader::getData);
    this->dataOutSlot.SetCallback("MultiParticleDataCall", "GetExtent", &XYZLoader::getExtent);
    this->MakeSlotAvailable( &this->dataOutSlot);

}

/*
 * protein::XYZLoader::~XYZLoader
 */
XYZLoader::~XYZLoader(void) {
    this->Release ();
}

/*
 * XYZLoader::create
 */
bool XYZLoader::create(void) {
    // intentionally empty
    return true;
}

/*
 * XYZLoader::getData
 */
bool XYZLoader::getData( core::Call& call) {
    using vislib::sys::Log;
    using namespace megamol::core::moldyn;

    ParticleDataCall *dc = dynamic_cast<ParticleDataCall*>( &call);
    MultiParticleDataCall *mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
    if ( dc == NULL && mpdc == NULL) return false;

    if ( this->filenameSlot.IsDirty() ) {
        this->filenameSlot.ResetDirty();
        if (mpdc != NULL) {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value(), false);
        } else {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value());
        }
    }

    if (dc != NULL) {
        dc->SetDataHash( this->datahash);

        // set values to call
        dc->SetParticleCount( this->particleCount);
        dc->SetParticles( this->particles);
        dc->SetColors( this->colors);
        dc->SetCharges( this->charges);
    } else {
        mpdc->SetDataHash( this->datahash);
        mpdc->SetFrameCount(1);
        // set values to call
        mpdc->SetParticleListCount(1);
        mpdc->AccessParticles(0).SetCount(this->particleCount);
        mpdc->AccessParticles(0).SetVertexData(SimpleSphericalParticles::VERTDATA_FLOAT_XYZR, this->particles);
        mpdc->AccessParticles(0).SetColourData(SimpleSphericalParticles::COLDATA_FLOAT_RGB, this->colors);
    }
    return true;
}

/*
 * XYZLoader::getExtent
 */
bool XYZLoader::getExtent( core::Call& call) {
    // get data call
    using namespace megamol::core::moldyn;
    ParticleDataCall *dc = dynamic_cast<ParticleDataCall*>( &call);
    MultiParticleDataCall *mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
    if ( dc == NULL && mpdc == NULL) return false;

    if ( this->filenameSlot.IsDirty() ) {
        this->filenameSlot.ResetDirty();
        if (mpdc != NULL) {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value(), false);
        } else {
            this->loadFile( this->filenameSlot.Param<core::param::FilePathParam>()->Value());
        }
    }

    if (dc != NULL) {
        dc->AccessBoundingBoxes().Clear();
        dc->AccessBoundingBoxes().SetObjectSpaceBBox( this->bbox);
        dc->AccessBoundingBoxes().SetObjectSpaceClipBox( this->bbox);

        dc->SetDataHash( this->datahash);
    } else {
        mpdc->SetFrameCount(1);
        mpdc->AccessBoundingBoxes().Clear();
        mpdc->AccessBoundingBoxes().SetObjectSpaceBBox( this->bbox);
        mpdc->AccessBoundingBoxes().SetObjectSpaceClipBox( this->bbox);

        mpdc->SetDataHash( this->datahash);
    }
    return true;
}

/*
 * XYZLoader::release
 */
void XYZLoader::release(void) {

}

/*
 * XYZLoader::loadFile
 */
void XYZLoader::loadFile( const vislib::TString& filename, bool doElectrostatics) {
    using vislib::sys::Log;

    this->bbox.Set( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);

    this->datahash++;

#ifdef USE_RANDOM_ROT_TRANS
    srand( static_cast<unsigned int>(time( NULL)));
    vislib::math::Vector<float, 3> rotAxis( static_cast<float>(rand()),
        static_cast<float>(rand()), static_cast<float>(rand()));
    rotAxis.Normalise();
    vislib::math::Vector<float, 3> trans( static_cast<float>(rand()),
        static_cast<float>(rand()), static_cast<float>(rand()));
    trans.Normalise();
    float angle = float( rand()) / float( RAND_MAX);
#endif

    vislib::StringA line, name;
    unsigned int cnt, pCnt;

    time_t t = clock(); // DEBUG

    vislib::sys::ASCIIFileBuffer file;
    vislib::Array<vislib::StringA> entries;
    vislib::math::Cuboid<float> sphereBBox;

    vislib::math::Vector<float, 3> color;
    vislib::math::Vector<float, 3> charge;

    // try to load the file
    if( file.LoadFile( T2A( filename) ) ) {
        // get particle count
        pCnt = atoi( file.Line( 0).Pointer());
        this->particleCount = pCnt;
        // resize arrays
        if( this->particles )
            delete[] this->particles;
        this->particles = new float[pCnt * 4];
        if( this->colors )
            delete[] this->colors;
        this->colors = new float[pCnt * 3];
        if( this->charges )
            delete[] this->charges;
        this->charges = new float[pCnt * 3];
        for( cnt = 0; cnt < pCnt; ++cnt ) {
            // get the current line from the file
            line = file.Line( cnt + 2);
            entries = vislib::StringTokeniser<vislib::CharTraitsA>::Split( line, " ", true);
            if( entries.Count() > 3 ) {
                // position
                this->particles[cnt*4+0] = static_cast<float>(atof( entries[1]));
                this->particles[cnt*4+1] = static_cast<float>(atof( entries[2]));
                this->particles[cnt*4+2] = static_cast<float>(atof( entries[3]));
                // radius
                this->particles[cnt*4+3] = this->getElementRadius( entries[0]);
                //color
                color = this->getElementColor( entries[0]);
                this->colors[cnt*3+0] = color.X();
                this->colors[cnt*3+1] = color.Y();
                this->colors[cnt*3+2] = color.Z();
                // charges
                if( entries.Count() > 4 )
                    this->charges[cnt*3+0] = static_cast<float>(atof( entries[4]));
                if( entries.Count() > 5 )
                    this->charges[cnt*3+1] = static_cast<float>(atof( entries[5]));
                if( entries.Count() > 6 )
                    this->charges[cnt*3+2] = static_cast<float>(atof( entries[6]));
                // update the bounding box
                sphereBBox.Set(
                    this->particles[cnt*4+0] - this->particles[cnt*4+3],
                    this->particles[cnt*4+1] - this->particles[cnt*4+3],
                    this->particles[cnt*4+2] - this->particles[cnt*4+3],
                    this->particles[cnt*4+0] + this->particles[cnt*4+3],
                    this->particles[cnt*4+1] + this->particles[cnt*4+3],
                    this->particles[cnt*4+2] + this->particles[cnt*4+3] );
                if( cnt == 0 ) {
                    this->bbox = sphereBBox;
                } else {
                    this->bbox.Union( sphereBBox);
                }
            }
        }

        if (doElectrostatics) {
            float edge = this->bbox.LongestEdge() * 5.0f;
            this->bbox.Grow( edge, edge, edge);

#ifdef USE_RANDOM_ROT_TRANS
            vislib::math::Vector<float, 3> center( 0, 0, 0);
            for( unsigned int i = 0; i < this->particleCount; i++ ) {
                center += vislib::math::Vector<float, 3>( this->particles[i*4+0], this->particles[i*4+1], this->particles[i*4+2]);
            }
            center /= float( this->particleCount);
            vislib::math::Quaternion<float> quart( angle, rotAxis);
            for( unsigned int i = 0; i < this->particleCount; i++ ) {
                vislib::math::Vector<float, 3> part( this->particles[i*4+0], this->particles[i*4+1], this->particles[i*4+2]);
                part -= center;
                part = quart * part;
                part += center;
                part += trans;
                this->particles[i*4+0] = part.X();
                this->particles[i*4+1] = part.Y();
                this->particles[i*4+2] = part.Z();
            }
#endif
        }
        Log::DefaultLog.WriteMsg( Log::LEVEL_INFO, "Time for loading file %s: %f", static_cast<const char*>(T2A( filename)), ( double( clock() - t) / double( CLOCKS_PER_SEC) )); // DEBUG
    } else {
        Log::DefaultLog.WriteMsg( Log::LEVEL_ERROR, "Could not load file %s", static_cast<const char*>(T2A( filename))); // DEBUG
    }
}

/*
 * Get the radius of the element
 */
float XYZLoader::getElementRadius( vislib::StringA name) {
    // extract the element symbol from the name
    unsigned int cnt = 0;
    vislib::StringA element;
    while( cnt < static_cast<unsigned int>(name.Length()) && vislib::CharTraitsA::IsDigit( name[cnt]) ) {
        cnt++;
    }

    // --- van der Waals radii ---
    if( cnt < static_cast<unsigned int>(name.Length()) ) {
        if( name[cnt] == 'H' )
            return 1.2f;
        else if( name[cnt] == 'C' ) {
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                if( name[cnt+1] == 'l' )
                    return 1.75f; // chlorine
            return 1.7f; // carbon
        } else if( name[cnt] == 'O' )
            return 1.52f;
        else if( name[cnt] == 'S' )
            return 1.8f;
        else if( name[cnt] == 'P' )
            return 1.8f;
        else if( name[cnt] == 'C' )
            return 1.7f;
        else if( name[cnt] == 'N' ) {
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                if( name[cnt+1] == 'i' )
                    return 1.63f; // nickel
            return 1.55f; // nitrogen
        }
    }

    return 1.5f;
}

/*
 * Get the color of the element
 */
vislib::math::Vector<float, 3> XYZLoader::getElementColor( vislib::StringA name) {
    // extract the element symbol from the name
    unsigned int cnt = 0;
    vislib::StringA element;
    while( cnt < static_cast<unsigned int>(name.Length()) && vislib::CharTraitsA::IsDigit( name[cnt]) ) {
        cnt++;
    }

    // default color
    vislib::math::Vector<unsigned char, 3> col( 191, 191, 191);
    vislib::math::Vector<float, 3> colFloat;

    // check element
    if( cnt < static_cast<unsigned int>(name.Length()) ) {
        if( name[cnt] == 'H' ) // white or light grey
            col.Set( 240, 240, 240);
        else if( name[cnt] == 'C' ) {
            // Carbon: (dark) grey or green
            col.Set( 125, 125, 125);
            //col.Set( 90, 175, 50);
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) )
                // Chlorine: yellowgreen
                col.Set( 173, 255, 47);
        } else if( name[cnt] == 'O' ) // red
            //col.Set( 250, 94, 82);
            col.Set( 206, 34, 34);
        else if( name[cnt] == 'S' ) // yellow
            //col.Set( 250, 230, 50);
            col.Set( 255, 215, 0);
        else if( name[cnt] == 'P' ) // orange
            col.Set( 255, 128, 64);
        else if( name[cnt] == 'N' ) {
            if( ( cnt + 1) < static_cast<unsigned int>(name.Length()) ) {
                if( name[cnt+1] == 'i' )
                    col.Set( 136, 136, 136); // nickel
            } else {
                col.Set( 37, 136, 195); // nitrogen
            }
        }
    }

    colFloat.Set( float( col.X()) / 255.0f, float( col.Y()) / 255.0f, float( col.Z()) / 255.0f);
    return colFloat;
}
<|endoftext|>


<commit_before>#include "gamelib/core/rendering/SceneObject.hpp"
#include "gamelib/core/rendering/Scene.hpp"
#include "gamelib/core/rendering/flags.hpp"
#include "gamelib/utils/json.hpp"
#include <cassert>

namespace gamelib
{
    SceneObject::SceneObject(int depth, float parallax, unsigned int flags) :
        SceneData(depth, parallax, flags),
        Transformable(movable | rotatable | scalable),
        _scale(1, 1),
        _rotation(0)
    { };

    void SceneObject::setLayer(Layer::Handle layer)
    {
        if (!_scene)
            _layer = layer;
        else if (layer != _layer)
        {
            _layer = layer;
            _scene->_dirty = true;
        }
    }

    Layer::Handle SceneObject::getLayer() const
    {
        return _layer;
    }

    unsigned int SceneObject::getAllFlags() const
    {
        assert(_scene && "Scene is null");
        Layer* layer = _scene->getLayer(_layer);
        return flags | _scene->flags | (layer ? layer->flags : 0);
    }

    bool SceneObject::isVisible() const
    {
        auto allflags = getAllFlags();
        return !(allflags & render_invisible ||
                (allflags & render_hidden && !(allflags & render_drawhidden)));
    }

    void SceneObject::unregister()
    {
        if (_scene)
            _scene->remove(this);
    }

    void SceneObject::render(sf::RenderTarget& target) const
    {
        render(target, sf::RenderStates());
    }

    void SceneObject::render(sf::RenderTarget& target, const sf::RenderStates& states_) const
    {
        sf::RenderStates states(states_);
        states.transform.combine(getTransform());
        target.draw(_vertices, states);
    }

    void SceneObject::_updateBBox()
    {
        auto bounds = getTransform().transformRect(_vertices.getBounds());
        _bbox = math::AABBf(bounds.left, bounds.top, bounds.width, bounds.height);
        markDirty();
    }

    bool SceneObject::loadFromJson(const Json::Value& node)
    {
        SceneData::loadFromJson(node);

        auto scene = _scene ? _scene : getSubsystem<Scene>();
        auto layer = scene->getLayer(node["layer"].asString());
        if (!layer.isNull())
            setLayer(layer);

        gamelib::loadFromJson(node["transform"], *static_cast<Transformable*>(this));
        gamelib::loadFromJson(node["origin"], _origin);

        return true;
    }

    void SceneObject::writeToJson(Json::Value& node)
    {
        SceneData::writeToJson(node);

        auto scene = _scene ? _scene : getSubsystem<Scene>();
        auto layer = scene->getLayer(getLayer());
        if (layer)
            node["layer"] = layer->getName();

        gamelib::writeToJson(node["transform"], *static_cast<Transformable*>(this));
        gamelib::writeToJson(node["origin"], _origin);
    }

    void SceneObject::move(const math::Vec2f& rel)
    {
        _bbox.pos += rel;
        _pos += rel;
        _updateBBox();
        Transformable::move(rel);
    }

    void SceneObject::scale(const math::Vec2f& scale)
    {
        _bbox.size *= scale;
        _scale *= scale;
        _updateBBox();
        Transformable::scale(scale);
    }

    void SceneObject::rotate(float angle)
    {
        _rotation += angle;
        _updateBBox();
        Transformable::rotate(angle);
    }

    void SceneObject::setOrigin(const math::Point2f& origin)
    {
        _origin = origin;
    }

    const math::Point2f& SceneObject::getOrigin() const
    {
        return _origin;
    }

    const math::Point2f& SceneObject::getPosition() const
    {
        return _pos;
    }

    const math::Vec2f& SceneObject::getScale() const
    {
        return _scale;
    }

    float SceneObject::getRotation() const
    {
        return _rotation;
    }

    const math::AABBf& SceneObject::getBBox() const
    {
        return _bbox;
    }

    math::AABBf SceneObject::getLocalBounds() const
    {
        auto bounds = _vertices.getBounds();
        return math::AABBf(bounds.left, bounds.top, bounds.width, bounds.height);
    }

    sf::Transform SceneObject::getTransform() const
    {
        sf::Transform trans;
        trans.translate(_pos.x - _origin.x, _pos.y - _origin.y);
        trans.rotate(_rotation, _origin.x, _origin.y);
        trans.scale(_scale.x, _scale.y, _origin.x, _origin.y);
        return trans;
    }
}
<commit_msg>Fix segfault in SceneObject's writeToJson()<commit_after>#include "gamelib/core/rendering/SceneObject.hpp"
#include "gamelib/core/rendering/Scene.hpp"
#include "gamelib/core/rendering/flags.hpp"
#include "gamelib/utils/json.hpp"
#include <cassert>

namespace gamelib
{
    SceneObject::SceneObject(int depth, float parallax, unsigned int flags) :
        SceneData(depth, parallax, flags),
        Transformable(movable | rotatable | scalable),
        _scale(1, 1),
        _rotation(0)
    { };

    void SceneObject::setLayer(Layer::Handle layer)
    {
        if (!_scene)
            _layer = layer;
        else if (layer != _layer)
        {
            _layer = layer;
            _scene->_dirty = true;
        }
    }

    Layer::Handle SceneObject::getLayer() const
    {
        return _layer;
    }

    unsigned int SceneObject::getAllFlags() const
    {
        assert(_scene && "Scene is null");
        Layer* layer = _scene->getLayer(_layer);
        return flags | _scene->flags | (layer ? layer->flags : 0);
    }

    bool SceneObject::isVisible() const
    {
        auto allflags = getAllFlags();
        return !(allflags & render_invisible ||
                (allflags & render_hidden && !(allflags & render_drawhidden)));
    }

    void SceneObject::unregister()
    {
        if (_scene)
            _scene->remove(this);
    }

    void SceneObject::render(sf::RenderTarget& target) const
    {
        render(target, sf::RenderStates());
    }

    void SceneObject::render(sf::RenderTarget& target, const sf::RenderStates& states_) const
    {
        sf::RenderStates states(states_);
        states.transform.combine(getTransform());
        target.draw(_vertices, states);
    }

    void SceneObject::_updateBBox()
    {
        auto bounds = getTransform().transformRect(_vertices.getBounds());
        _bbox = math::AABBf(bounds.left, bounds.top, bounds.width, bounds.height);
        markDirty();
    }

    bool SceneObject::loadFromJson(const Json::Value& node)
    {
        SceneData::loadFromJson(node);

        auto scene = _scene ? _scene : getSubsystem<Scene>();
        assert(scene && "There must be a Scene to load this component");

        auto layer = scene->getLayer(node["layer"].asString());
        if (!layer.isNull())
            setLayer(layer);

        gamelib::loadFromJson(node["transform"], *static_cast<Transformable*>(this));
        gamelib::loadFromJson(node["origin"], _origin);

        return true;
    }

    void SceneObject::writeToJson(Json::Value& node)
    {
        SceneData::writeToJson(node);

        auto scene = _scene ? _scene : getSubsystem<Scene>();
        if (scene)
        {
            auto layer = scene->getLayer(getLayer());
            if (layer)
                node["layer"] = layer->getName();
        }

        gamelib::writeToJson(node["transform"], *static_cast<Transformable*>(this));
        gamelib::writeToJson(node["origin"], _origin);
    }

    void SceneObject::move(const math::Vec2f& rel)
    {
        _bbox.pos += rel;
        _pos += rel;
        _updateBBox();
        Transformable::move(rel);
    }

    void SceneObject::scale(const math::Vec2f& scale)
    {
        _bbox.size *= scale;
        _scale *= scale;
        _updateBBox();
        Transformable::scale(scale);
    }

    void SceneObject::rotate(float angle)
    {
        _rotation += angle;
        _updateBBox();
        Transformable::rotate(angle);
    }

    void SceneObject::setOrigin(const math::Point2f& origin)
    {
        _origin = origin;
    }

    const math::Point2f& SceneObject::getOrigin() const
    {
        return _origin;
    }

    const math::Point2f& SceneObject::getPosition() const
    {
        return _pos;
    }

    const math::Vec2f& SceneObject::getScale() const
    {
        return _scale;
    }

    float SceneObject::getRotation() const
    {
        return _rotation;
    }

    const math::AABBf& SceneObject::getBBox() const
    {
        return _bbox;
    }

    math::AABBf SceneObject::getLocalBounds() const
    {
        auto bounds = _vertices.getBounds();
        return math::AABBf(bounds.left, bounds.top, bounds.width, bounds.height);
    }

    sf::Transform SceneObject::getTransform() const
    {
        sf::Transform trans;
        trans.translate(_pos.x - _origin.x, _pos.y - _origin.y);
        trans.rotate(_rotation, _origin.x, _origin.y);
        trans.scale(_scale.x, _scale.y, _origin.x, _origin.y);
        return trans;
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp

#include <NDK/Systems/RenderSystem.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Graphics/ColorBackground.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>

namespace Ndk
{
	RenderSystem::RenderSystem()
	{
	}

	void RenderSystem::OnEntityRemoved(Entity* entity)
	{
		m_cameras.Remove(entity);
		m_drawables.Remove(entity);
		m_lights.Remove(entity);
	}

	void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded)
	{
		if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>())
		{
			m_cameras.Insert(entity);
			std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2)
			{
				return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer();
			});
		}
		else
			m_cameras.Remove(entity);

		if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
			m_drawables.Insert(entity);
		else
			m_drawables.Remove(entity);

		if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
			m_lights.Insert(entity);
		else
			m_lights.Remove(entity);
	}

	void RenderSystem::OnEntityRemoved(Entity* entity)
	{
		m_cameras.Remove(entity);
		m_drawables.Remove(entity);
		m_lights.Remove(entity);
	}

	void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded)
	{
		if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>())
		{
			m_cameras.Insert(entity);
			std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2)
			{
				return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer();
			});
		}
		else
			m_cameras.Remove(entity);

		if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
			m_drawables.Insert(entity);
		else
			m_drawables.Remove(entity);

		if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
			m_lights.Insert(entity);
		else
			m_lights.Remove(entity);
	}

	void RenderSystem::OnUpdate(float elapsedTime)
	{
		UpdateShadowMaps();

		for (const Ndk::EntityHandle& camera : m_cameras)
		{
			CameraComponent& camComponent = camera->GetComponent<CameraComponent>();
			camComponent.ApplyView();

			NzAbstractRenderQueue* renderQueue = m_renderTechnique.GetRenderQueue();
			renderQueue->Clear();

			for (const Ndk::EntityHandle& drawable : m_drawables)
			{
				GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
				NodeComponent& drawableNode = drawable->GetComponent<NodeComponent>();

				graphicsComponent.AddToRenderQueue(renderQueue);
			}

			for (const Ndk::EntityHandle& light : m_lights)
			{
				LightComponent& lightComponent = light->GetComponent<LightComponent>();
				NodeComponent& lightNode = light->GetComponent<NodeComponent>();

				lightComponent.AddToRenderQueue(renderQueue, lightNode.GetTransformMatrix());
			}

			NzColorBackground background;

			NzSceneData sceneData;
			sceneData.ambientColor = NzColor(25, 25, 25);
			sceneData.background = &background;
			sceneData.viewer = &camComponent;

			m_renderTechnique.Draw(sceneData);
		}
	}

	void RenderSystem::UpdateShadowMaps()
	{
		if (!m_shadowRT.IsValid())
			m_shadowRT.Create();

		for (const Ndk::EntityHandle& light : m_lights)
		{
			LightComponent& lightComponent = light->GetComponent<LightComponent>();
			NodeComponent& lightNode = light->GetComponent<NodeComponent>();

			if (!lightComponent.IsShadowCastingEnabled() || lightComponent.GetLightType() != nzLightType_Spot)
				continue;

			NzVector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());

			m_shadowRT.AttachTexture(nzAttachmentPoint_Depth, 0, lightComponent.GetShadowMap());

			///TODO: Cache the matrices in the light?
			NzRenderer::SetMatrix(nzMatrixType_Projection, NzMatrix4f::Perspective(lightComponent.GetOuterAngle(), 1.f, 1.f, 1000.f));
			NzRenderer::SetMatrix(nzMatrixType_View, NzMatrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation()));
			NzRenderer::SetTarget(&m_shadowRT);
			NzRenderer::SetViewport(NzRecti(0, 0, shadowMapSize.x, shadowMapSize.y));

			NzAbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
			renderQueue->Clear();

			for (const Ndk::EntityHandle& drawable : m_drawables)
			{
				GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
				NodeComponent& drawableNode = drawable->GetComponent<NodeComponent>();

				graphicsComponent.AddToRenderQueue(renderQueue);
			}

			NzSceneData sceneData;
			sceneData.ambientColor = NzColor(0, 0, 0);
			sceneData.background = nullptr;
			sceneData.viewer = nullptr; //< Depth technique doesn't require any viewer

			m_shadowTechnique.Draw(sceneData);
		}
	}

	SystemIndex RenderSystem::systemIndex;
}
<commit_msg>Sdk/RenderSystem: Fix code duplication (merge fail)<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp

#include <NDK/Systems/RenderSystem.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Graphics/ColorBackground.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>

namespace Ndk
{
	RenderSystem::RenderSystem()
	{
	}

	void RenderSystem::OnEntityRemoved(Entity* entity)
	{
		m_cameras.Remove(entity);
		m_drawables.Remove(entity);
		m_lights.Remove(entity);
	}

	void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded)
	{
		if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>())
		{
			m_cameras.Insert(entity);
			std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2)
			{
				return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer();
			});
		}
		else
			m_cameras.Remove(entity);

		if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
			m_drawables.Insert(entity);
		else
			m_drawables.Remove(entity);

		if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
			m_lights.Insert(entity);
		else
			m_lights.Remove(entity);
	}

	void RenderSystem::OnUpdate(float elapsedTime)
	{
		UpdateShadowMaps();

		for (const Ndk::EntityHandle& camera : m_cameras)
		{
			CameraComponent& camComponent = camera->GetComponent<CameraComponent>();
			camComponent.ApplyView();

			NzAbstractRenderQueue* renderQueue = m_renderTechnique.GetRenderQueue();
			renderQueue->Clear();

			for (const Ndk::EntityHandle& drawable : m_drawables)
			{
				GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
				NodeComponent& drawableNode = drawable->GetComponent<NodeComponent>();

				graphicsComponent.AddToRenderQueue(renderQueue);
			}

			for (const Ndk::EntityHandle& light : m_lights)
			{
				LightComponent& lightComponent = light->GetComponent<LightComponent>();
				NodeComponent& lightNode = light->GetComponent<NodeComponent>();

				lightComponent.AddToRenderQueue(renderQueue, lightNode.GetTransformMatrix());
			}

			NzColorBackground background;

			NzSceneData sceneData;
			sceneData.ambientColor = NzColor(25, 25, 25);
			sceneData.background = &background;
			sceneData.viewer = &camComponent;

			m_renderTechnique.Draw(sceneData);
		}
	}

	void RenderSystem::UpdateShadowMaps()
	{
		if (!m_shadowRT.IsValid())
			m_shadowRT.Create();

		for (const Ndk::EntityHandle& light : m_lights)
		{
			LightComponent& lightComponent = light->GetComponent<LightComponent>();
			NodeComponent& lightNode = light->GetComponent<NodeComponent>();

			if (!lightComponent.IsShadowCastingEnabled() || lightComponent.GetLightType() != nzLightType_Spot)
				continue;

			NzVector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());

			m_shadowRT.AttachTexture(nzAttachmentPoint_Depth, 0, lightComponent.GetShadowMap());

			///TODO: Cache the matrices in the light?
			NzRenderer::SetMatrix(nzMatrixType_Projection, NzMatrix4f::Perspective(lightComponent.GetOuterAngle(), 1.f, 1.f, 1000.f));
			NzRenderer::SetMatrix(nzMatrixType_View, NzMatrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation()));
			NzRenderer::SetTarget(&m_shadowRT);
			NzRenderer::SetViewport(NzRecti(0, 0, shadowMapSize.x, shadowMapSize.y));

			NzAbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
			renderQueue->Clear();

			for (const Ndk::EntityHandle& drawable : m_drawables)
			{
				GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
				NodeComponent& drawableNode = drawable->GetComponent<NodeComponent>();

				graphicsComponent.AddToRenderQueue(renderQueue);
			}

			NzSceneData sceneData;
			sceneData.ambientColor = NzColor(0, 0, 0);
			sceneData.background = nullptr;
			sceneData.viewer = nullptr; //< Depth technique doesn't require any viewer

			m_shadowTechnique.Draw(sceneData);
		}
	}

	SystemIndex RenderSystem::systemIndex;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basdoc.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: vg $ $Date: 2007-01-16 16:27:22 $
 *
 *  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_basctl.hxx"

#include <ide_pch.hxx>

#define GLOBALOVERFLOW2

#include <sfx2/docfac.hxx>

#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif

#include <svx/xmlsecctrl.hxx>

#include <basdoc.hxx>

#define BasicDocShell
#include <basslots.hxx>

#include "basicmod.hxx"
#include "unomodel.hxx"

TYPEINIT1(BasicDocShell, SfxObjectShell);
DBG_NAME(BasicDocShell);

SFX_IMPL_OBJECTFACTORY( BasicDocShell, SvGlobalName(), SFXOBJECTSHELL_STD_NORMAL, "sbasic" )

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( SID_BASICIDE_STATUSBAR );
}

BasicDocShell::BasicDocShell( SfxObjectCreateMode eMode ) : SfxObjectShell( eMode )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
    SetModel( new SIDEModel(this) );
}

__EXPORT BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

void __EXPORT BasicDocShell::Execute( SfxRequest& )
{
}

void __EXPORT BasicDocShell::GetState( SfxItemSet& )
{
}

SfxPrinter* BasicDocShell::GetPrinter( BOOL bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillStatusBar( StatusBar& rStatusBar )
{
    String aTmp;

    // Titel
    aTmp.Fill( 30, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_TITLE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT);

    // Modify
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
        rStatusBar.GetTextWidth( '*' ) );

    // signatures
    rStatusBar.InsertItem( SID_SIGNATURE, XmlSecStatusBarControl::GetDefItemWidth( rStatusBar ), SIB_USERDRAW );
    rStatusBar.SetHelpId(SID_SIGNATURE, SID_SIGNATURE);

    // Position
    aTmp.Erase();
    aTmp.Fill( 15, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_POS,
        rStatusBar.GetTextWidth( aTmp ), SIB_LEFT);

    // Insert/Overwrite
    rStatusBar.InsertItem( SID_ATTR_INSERT,
        rStatusBar.GetTextWidth( String( RTL_CONSTASCII_USTRINGPARAM( "XXXXX" /* "EINFG" */ ) ) ) );

    // Uhrzeit
    aTmp.Fill( 20, 'X' );
    rStatusBar.InsertItem( SID_ATTR_SIZE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT | SIB_USERDRAW );

//  return pStatusBar;

}

void BasicDocShell::FillClass( SvGlobalName*, sal_uInt32*, String*, String*, String*, sal_Int32) const
{}

void BasicDocShell::Draw( OutputDevice *, const JobSetup &, USHORT )
{}

<commit_msg>INTEGRATION: CWS basmgr02 (1.16.48); FILE MERGED 2007/01/30 14:58:47 fs 1.16.48.2: RESYNC: (1.16-1.17); FILE MERGED 2007/01/17 11:36:35 fs 1.16.48.1: #i73329# +SetHasNoBasic<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basdoc.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 15:51:10 $
 *
 *  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_basctl.hxx"

#include <ide_pch.hxx>

#define GLOBALOVERFLOW2

#include <sfx2/docfac.hxx>

#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif

#include <svx/xmlsecctrl.hxx>

#include <basdoc.hxx>

#define BasicDocShell
#include <basslots.hxx>

#include "basicmod.hxx"
#include "unomodel.hxx"

TYPEINIT1(BasicDocShell, SfxObjectShell);
DBG_NAME(BasicDocShell);

SFX_IMPL_OBJECTFACTORY( BasicDocShell, SvGlobalName(), SFXOBJECTSHELL_STD_NORMAL, "sbasic" )

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( SID_BASICIDE_STATUSBAR );
}

BasicDocShell::BasicDocShell( SfxObjectCreateMode eMode ) : SfxObjectShell( eMode )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
    SetModel( new SIDEModel(this) );
    SetHasNoBasic();
}

__EXPORT BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

void __EXPORT BasicDocShell::Execute( SfxRequest& )
{
}

void __EXPORT BasicDocShell::GetState( SfxItemSet& )
{
}

SfxPrinter* BasicDocShell::GetPrinter( BOOL bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillStatusBar( StatusBar& rStatusBar )
{
    String aTmp;

    // Titel
    aTmp.Fill( 30, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_TITLE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT);

    // Modify
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
        rStatusBar.GetTextWidth( '*' ) );

    // signatures
    rStatusBar.InsertItem( SID_SIGNATURE, XmlSecStatusBarControl::GetDefItemWidth( rStatusBar ), SIB_USERDRAW );
    rStatusBar.SetHelpId(SID_SIGNATURE, SID_SIGNATURE);

    // Position
    aTmp.Erase();
    aTmp.Fill( 15, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_POS,
        rStatusBar.GetTextWidth( aTmp ), SIB_LEFT);

    // Insert/Overwrite
    rStatusBar.InsertItem( SID_ATTR_INSERT,
        rStatusBar.GetTextWidth( String( RTL_CONSTASCII_USTRINGPARAM( "XXXXX" /* "EINFG" */ ) ) ) );

    // Uhrzeit
    aTmp.Fill( 20, 'X' );
    rStatusBar.InsertItem( SID_ATTR_SIZE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT | SIB_USERDRAW );

//  return pStatusBar;

}

void BasicDocShell::FillClass( SvGlobalName*, sal_uInt32*, String*, String*, String*, sal_Int32) const
{}

void BasicDocShell::Draw( OutputDevice *, const JobSetup &, USHORT )
{}

<|endoftext|>


<commit_before><commit_msg>Fix failure to open AVRCP input device due to EPERM.<commit_after><|endoftext|>