<commit_before>/*
 * Copyright 2010, Nikhil Marathe <nsm.nikhil@gmail.com> All rights reserved.
 * See LICENSE for details.
*/
#include "sasljs.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace v8;
using namespace node;

/*
 * Macro from the sqlite3 bindings
 * http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
 * by Eric Fredricksen
 */
#define REQ_STR_ARG(I, VAR)                                             \
      if (args.Length() <= (I) || !args[I]->IsString())                     \
    return ThrowException(Exception::TypeError(                         \
                                  String::New("Argument " #I " must be a string"))); \
  String::Utf8Value VAR(args[I]->ToString());

#define ENSURE_STARTED( session_obj )\
  if( !session_obj->m_session )\
    std::cerr << "sasljs: Session is not started!\n";\
  assert( session_obj->m_session != NULL )

namespace sasljs {
v8::Local<v8::FunctionTemplate> Session::Initialize ( Handle<Object> target )
{
  v8::HandleScope scope;

  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);

  t->InstanceTemplate()->SetInternalFieldCount(1);

  // error codes
  NODE_DEFINE_CONSTANT( target, GSASL_OK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE  );
  NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES  );
  NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN  );

  // property constants
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );
  NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );
  NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );
  NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_REALM );
  NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_QOPS );
  NODE_DEFINE_CONSTANT( target, GSASL_QOP );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );

  NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
  NODE_SET_PROTOTYPE_METHOD( t, "step", Step );
  NODE_SET_PROTOTYPE_METHOD( t, "property", GetSaslProperty );
  NODE_SET_PROTOTYPE_METHOD( t, "setProperty", SetSaslProperty );

  return scope.Close(t);
}

void ServerSession::Initialize ( Handle<Object> target ) {
  v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  target->Set( v8::String::NewSymbol("ServerSession"), t->GetFunction() );
}

void ClientSession::Initialize ( Handle<Object> target ) {
  v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  target->Set( v8::String::NewSymbol("ClientSession"), t->GetFunction() );
}

/*
 * Call in JS
 * new Session( "service name" );
 * All other options default to NULL for now
 */
v8::Handle<v8::Value>
Session::New (const v8::Arguments& args)
{
  HandleScope scope;

  if( args.Length() < 1 || !args[0]->IsFunction() ) {
    return ThrowException(Exception::TypeError(
                                  String::New("Argument 0 must be a callback")));
  }

  Session *sc = new Session( cb_persist( args[0] ) );
  sc->Wrap( args.This() );
  return args.This();
}

Session::Session( Persistent<Function> *cb )
  : ObjectWrap()
  , m_session( NULL )
  , m_callback( cb )
{
}

Session::~Session()
{
  if (m_session)
    gsasl_finish(m_session);
  m_callback->Dispose();
}

Handle<Value>
Session::GetMechanisms( const v8::Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );

  char *result;

  int mechres = gsasl_server_mechlist( ctx, &result );
  if( mechres != GSASL_OK ) {
    return String::New( "" );
  }

  Handle<String> ret = String::New( result, strlen( result ) );
  free( result );
  return ret;
}

int
Session::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
  Session *sc = static_cast<Session*>(gsasl_session_hook_get( sctx ));
  ENSURE_STARTED( sc );

  std::map<Gsasl_property, const char *>::iterator it = property_codes.find( prop );

  Local<Value> propValue;
  if( it != property_codes.end() ) {
    propValue = String::NewSymbol(it->second);
  } else {
    propValue = Integer::New(prop);
  }

  Local<Value> argv[] = { propValue, Local<Object>::New(sc->handle_) };
  Local<Value> ret = (*sc->m_callback)->Call( sc->handle_, 2, argv );

  if( !ret->IsNumber() )
    return GSASL_NO_CALLBACK;

  return ret->ToInteger()->Value();
}

/**
 * Returns a map
 * { status: integer_error_code,
 *   data : data to send to client if error == GSASL_OK }
 */
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ServerSession *sc = Unwrap<ServerSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
ClientSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ClientSession *sc = Unwrap<ClientSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_client_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
Session::Step( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, clientinString );

  Session *sc = Unwrap<Session>( args.This() );

  char *reply;

  int res = gsasl_step64( sc->m_session, *clientinString, &reply );

  Handle<Object> obj = Object::New();
  Local<String> status = String::NewSymbol( "status" );

  obj->Set( status, Integer::New( res ) );

  if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
    obj->Set( String::NewSymbol( "data" ), String::New( reply, strlen( reply ) ) );
  }
  else {
    obj->Set( String::NewSymbol( "data" ), String::New( gsasl_strerror( res ) ) );
  }

  return obj;
}

Handle<Value>
Session::GetSaslProperty( const Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );
  ENSURE_STARTED( sc );

  if( args.Length() < 1 || !args[0]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
  }

  String::AsciiValue key( args[0]->ToString() );

  std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );

  if( it != property_strings.end() ) {
    const char *prop = gsasl_property_fast( sc->m_session, it->second );

    if( prop == NULL )
      return Null();
    return String::New( prop );
  }

  return Null();
}

Handle<Value>
Session::SetSaslProperty( const Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );
  ENSURE_STARTED( sc );

  if( args.Length() < 1 || !args[0]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
  }

  String::AsciiValue key( args[0]->ToString() );

  if( args.Length() < 2 || !args[1]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property value as second argument" ) ) );
  }

  String::AsciiValue val( args[1]->ToString() );

  std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
  if( it != property_strings.end() ) {
    gsasl_property_set( sc->m_session, it->second, *val );
  }

  return Null();
}

static void register_property(const char *name, Gsasl_property prop)
{
  property_strings[name] = prop;
  property_codes[prop] = name;
}
}

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;

  sasljs::ctx = NULL;
  int initres = gsasl_init( &sasljs::ctx );

  if( initres != GSASL_OK ) {
      fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
      abort();
  }

  sasljs::register_property("authid", GSASL_AUTHID);
  sasljs::register_property("authzid", GSASL_AUTHZID);
  sasljs::register_property("password", GSASL_PASSWORD);
  sasljs::register_property("anonymous_token", GSASL_ANONYMOUS_TOKEN);
  sasljs::register_property("service", GSASL_SERVICE);
  sasljs::register_property("hostname", GSASL_HOSTNAME);
  sasljs::register_property("gssapi_display_name", GSASL_GSSAPI_DISPLAY_NAME);
  sasljs::register_property("passcode", GSASL_PASSCODE);
  sasljs::register_property("suggested_pin", GSASL_SUGGESTED_PIN);
  sasljs::register_property("pin", GSASL_PIN);
  sasljs::register_property("realm", GSASL_REALM);
  sasljs::register_property("digest_md5_hashed_password", GSASL_DIGEST_MD5_HASHED_PASSWORD);
  sasljs::register_property("qops", GSASL_QOPS);
  sasljs::register_property("qop", GSASL_QOP);
  sasljs::register_property("scram_iter", GSASL_SCRAM_ITER);
  sasljs::register_property("scram_salt", GSASL_SCRAM_SALT);
  sasljs::register_property("scram_salted_password", GSASL_SCRAM_SALTED_PASSWORD);
  sasljs::register_property("validate_simple", GSASL_VALIDATE_SIMPLE);
  sasljs::register_property("validate_external", GSASL_VALIDATE_EXTERNAL);
  sasljs::register_property("validate_anonymous", GSASL_VALIDATE_ANONYMOUS);
  sasljs::register_property("validate_gssapi", GSASL_VALIDATE_GSSAPI);
  sasljs::register_property("validate_securid", GSASL_VALIDATE_SECURID);

  sasljs::ServerSession::Initialize(target);
  sasljs::ClientSession::Initialize(target);
}
<commit_msg>add cb_tls_unique property<commit_after>/*
 * Copyright 2010, Nikhil Marathe <nsm.nikhil@gmail.com> All rights reserved.
 * See LICENSE for details.
*/
#include "sasljs.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace v8;
using namespace node;

/*
 * Macro from the sqlite3 bindings
 * http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
 * by Eric Fredricksen
 */
#define REQ_STR_ARG(I, VAR)                                             \
      if (args.Length() <= (I) || !args[I]->IsString())                     \
    return ThrowException(Exception::TypeError(                         \
                                  String::New("Argument " #I " must be a string"))); \
  String::Utf8Value VAR(args[I]->ToString());

#define ENSURE_STARTED( session_obj )\
  if( !session_obj->m_session )\
    std::cerr << "sasljs: Session is not started!\n";\
  assert( session_obj->m_session != NULL )

namespace sasljs {
v8::Local<v8::FunctionTemplate> Session::Initialize ( Handle<Object> target )
{
  v8::HandleScope scope;

  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);

  t->InstanceTemplate()->SetInternalFieldCount(1);

  // error codes
  NODE_DEFINE_CONSTANT( target, GSASL_OK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE  );
  NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES  );
  NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE  );
  NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR  );
  NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE  );
  NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN  );

  // property constants
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );
  NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );
  NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );
  NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );
  NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );
  NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );
  NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_PIN );
  NODE_DEFINE_CONSTANT( target, GSASL_REALM );
  NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_QOPS );
  NODE_DEFINE_CONSTANT( target, GSASL_QOP );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );
  NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );
  NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );

  NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
  NODE_SET_PROTOTYPE_METHOD( t, "step", Step );
  NODE_SET_PROTOTYPE_METHOD( t, "property", GetSaslProperty );
  NODE_SET_PROTOTYPE_METHOD( t, "setProperty", SetSaslProperty );

  return scope.Close(t);
}

void ServerSession::Initialize ( Handle<Object> target ) {
  v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  target->Set( v8::String::NewSymbol("ServerSession"), t->GetFunction() );
}

void ClientSession::Initialize ( Handle<Object> target ) {
  v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
  NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
  target->Set( v8::String::NewSymbol("ClientSession"), t->GetFunction() );
}

/*
 * Call in JS
 * new Session( "service name" );
 * All other options default to NULL for now
 */
v8::Handle<v8::Value>
Session::New (const v8::Arguments& args)
{
  HandleScope scope;

  if( args.Length() < 1 || !args[0]->IsFunction() ) {
    return ThrowException(Exception::TypeError(
                                  String::New("Argument 0 must be a callback")));
  }

  Session *sc = new Session( cb_persist( args[0] ) );
  sc->Wrap( args.This() );
  return args.This();
}

Session::Session( Persistent<Function> *cb )
  : ObjectWrap()
  , m_session( NULL )
  , m_callback( cb )
{
}

Session::~Session()
{
  if (m_session)
    gsasl_finish(m_session);
  m_callback->Dispose();
}

Handle<Value>
Session::GetMechanisms( const v8::Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );

  char *result;

  int mechres = gsasl_server_mechlist( ctx, &result );
  if( mechres != GSASL_OK ) {
    return String::New( "" );
  }

  Handle<String> ret = String::New( result, strlen( result ) );
  free( result );
  return ret;
}

int
Session::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
  Session *sc = static_cast<Session*>(gsasl_session_hook_get( sctx ));
  ENSURE_STARTED( sc );

  std::map<Gsasl_property, const char *>::iterator it = property_codes.find( prop );

  Local<Value> propValue;
  if( it != property_codes.end() ) {
    propValue = String::NewSymbol(it->second);
  } else {
    propValue = Integer::New(prop);
  }

  Local<Value> argv[] = { propValue, Local<Object>::New(sc->handle_) };
  Local<Value> ret = (*sc->m_callback)->Call( sc->handle_, 2, argv );

  if( !ret->IsNumber() )
    return GSASL_NO_CALLBACK;

  return ret->ToInteger()->Value();
}

/**
 * Returns a map
 * { status: integer_error_code,
 *   data : data to send to client if error == GSASL_OK }
 */
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ServerSession *sc = Unwrap<ServerSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
ClientSession::Start( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, mechanismString );

  int res;

  ClientSession *sc = Unwrap<ClientSession>( args.This() );
  if( sc->m_session != NULL ) {
    return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
  }

  res = gsasl_client_start( ctx, *mechanismString, &sc->m_session );
  gsasl_session_hook_set( sc->m_session, sc );
  gsasl_callback_set( ctx, sc->Callback );

  return Integer::New( res );
}

v8::Handle<v8::Value>
Session::Step( const v8::Arguments &args )
{
  REQ_STR_ARG( 0, clientinString );

  Session *sc = Unwrap<Session>( args.This() );

  char *reply;

  int res = gsasl_step64( sc->m_session, *clientinString, &reply );

  Handle<Object> obj = Object::New();
  Local<String> status = String::NewSymbol( "status" );

  obj->Set( status, Integer::New( res ) );

  if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
    obj->Set( String::NewSymbol( "data" ), String::New( reply, strlen( reply ) ) );
  }
  else {
    obj->Set( String::NewSymbol( "data" ), String::New( gsasl_strerror( res ) ) );
  }

  return obj;
}

Handle<Value>
Session::GetSaslProperty( const Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );
  ENSURE_STARTED( sc );

  if( args.Length() < 1 || !args[0]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
  }

  String::AsciiValue key( args[0]->ToString() );

  std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );

  if( it != property_strings.end() ) {
    const char *prop = gsasl_property_fast( sc->m_session, it->second );

    if( prop == NULL )
      return Null();
    return String::New( prop );
  }

  return Null();
}

Handle<Value>
Session::SetSaslProperty( const Arguments &args )
{
  Session *sc = Unwrap<Session>( args.This() );
  ENSURE_STARTED( sc );

  if( args.Length() < 1 || !args[0]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
  }

  String::AsciiValue key( args[0]->ToString() );

  if( args.Length() < 2 || !args[1]->IsString() ) {
    return ThrowException( Exception::TypeError( String::New( "Expect property value as second argument" ) ) );
  }

  String::AsciiValue val( args[1]->ToString() );

  std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
  if( it != property_strings.end() ) {
    gsasl_property_set( sc->m_session, it->second, *val );
  }

  return Null();
}

static void register_property(const char *name, Gsasl_property prop)
{
  property_strings[name] = prop;
  property_codes[prop] = name;
}
}

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;

  sasljs::ctx = NULL;
  int initres = gsasl_init( &sasljs::ctx );

  if( initres != GSASL_OK ) {
      fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
      abort();
  }

  sasljs::register_property("authid", GSASL_AUTHID);
  sasljs::register_property("authzid", GSASL_AUTHZID);
  sasljs::register_property("password", GSASL_PASSWORD);
  sasljs::register_property("anonymous_token", GSASL_ANONYMOUS_TOKEN);
  sasljs::register_property("service", GSASL_SERVICE);
  sasljs::register_property("hostname", GSASL_HOSTNAME);
  sasljs::register_property("gssapi_display_name", GSASL_GSSAPI_DISPLAY_NAME);
  sasljs::register_property("passcode", GSASL_PASSCODE);
  sasljs::register_property("suggested_pin", GSASL_SUGGESTED_PIN);
  sasljs::register_property("pin", GSASL_PIN);
  sasljs::register_property("realm", GSASL_REALM);
  sasljs::register_property("digest_md5_hashed_password", GSASL_DIGEST_MD5_HASHED_PASSWORD);
  sasljs::register_property("qops", GSASL_QOPS);
  sasljs::register_property("qop", GSASL_QOP);
  sasljs::register_property("scram_iter", GSASL_SCRAM_ITER);
  sasljs::register_property("scram_salt", GSASL_SCRAM_SALT);
  sasljs::register_property("scram_salted_password", GSASL_SCRAM_SALTED_PASSWORD);
  sasljs::register_property("cb_tls_unique", GSASL_CB_TLS_UNIQUE);
  sasljs::register_property("validate_simple", GSASL_VALIDATE_SIMPLE);
  sasljs::register_property("validate_external", GSASL_VALIDATE_EXTERNAL);
  sasljs::register_property("validate_anonymous", GSASL_VALIDATE_ANONYMOUS);
  sasljs::register_property("validate_gssapi", GSASL_VALIDATE_GSSAPI);
  sasljs::register_property("validate_securid", GSASL_VALIDATE_SECURID);

  sasljs::ServerSession::Initialize(target);
  sasljs::ClientSession::Initialize(target);
}
<|endoftext|>


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

#ifndef _SOURCE_HXX_
#define _SOURCE_HXX_

#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCE_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSource.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCECONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _OSL_MUTEX_H_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#include "../../inc/DtObjFactory.hxx"
#include "globals.hxx"
#include <oleidl.h>

#include <systools/win32/comtools.hxx>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;

class SourceContext;
// RIGHT MOUSE BUTTON drag and drop not supportet currently.
// ALT modifier is considered to effect a user selection of effects
class DragSource:
      public MutexDummy,
      public WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>,
      public IDropSource

{
    Reference<XMultiServiceFactory> m_serviceFactory;
    HWND m_hAppWindow;

    // The mouse button that set off the drag and drop operation
    short m_MouseButton;
    // Converts XTransferable objects to IDataObject objects.
    CDTransObjFactory m_aDataConverter;

    DragSource();
    DragSource(const DragSource&);
    DragSource &operator= ( const DragSource&);

    // First starting a new drag and drop thread if
    // the last one has finished
    void StartDragImpl(
        const DragGestureEvent& trigger,
        sal_Int8 sourceActions,
        sal_Int32 cursor,
        sal_Int32 image,
        const Reference<XTransferable >& trans,
        const Reference<XDragSourceListener >& listener);

public:
    long m_RunningDndOperationCount;

public:
    // only valid for one dnd operation
    // the thread ID of the thread which created the window
    DWORD m_threadIdWindow;
    // The context notifies the XDragSourceListener s
    Reference<XDragSourceContext>   m_currentContext;

    // the wrapper for the Transferable ( startDrag)
    IDataObjectPtr m_spDataObject;

    sal_Int8 m_sourceActions;

public:
    DragSource(const Reference<XMultiServiceFactory>& sf);
    virtual ~DragSource();

#if OSL_DEBUG_LEVEL > 1
    virtual void SAL_CALL release();
#endif

  // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
        throw(Exception, RuntimeException);

    // XDragSource
    virtual sal_Bool SAL_CALL isDragImageSupported(  ) throw(RuntimeException);
    virtual sal_Int32 SAL_CALL getDefaultCursor( sal_Int8 dragAction )
        throw( IllegalArgumentException, RuntimeException);
    virtual void SAL_CALL startDrag( const DragGestureEvent& trigger,
                                     sal_Int8 sourceActions,
                                     sal_Int32 cursor,
                                     sal_Int32 image,
                                     const Reference<XTransferable >& trans,
                                     const Reference<XDragSourceListener >& listener )
                throw( RuntimeException);

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw (RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw (RuntimeException);

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
            /* [in] */ REFIID riid,
            /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);

    virtual ULONG STDMETHODCALLTYPE AddRef( );

    virtual ULONG STDMETHODCALLTYPE Release( );

    // IDropSource
    virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag(
        /* [in] */ BOOL fEscapePressed,
        /* [in] */ DWORD grfKeyState);

    virtual HRESULT STDMETHODCALLTYPE GiveFeedback(
        /* [in] */ DWORD dwEffect);

};

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

#ifndef _SOURCE_HXX_
#define _SOURCE_HXX_

#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCE_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSource.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCECONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _OSL_MUTEX_H_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#include "../../inc/DtObjFactory.hxx"
#include "globals.hxx"
#include <oleidl.h>

#include <systools/win32/comtools.hxx>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;

class SourceContext;
// RIGHT MOUSE BUTTON drag and drop not supportet currently.
// ALT modifier is considered to effect a user selection of effects
class DragSource:
      public MutexDummy,
      public WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>,
      public IDropSource

{
    Reference<XMultiServiceFactory> m_serviceFactory;
    HWND m_hAppWindow;

    // The mouse button that set off the drag and drop operation
    short m_MouseButton;
    // Converts XTransferable objects to IDataObject objects.
    CDTransObjFactory m_aDataConverter;

    DragSource();
    DragSource(const DragSource&);
    DragSource &operator= ( const DragSource&);

    // First starting a new drag and drop thread if
    // the last one has finished
    void StartDragImpl(
        const DragGestureEvent& trigger,
        sal_Int8 sourceActions,
        sal_Int32 cursor,
        sal_Int32 image,
        const Reference<XTransferable >& trans,
        const Reference<XDragSourceListener >& listener);

public:
    long m_RunningDndOperationCount;

public:
    // only valid for one dnd operation
    // the thread ID of the thread which created the window
    DWORD m_threadIdWindow;
    // The context notifies the XDragSourceListener s
    Reference<XDragSourceContext>   m_currentContext;

    // the wrapper for the Transferable ( startDrag)
    IDataObjectPtr m_spDataObject;

    sal_Int8 m_sourceActions;

public:
    DragSource(const Reference<XMultiServiceFactory>& sf);
    virtual ~DragSource();

#if OSL_DEBUG_LEVEL > 1
    virtual void SAL_CALL release();
#endif

  // XInitialization
    virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
        throw(Exception, RuntimeException);

    // XDragSource
    virtual sal_Bool SAL_CALL isDragImageSupported(  ) throw(RuntimeException);
    virtual sal_Int32 SAL_CALL getDefaultCursor( sal_Int8 dragAction )
        throw( IllegalArgumentException, RuntimeException);
    virtual void SAL_CALL startDrag( const DragGestureEvent& trigger,
                                     sal_Int8 sourceActions,
                                     sal_Int32 cursor,
                                     sal_Int32 image,
                                     const Reference<XTransferable >& trans,
                                     const Reference<XDragSourceListener >& listener )
                throw( RuntimeException);

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName(  ) throw (RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw (RuntimeException);

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
            /* [in] */ REFIID riid,
            /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);

    virtual ULONG STDMETHODCALLTYPE AddRef( );

    virtual ULONG STDMETHODCALLTYPE Release( );

    // IDropSource
    virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag(
        /* [in] */ BOOL fEscapePressed,
        /* [in] */ DWORD grfKeyState);

    virtual HRESULT STDMETHODCALLTYPE GiveFeedback(
        /* [in] */ DWORD dwEffect);

};

#endif
<|endoftext|>


<commit_before><commit_msg>Use FilePath::BaseName instead of the deprecated file_util::GetFilenameFromPath. Part 2.<commit_after><|endoftext|>


<commit_before> #include "Terminal.h"

Terminal::Terminal(int width, int height, uint8_t dir, int fontSize){
	this->w = width;
	this->h = height;
	this->fontSize = fontSize;

	bgColor = BLACK;
	fgColor = GRAY1;
	borderColor = GRAY1;

	direction = dir;
	keepColors = true;
	borderWidth = 1;
	horizontalBleed = horizontalBleed * fontSize*FONT_X;
	verticalBleed = verticalBleed * fontSize*FONT_Y / 2;
	lineSpace = fontSize*FONT_Y / 2;
	lines  = (this->h-2*borderWidth-2*verticalBleed)/(fontSize*FONT_Y+lineSpace);
	lines = (lines > MAX_LINES) ? MAX_LINES : lines;
	memset(linesBuffer, 0, MAX_LINES * sizeof(char*));

	// Allocate memory for lines
	//if(linesBuffer = (char**)malloc(this->lines)){
		//memset(linesBuffer,0,sizeof(char*)*this->lines);
	//}

	// Calculate characters based on fontSize and width
	maxCharacters = (this->w - 2*borderWidth - 2*horizontalBleed)/(fontSize*FONT_X);
	// Allocate memory for characters
	for(int i = 0; i < lines; i++){
		if(linesBuffer[i] = (char*) malloc((maxCharacters+1) * sizeof(char))){
				memset(linesBuffer[i],0,(maxCharacters+1)*sizeof(char));
		}
	}

}

Terminal::~Terminal(){}

void Terminal::print(char* string,uint16_t highColor){
	highlightColor = highColor;
	int length = Widget::getTextLength(string);
	length = (length > maxCharacters) ? maxCharacters : length;
	char lineIndex = (direction == TERMINAL_SCROLL_DOWN) ? 0 : lines - 1;

	// Only scroll if:
	if(direction==TERMINAL_SCROLL_UP && linesIndex <= lines -1){
		lineIndex = linesIndex++;
	}else{
		scroll();
	}

	linesColors[lineIndex] = (highlightColor == NULL) ? fgColor : highlightColor;

	for(int i=0; i<length; i++){
		linesBuffer[lineIndex][i] = string[i];
	}
	linesBuffer[lineIndex][length] = 0;

	update();
}

// Trying to implement a print("some %d characters",4)
void Terminal::print(char* string, int num, uint16_t highColor){
	uint8_t num_size = Widget::getIntLength(num);
	uint8_t str_size = Widget::getTextLength(string);

	char num_string[num_size];
	memset(num_string,0,num_size);

	char new_string[str_size + num_size - 2];
	memset(new_string,0,str_size+num_size-1);

	uint8_t j = 0;
	for(uint8_t i=0; i<str_size; i++){

		if(string[i] == '%' && string[i+1] == 'd'){
			Widget::convert_str(num,num_string);
			//Invert the characters
			for(uint8_t k=num_size; k!=0; k--){
				new_string[j+(num_size-k)] = num_string[k-1];
			}
			j += num_size-1;
			i++;
		}else{
			new_string[j] = string[i];
		}
		j++;
	}

	this->print(new_string,highColor);
}

/*
void Terminal::print(char* string, int num, uint16_t highColor){
	highlightColor = highColor;
	char numChar[DISPLAY_SIZE];
	char numStr[DISPLAY_SIZE];
	char chars = 0;
	while(num >= 10)
	{
		numChar[chars++] = num%10;
		num /= 10;
	}
	numChar[chars++] = num;
	for(int j = 0; j < chars; j++)
	{
		numStr[chars-1-j] = '0'+numChar[j];
	}
	numStr[chars]=0;

	int numLength = Widget::getTextLength(numStr);
	int strLength = Widget::getTextLength(string);
	int length = strLength + numLength;
	length = (length > maxCharacters) ? maxCharacters : length;

	scroll();

	char lineIndex = (direction) ? 0 : lines - 1;
	for(int i=0; i<length; i++){
		if(i >= strLength){
			linesBuffer[lineIndex][i] = numStr[i-strLength];
		}else{
			linesBuffer[lineIndex][i] = string[i];
		}
	}
	linesBuffer[lineIndex][length] = 0;

	update();
}

void Terminal::print(int num, uint16_t highColor){
	highlightColor = highColor;
	char numChar[DISPLAY_SIZE];
	char chars = 0;

	// Extract characters representing the powers of ten
	while(num >= 10)
	{
		numChar[chars++] = num%10;
		num /= 10;
	}
	numChar[chars++] = num;

	scroll();

	char lineIndex = (direction) ? 0 : lines - 1;
	for(int j = 0; j < chars; j++)
	{
		linesBuffer[lineIndex][chars-1-j] = '0'+numChar[j];
	}
	linesBuffer[lineIndex][chars]=0;

	update();
}

*/

void Terminal::scroll(){
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);

	if(direction){
		scrollDown();
	}else{
		scrollUp();
	}
}

void Terminal::scrollDown(){
	// Scroll Down
	for(int line = lines-1; line!=0; line--){
		for(int i=0; i<maxCharacters; i++){
			linesBuffer[line][i] = linesBuffer[line-1][i];
		}
		linesColors[line] = linesColors[line-1];
	}
}

void Terminal::scrollUp(){
	// Scroll Up
	for(int line = 0; line<lines-1; line++){
		for(int i=0; i<maxCharacters; i++){
			linesBuffer[line][i] = linesBuffer[line+1][i];
		}
		linesColors[line] = linesColors[line+1];
	}
}

	/*
	* Clears the terminal and all lines text are cleared
	*/
void Terminal::clear(){
	for(int i=0;i<lines;i++){
		linesBuffer[i][0]=0;
	}
	linesIndex = 0;
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
}

void Terminal::drawFrame(){
  int xPos = x;
  int width = w;
  int yPos = y;
  int height = h;
  for(int i=borderWidth; i!=0;i--){
    myCanvas->tft->drawRect(xPos++,yPos++,width--,height--,borderColor);
    width--;
    height--;
  }
}

void Terminal::show(){
	drawFrame();
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
	update();
}

void Terminal::update(){
	uint16_t color;

	//Calculate position for first line
	int lineX = this->x + borderWidth + horizontalBleed;
	int lineY = this->y + borderWidth + verticalBleed;

	char lineIndex = (direction) ? 0 : lines - 1;

	for(int i=0; i<lines; i++){
		if(i==lineIndex){
			color = linesColors[i];
		}else{
			color = (keepColors)?linesColors[i]:fgColor;
		}
		myCanvas->tft->drawString(linesBuffer[i], lineX, lineY+(i*(fontSize*FONT_Y+lineSpace)), this->fontSize, color);//color);
	}
}
<commit_msg>Cleanup of code and comments in Terminal.cpp<commit_after> #include "Terminal.h"

Terminal::Terminal(int width, int height, uint8_t dir, int fontSize){
	this->w = width;
	this->h = height;
	this->fontSize = fontSize;

	bgColor = BLACK;
	fgColor = GRAY1;
	borderColor = GRAY1;

	direction = dir;
	keepColors = true;
	borderWidth = 1;
	horizontalBleed = horizontalBleed * fontSize*FONT_X;
	verticalBleed = verticalBleed * fontSize*FONT_Y / 2;
	lineSpace = fontSize*FONT_Y / 2;
	lines  = (this->h-2*borderWidth-2*verticalBleed)/(fontSize*FONT_Y+lineSpace);
	lines = (lines > MAX_LINES) ? MAX_LINES : lines;
	memset(linesBuffer, 0, MAX_LINES * sizeof(char*));

	// Calculate characters based on fontSize and width
	maxCharacters = (this->w - 2*borderWidth - 2*horizontalBleed)/(fontSize*FONT_X);
	// Allocate memory for characters
	for(int i = 0; i < lines; i++){
		if(linesBuffer[i] = (char*) malloc((maxCharacters+1) * sizeof(char))){
				memset(linesBuffer[i],0,(maxCharacters+1)*sizeof(char));
		}
	}

}

Terminal::~Terminal(){}

/*
 * Main print function.
 * Prints a char array, given by a pointer with the highlight color
 * specified.
 */
void Terminal::print(char* string,uint16_t highColor){
	highlightColor = highColor;
	int length = Widget::getTextLength(string);
	length = (length > maxCharacters) ? maxCharacters : length;
	char lineIndex = (direction == TERMINAL_SCROLL_DOWN) ? 0 : lines - 1;

	// Only scroll if:
	if(direction==TERMINAL_SCROLL_UP && linesIndex <= lines -1){
		lineIndex = linesIndex++;
	}else{
		scroll();
	}

	linesColors[lineIndex] = (highlightColor == NULL) ? fgColor : highlightColor;

	for(int i=0; i<length; i++){
		linesBuffer[lineIndex][i] = string[i];
	}
	linesBuffer[lineIndex][length] = 0;

	update();
}

/*
 * Implementation of print("some %d characters",4)
 * similar to C++ printf function. Only %d is recognized here.
 * First searches for the position of the % symbol in the string.
 * Then if the next character is d then convert the number to
 * a character array in num_string using Widget's convert_str
 * and copy them into the new_string in the inverted order.
 * Then update the indexes and keep copying the rest of the characters
 * into the new_string array.
 *
 * At the end call the main print function with the new_string
 * characters array.
 */
void Terminal::print(char* string, int num, uint16_t highColor){
	uint8_t str_size = Widget::getTextLength(string);
	uint8_t num_size = Widget::getIntLength(num);

	char new_string[str_size + num_size - 2];
	memset(new_string,0,str_size+num_size-1);

	char num_string[num_size];
	memset(num_string,0,num_size);

	uint8_t j = 0;
	for(uint8_t i=0; i<str_size; i++){

		if(string[i] == '%' && string[i+1] == 'd'){
			Widget::convert_str(num,num_string);
			for(uint8_t k=num_size; k!=0; k--){
				new_string[j+(num_size-k)] = num_string[k-1];
			}
			j += num_size-1;
			i++;
		}else{
			new_string[j] = string[i];
		}
		j++;
	}

	//Call the main print function
	this->print(new_string,highColor);
}

/*
 * Calls the corresponding scroll function based on the
 * direction property.
 */
void Terminal::scroll(){
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);

	if(direction){
		scrollDown();
	}else{
		scrollUp();
	}
}

void Terminal::scrollDown(){
	// Scroll Down
	for(int line = lines-1; line!=0; line--){
		for(int i=0; i<maxCharacters; i++){
			linesBuffer[line][i] = linesBuffer[line-1][i];
		}
		linesColors[line] = linesColors[line-1];
	}
}

void Terminal::scrollUp(){
	// Scroll Up
	for(int line = 0; line<lines-1; line++){
		for(int i=0; i<maxCharacters; i++){
			linesBuffer[line][i] = linesBuffer[line+1][i];
		}
		linesColors[line] = linesColors[line+1];
	}
}

	/*
	* Clears the terminal and all lines text are cleared
	*/
void Terminal::clear(){
	for(int i=0;i<lines;i++){
		linesBuffer[i][0]=0;
	}
	linesIndex = 0;
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
}

void Terminal::drawFrame(){
  int xPos = x;
  int width = w;
  int yPos = y;
  int height = h;
  for(int i=borderWidth; i!=0;i--){
    myCanvas->tft->drawRect(xPos++,yPos++,width--,height--,borderColor);
    width--;
    height--;
  }
}

void Terminal::show(){
	drawFrame();
	myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
	update();
}

void Terminal::update(){
	uint16_t color;

	//Calculate position for first line
	int lineX = this->x + borderWidth + horizontalBleed;
	int lineY = this->y + borderWidth + verticalBleed;

	char lineIndex = (direction) ? 0 : lines - 1;

	for(int i=0; i<lines; i++){
		if(i==lineIndex){
			color = linesColors[i];
		}else{
			color = (keepColors)?linesColors[i]:fgColor;
		}
		myCanvas->tft->drawString(linesBuffer[i], lineX, lineY+(i*(fontSize*FONT_Y+lineSpace)), this->fontSize, color);//color);
	}
}
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

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

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

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

#include <ostream>
#include <unordered_map>                        // TODO: consider changing.
#include <unordered_set>                        // TODO: consider changing.

#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowId.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "Correlate.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "NativeJIT/TypeConverter.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"
#include "Term.h"

// Define hash of RowId to allow use of map/set.
// TODO: remove this when we stop using map/set.
namespace std
{
    template<>
    struct hash<BitFunnel::RowId>
    {
        std::size_t operator()(BitFunnel::RowId const & row) const
        {
            // TODO: do we need to hash this?
            return NativeJIT::convertType<BitFunnel::RowId, size_t>(row);
        }
    };
}

namespace BitFunnel
{
    void Factories::CreateCorrelate(ISimpleIndex const & index,
                                    char const * outDir,
                                    std::vector<std::string> const & terms)
    {
        CHECK_NE(*outDir, '\0')
            << "Output directory not set. ";

        Correlate correlate(index, terms);
        // TODO: call methods here.
    }

    Correlate::Correlate(ISimpleIndex const & index,
                         std::vector<std::string> const & terms)
        : m_index(index),
          m_terms(terms)
    {
    }

    void Correlate::CorrelateRows(char const * outDir) const
    {
        auto & fileManager = m_index.GetFileManager();
        auto & ingestor = m_index.GetIngestor();

        // // TODO: Create with factory?
        // TermToText termToText(*fileManager.TermToText().OpenForRead());

        for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
        {
            auto terms(Factories::CreateDocumentFrequencyTable(
                *fileManager.DocFreqTable(shardId).OpenForRead()));

            auto fileSystem = Factories::CreateFileSystem();
            auto outFileManager =
                Factories::CreateFileManager(outDir,
                                             outDir,
                                             outDir,
                                             *fileSystem);

            // TODO: hoist this read out of loop?
            CorrelateShard(shardId,
                           // termToText,
                           *outFileManager->RowDensities(shardId).OpenForWrite());
        }
    }

    void Correlate::CorrelateShard(
                                   ShardId const & shardId,
        // ITermToText const & termToText,
                                   std::ostream& /*out*/) const
    {
        const Term::StreamId c_TODOStreamId = 0;
        std::unordered_map<Term::Hash, std::unordered_set<RowId>> hashToRowId;

        // auto & fileManager = m_index.GetFileManager();
        for (auto const & termText : m_terms)
        {
            Term term(termText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
            RowIdSequence rows(term, m_index.GetTermTable(shardId));
            for (RowId row : rows)
            {
                hashToRowId[term.GetRawHash()].insert(row);
            }
        }

        // for (auto const & outerTermText : m_terms)
        // {
        //     Term outerTerm(outerTermText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
        //     for (auto const & innerTermText : m_terms)
        //     {
        //         RowIdSequence outerRows(outerTerm, m_index.GetTermTable(shardId));

        //     }

        // }
    }

}
<commit_msg>Fix include path.<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

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

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

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

#include <ostream>
#include <unordered_map>                        // TODO: consider changing.
#include <unordered_set>                        // TODO: consider changing.

#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowId.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "BitFunnel/Term.h"
#include "Correlate.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "NativeJIT/TypeConverter.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"

// Define hash of RowId to allow use of map/set.
// TODO: remove this when we stop using map/set.
namespace std
{
    template<>
    struct hash<BitFunnel::RowId>
    {
        std::size_t operator()(BitFunnel::RowId const & row) const
        {
            // TODO: do we need to hash this?
            return NativeJIT::convertType<BitFunnel::RowId, size_t>(row);
        }
    };
}

namespace BitFunnel
{
    void Factories::CreateCorrelate(ISimpleIndex const & index,
                                    char const * outDir,
                                    std::vector<std::string> const & terms)
    {
        CHECK_NE(*outDir, '\0')
            << "Output directory not set. ";

        Correlate correlate(index, terms);
        // TODO: call methods here.
    }

    Correlate::Correlate(ISimpleIndex const & index,
                         std::vector<std::string> const & terms)
        : m_index(index),
          m_terms(terms)
    {
    }

    void Correlate::CorrelateRows(char const * outDir) const
    {
        auto & fileManager = m_index.GetFileManager();
        auto & ingestor = m_index.GetIngestor();

        // // TODO: Create with factory?
        // TermToText termToText(*fileManager.TermToText().OpenForRead());

        for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
        {
            auto terms(Factories::CreateDocumentFrequencyTable(
                *fileManager.DocFreqTable(shardId).OpenForRead()));

            auto fileSystem = Factories::CreateFileSystem();
            auto outFileManager =
                Factories::CreateFileManager(outDir,
                                             outDir,
                                             outDir,
                                             *fileSystem);

            // TODO: hoist this read out of loop?
            CorrelateShard(shardId,
                           // termToText,
                           *outFileManager->RowDensities(shardId).OpenForWrite());
        }
    }

    void Correlate::CorrelateShard(
                                   ShardId const & shardId,
        // ITermToText const & termToText,
                                   std::ostream& /*out*/) const
    {
        const Term::StreamId c_TODOStreamId = 0;
        std::unordered_map<Term::Hash, std::unordered_set<RowId>> hashToRowId;

        // auto & fileManager = m_index.GetFileManager();
        for (auto const & termText : m_terms)
        {
            Term term(termText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
            RowIdSequence rows(term, m_index.GetTermTable(shardId));
            for (RowId row : rows)
            {
                hashToRowId[term.GetRawHash()].insert(row);
            }
        }

        // for (auto const & outerTermText : m_terms)
        // {
        //     Term outerTerm(outerTermText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
        //     for (auto const & innerTermText : m_terms)
        //     {
        //         RowIdSequence outerRows(outerTerm, m_index.GetTermTable(shardId));

        //     }

        // }
    }

}
<|endoftext|>


<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief  Implementation of CPACS configuration handling routines.
*/

#include "CCPACSConfiguration.h"
#include "TopoDS_Shape.hxx"
#include "Standard_CString.hxx"
#include "BRepOffsetAPI_ThruSections.hxx"
#include "BRepAlgoAPI_Fuse.hxx"
#include "BRepAlgo_Fuse.hxx"
#include "ShapeFix_Shape.hxx"
#include "TopoDS_Compound.hxx"
#include "BRepFeat_Gluer.hxx"
#include "BRep_Builder.hxx"
#include "BRepMesh.hxx"
#include "IGESControl_Controller.hxx"
#include "IGESControl_Writer.hxx"
#include "StlAPI_Writer.hxx"
#include "Interface_Static.hxx"
#include "StlAPI.hxx"
#include "BRepTools.hxx"
#include <BRepBndLib.hxx>
#include <Bnd_Box.hxx>

#include <cfloat>

namespace tigl {

    // Constructor
    CCPACSConfiguration::CCPACSConfiguration(TixiDocumentHandle tixiHandle)
        : tixiDocumentHandle(tixiHandle)
        , header()
        , wings(this)
        , fuselages(this)
        , uidManager()
    {
    }

    // Destructor
    CCPACSConfiguration::~CCPACSConfiguration(void)
    {
    }

    // Invalidates the internal state of the configuration and forces
    // recalculation of wires, lofts etc.
    void CCPACSConfiguration::Invalidate(void)
    {
        wings.Invalidate();
        fuselages.Invalidate();
        fusedAirplane.Nullify();
        configUID = "";
    }

    // Build up memory structure for whole CPACS file
    void CCPACSConfiguration::ReadCPACS(const char* configurationUID)
    {
        if(!configurationUID) return;

        header.ReadCPACS(tixiDocumentHandle);
        wings.ReadCPACS(tixiDocumentHandle, configurationUID);
        fuselages.ReadCPACS(tixiDocumentHandle, configurationUID);

        configUID = configurationUID;
        // Now do parent <-> child transformations. Child should use the
        // parent coordinate system as root.
        try {
            transformAllComponents(uidManager.GetRootComponent());
        }
        catch (tigl::CTiglError& ex) {
            LOG(ERROR) << ex.getError() << std::endl;
        }
    }

    // transform all components relative to their parents
    void CCPACSConfiguration::transformAllComponents(CTiglAbstractPhysicalComponent* parent)
    {
        CTiglAbstractPhysicalComponent::ChildContainerType& children = parent->GetChildren(false);
        CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
        CTiglPoint parentTranslation = parent->GetTranslation();
        for (pIter = children.begin(); pIter != children.end(); pIter++) {
            CTiglAbstractPhysicalComponent* child = *pIter;
            child->Translate(parentTranslation);
            transformAllComponents(child);

        }
    }

    // Returns the boolean fused airplane as TopoDS_Shape
    TopoDS_Shape& CCPACSConfiguration::GetFusedAirplane(void)
    {
        if(fusedAirplane.IsNull()){
            CTiglAbstractPhysicalComponent* rootComponent = uidManager.GetRootComponent();
            fusedAirplane = rootComponent->GetLoft();
            OutputComponentTree(rootComponent);
        }
        return(fusedAirplane);
    }

    // This function does the boolean fusing
    void CCPACSConfiguration::OutputComponentTree(CTiglAbstractPhysicalComponent *parent)
    {
        if(!parent)
            throw CTiglError("Null Pointer argument in CCPACSConfiguration::OutputComponentTree", TIGL_NULL_POINTER);

        bool calcFullModel = true;

        TopoDS_Shape tmpShape = parent->GetMirroredLoft();
        if(!tmpShape.IsNull() && calcFullModel && (parent->GetComponentType()& TIGL_COMPONENT_WING)){
            try{
                fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " mirrored component!", TIGL_ERROR);
            }
        }

        CTiglAbstractPhysicalComponent::ChildContainerType& children = parent->GetChildren(false);
        CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
        for (pIter = children.begin(); pIter != children.end(); pIter++) {
            CTiglAbstractPhysicalComponent* child = *pIter;
            tmpShape = child->GetLoft();
            try{
               fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " with " + child->GetUID(), TIGL_ERROR);
            }
            tmpShape = child->GetMirroredLoft();
            if(tmpShape.IsNull() || !calcFullModel)
                continue;

            try{
               fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " with mirrored component " + child->GetUID(), TIGL_ERROR);
            }
        }
    }

    // Returns the underlying tixi document handle used by a CPACS configuration
    TixiDocumentHandle CCPACSConfiguration::GetTixiDocumentHandle(void) const
    {
        return tixiDocumentHandle;
    }

    // Returns the total count of wing profiles in this configuration
    int CCPACSConfiguration::GetWingProfileCount(void) const
    {
        return wings.GetProfileCount();
    }

    // Returns the wing profile for a given uid.
    CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(std::string uid) const
    {
        return wings.GetProfile(uid);
    }

    // Returns the wing profile for a given index - TODO: depricated function!
    CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(int index) const
    {
        return wings.GetProfile(index);
    }

    // Returns the total count of wings in a configuration
    int CCPACSConfiguration::GetWingCount(void) const
    {
        return wings.GetWingCount();
    }

    // Returns the wing for a given index.
    CCPACSWing& CCPACSConfiguration::GetWing(int index) const
    {
        return wings.GetWing(index);
    }
    // Returns the wing for a given UID.
    CCPACSWing& CCPACSConfiguration::GetWing(const std::string UID) const
    {
        return wings.GetWing(UID);
    }

    TopoDS_Shape CCPACSConfiguration::GetParentLoft(const std::string UID)
    {
        return uidManager.GetParentComponent(UID)->GetLoft();
    }

    // Returns the total count of fuselage profiles in this configuration
    int CCPACSConfiguration::GetFuselageProfileCount(void) const
    {
        return fuselages.GetProfileCount();
    }

    // Returns the fuselage profile for a given index.
    CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(int index) const
    {
        return fuselages.GetProfile(index);
    }

    // Returns the fuselage profile for a given uid.
    CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(std::string uid) const
    {
        return fuselages.GetProfile(uid);
    }

    // Returns the total count of fuselages in a configuration
    int CCPACSConfiguration::GetFuselageCount(void) const
    {
        return fuselages.GetFuselageCount();
    }

    // Returns the fuselage for a given index.
    CCPACSFuselage& CCPACSConfiguration::GetFuselage(int index) const
    {
        return fuselages.GetFuselage(index);
    }

    // Returns the fuselage for a given UID.
    CCPACSFuselage& CCPACSConfiguration::GetFuselage(const std::string UID) const
    {
        return fuselages.GetFuselage(UID);
    }

    // Returns the uid manager
    CTiglUIDManager& CCPACSConfiguration::GetUIDManager(void)
    {
        return uidManager;
    }

    double CCPACSConfiguration::GetAirplaneLenth(void){
        Bnd_Box boundingBox;

        // Draw all wings
        for (int w = 1; w <= GetWingCount(); w++)
        {
            tigl::CCPACSWing& wing = GetWing(w);

            for (int i = 1; i <= wing.GetSegmentCount(); i++)
            {
                tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);

            }

            if(wing.GetSymmetryAxis() == TIGL_NO_SYMMETRY)
                continue;

            for (int i = 1; i <= wing.GetSegmentCount(); i++)
            {
                tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);
            }
        }

        for (int f = 1; f <= GetFuselageCount(); f++)
        {
            tigl::CCPACSFuselage& fuselage = GetFuselage(f);

            for (int i = 1; i <= fuselage.GetSegmentCount(); i++)
            {
                tigl::CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i);
                TopoDS_Shape loft = segment.GetLoft();

                // Transform by fuselage transformation
                loft = fuselage.GetFuselageTransformation().Transform(loft);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);
            }
        }
        Standard_Real xmin, xmax, ymin, ymax, zmin, zmax;
        boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax);

        return xmax-xmin;
    }

    // Returns the uid manager
    std::string CCPACSConfiguration::GetUID(void)
    {
        return configUID;
    }

} // end namespace tigl
<commit_msg>Fixed linux build (hopefully)<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief  Implementation of CPACS configuration handling routines.
*/

#include "CCPACSConfiguration.h"
#include "TopoDS_Shape.hxx"
#include "Standard_CString.hxx"
#include "BRepOffsetAPI_ThruSections.hxx"
#include "BRepAlgoAPI_Fuse.hxx"
#include "BRepAlgo_Fuse.hxx"
#include "ShapeFix_Shape.hxx"
#include "TopoDS_Compound.hxx"
#include "BRepFeat_Gluer.hxx"
#include "BRep_Builder.hxx"
#include "BRepMesh.hxx"
#include "IGESControl_Controller.hxx"
#include "IGESControl_Writer.hxx"
#include "StlAPI_Writer.hxx"
#include "Interface_Static.hxx"
#include "StlAPI.hxx"
#include "BRepTools.hxx"
#include <BRepBndLib.hxx>
#include <Bnd_Box.hxx>

#include <cfloat>

namespace tigl {

    // Constructor
    CCPACSConfiguration::CCPACSConfiguration(TixiDocumentHandle tixiHandle)
        : tixiDocumentHandle(tixiHandle)
        , header()
        , wings(this)
        , fuselages(this)
        , uidManager()
    {
    }

    // Destructor
    CCPACSConfiguration::~CCPACSConfiguration(void)
    {
    }

    // Invalidates the internal state of the configuration and forces
    // recalculation of wires, lofts etc.
    void CCPACSConfiguration::Invalidate(void)
    {
        wings.Invalidate();
        fuselages.Invalidate();
        fusedAirplane.Nullify();
        configUID = "";
    }

    // Build up memory structure for whole CPACS file
    void CCPACSConfiguration::ReadCPACS(const char* configurationUID)
    {
        if(!configurationUID) return;

        header.ReadCPACS(tixiDocumentHandle);
        wings.ReadCPACS(tixiDocumentHandle, configurationUID);
        fuselages.ReadCPACS(tixiDocumentHandle, configurationUID);

        configUID = configurationUID;
        // Now do parent <-> child transformations. Child should use the
        // parent coordinate system as root.
        try {
            transformAllComponents(uidManager.GetRootComponent());
        }
        catch (tigl::CTiglError& ex) {
            LOG(ERROR) << ex.getError() << std::endl;
        }
    }

    // transform all components relative to their parents
    void CCPACSConfiguration::transformAllComponents(CTiglAbstractPhysicalComponent* parent)
    {
        CTiglAbstractPhysicalComponent::ChildContainerType children = parent->GetChildren(false);
        CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
        CTiglPoint parentTranslation = parent->GetTranslation();
        for (pIter = children.begin(); pIter != children.end(); pIter++) {
            CTiglAbstractPhysicalComponent* child = *pIter;
            child->Translate(parentTranslation);
            transformAllComponents(child);

        }
    }

    // Returns the boolean fused airplane as TopoDS_Shape
    TopoDS_Shape& CCPACSConfiguration::GetFusedAirplane(void)
    {
        if(fusedAirplane.IsNull()){
            CTiglAbstractPhysicalComponent* rootComponent = uidManager.GetRootComponent();
            fusedAirplane = rootComponent->GetLoft();
            OutputComponentTree(rootComponent);
        }
        return(fusedAirplane);
    }

    // This function does the boolean fusing
    void CCPACSConfiguration::OutputComponentTree(CTiglAbstractPhysicalComponent *parent)
    {
        if(!parent)
            throw CTiglError("Null Pointer argument in CCPACSConfiguration::OutputComponentTree", TIGL_NULL_POINTER);

        bool calcFullModel = true;

        TopoDS_Shape tmpShape = parent->GetMirroredLoft();
        if(!tmpShape.IsNull() && calcFullModel && (parent->GetComponentType()& TIGL_COMPONENT_WING)){
            try{
                fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " mirrored component!", TIGL_ERROR);
            }
        }

        CTiglAbstractPhysicalComponent::ChildContainerType children = parent->GetChildren(false);
        CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
        for (pIter = children.begin(); pIter != children.end(); pIter++) {
            CTiglAbstractPhysicalComponent* child = *pIter;
            tmpShape = child->GetLoft();
            try{
               fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " with " + child->GetUID(), TIGL_ERROR);
            }
            tmpShape = child->GetMirroredLoft();
            if(tmpShape.IsNull() || !calcFullModel)
                continue;

            try{
               fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
            }
            catch(...){
                throw CTiglError( "Error fusing "  + parent->GetUID() + " with mirrored component " + child->GetUID(), TIGL_ERROR);
            }
        }
    }

    // Returns the underlying tixi document handle used by a CPACS configuration
    TixiDocumentHandle CCPACSConfiguration::GetTixiDocumentHandle(void) const
    {
        return tixiDocumentHandle;
    }

    // Returns the total count of wing profiles in this configuration
    int CCPACSConfiguration::GetWingProfileCount(void) const
    {
        return wings.GetProfileCount();
    }

    // Returns the wing profile for a given uid.
    CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(std::string uid) const
    {
        return wings.GetProfile(uid);
    }

    // Returns the wing profile for a given index - TODO: depricated function!
    CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(int index) const
    {
        return wings.GetProfile(index);
    }

    // Returns the total count of wings in a configuration
    int CCPACSConfiguration::GetWingCount(void) const
    {
        return wings.GetWingCount();
    }

    // Returns the wing for a given index.
    CCPACSWing& CCPACSConfiguration::GetWing(int index) const
    {
        return wings.GetWing(index);
    }
    // Returns the wing for a given UID.
    CCPACSWing& CCPACSConfiguration::GetWing(const std::string UID) const
    {
        return wings.GetWing(UID);
    }

    TopoDS_Shape CCPACSConfiguration::GetParentLoft(const std::string UID)
    {
        return uidManager.GetParentComponent(UID)->GetLoft();
    }

    // Returns the total count of fuselage profiles in this configuration
    int CCPACSConfiguration::GetFuselageProfileCount(void) const
    {
        return fuselages.GetProfileCount();
    }

    // Returns the fuselage profile for a given index.
    CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(int index) const
    {
        return fuselages.GetProfile(index);
    }

    // Returns the fuselage profile for a given uid.
    CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(std::string uid) const
    {
        return fuselages.GetProfile(uid);
    }

    // Returns the total count of fuselages in a configuration
    int CCPACSConfiguration::GetFuselageCount(void) const
    {
        return fuselages.GetFuselageCount();
    }

    // Returns the fuselage for a given index.
    CCPACSFuselage& CCPACSConfiguration::GetFuselage(int index) const
    {
        return fuselages.GetFuselage(index);
    }

    // Returns the fuselage for a given UID.
    CCPACSFuselage& CCPACSConfiguration::GetFuselage(const std::string UID) const
    {
        return fuselages.GetFuselage(UID);
    }

    // Returns the uid manager
    CTiglUIDManager& CCPACSConfiguration::GetUIDManager(void)
    {
        return uidManager;
    }

    double CCPACSConfiguration::GetAirplaneLenth(void){
        Bnd_Box boundingBox;

        // Draw all wings
        for (int w = 1; w <= GetWingCount(); w++)
        {
            tigl::CCPACSWing& wing = GetWing(w);

            for (int i = 1; i <= wing.GetSegmentCount(); i++)
            {
                tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);

            }

            if(wing.GetSymmetryAxis() == TIGL_NO_SYMMETRY)
                continue;

            for (int i = 1; i <= wing.GetSegmentCount(); i++)
            {
                tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);
            }
        }

        for (int f = 1; f <= GetFuselageCount(); f++)
        {
            tigl::CCPACSFuselage& fuselage = GetFuselage(f);

            for (int i = 1; i <= fuselage.GetSegmentCount(); i++)
            {
                tigl::CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i);
                TopoDS_Shape loft = segment.GetLoft();

                // Transform by fuselage transformation
                loft = fuselage.GetFuselageTransformation().Transform(loft);
                BRepBndLib::Add(segment.GetLoft(), boundingBox);
            }
        }
        Standard_Real xmin, xmax, ymin, ymax, zmin, zmax;
        boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax);

        return xmax-xmin;
    }

    // Returns the uid manager
    std::string CCPACSConfiguration::GetUID(void)
    {
        return configUID;
    }

} // end namespace tigl
<|endoftext|>


<commit_before>/*
 * Copyright 2010-2011 PathScale, Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * memory.cc - Contains stub definition of C++ new/delete operators.
 *
 * These definitions are intended to be used for testing and are weak symbols
 * to allow them to be replaced by definitions from a STL implementation.
 * These versions simply wrap malloc() and free(), they do not provide a
 * C++-specific allocator.
 */

#include <stddef.h>
#include <stdlib.h>
#include "stdexcept.h"
#include "atomic.h"

namespace std
{
	struct nothrow_t {};
}

/// The type of the function called when allocation fails.
typedef void (*new_handler)();
/**
 * The function to call when allocation fails.  By default, there is no
 * handler and a bad allocation exception is thrown if an allocation fails.
 */
static new_handler new_handl;

namespace std
{
	/**
	 * Sets a function to be called when there is a failure in new.
	 */
	__attribute__((weak))
	new_handler set_new_handler(new_handler handler)
	{
		return ATOMIC_SWAP(&new_handl, handler);
	}
	__attribute__((weak))
	new_handler get_new_handler(void)
	{
		return ATOMIC_LOAD(&new_handl);
	}
}

__attribute__((weak))
void* operator new(size_t size)
{
	if (0 == size)
	{
		size = 1;
	}
	void * mem = malloc(size);
	while (0 == mem)
	{
		new_handler h = std::get_new_handler();
		if (0 != h)
		{
			h();
		}
		else
		{
			throw std::bad_alloc();
		}
		mem = malloc(size);
	}

	return mem;
}

__attribute__((weak))
void* operator new(size_t size, const std::nothrow_t &) throw()
{
	if (0 == size)
	{
		size = 1;
	}
	void *mem = malloc(size);
	while (0 == mem)
	{
		new_handler h = std::get_new_handler();
		if (0 != h)
		{
			try
			{
				h();
			}
			catch (...)
			{
				// nothrow operator new should return NULL in case of
				// std::bad_alloc exception in new handler
				return NULL;
			}
		}
		else
		{
			return NULL;
		}
		mem = malloc(size);
	}

	return mem;
}

__attribute__((weak))
void operator delete(void * ptr)
{
	free(ptr);
}

__attribute__((weak))
void * operator new[](size_t size)
{
	return ::operator new(size);
}

__attribute__((weak))
void operator delete[](void * ptr) throw()
{
	::operator delete(ptr);
}

<commit_msg>Ensure that the no-throw variants of new and new[] have the same behaviour as the throw variants in case of overrides.<commit_after>/*
 * Copyright 2010-2011 PathScale, Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * memory.cc - Contains stub definition of C++ new/delete operators.
 *
 * These definitions are intended to be used for testing and are weak symbols
 * to allow them to be replaced by definitions from a STL implementation.
 * These versions simply wrap malloc() and free(), they do not provide a
 * C++-specific allocator.
 */

#include <stddef.h>
#include <stdlib.h>
#include "stdexcept.h"
#include "atomic.h"

namespace std
{
	struct nothrow_t {};
}

/// The type of the function called when allocation fails.
typedef void (*new_handler)();
/**
 * The function to call when allocation fails.  By default, there is no
 * handler and a bad allocation exception is thrown if an allocation fails.
 */
static new_handler new_handl;

namespace std
{
	/**
	 * Sets a function to be called when there is a failure in new.
	 */
	__attribute__((weak))
	new_handler set_new_handler(new_handler handler)
	{
		return ATOMIC_SWAP(&new_handl, handler);
	}
	__attribute__((weak))
	new_handler get_new_handler(void)
	{
		return ATOMIC_LOAD(&new_handl);
	}
}

__attribute__((weak))
void* operator new(size_t size)
{
	if (0 == size)
	{
		size = 1;
	}
	void * mem = malloc(size);
	while (0 == mem)
	{
		new_handler h = std::get_new_handler();
		if (0 != h)
		{
			h();
		}
		else
		{
			throw std::bad_alloc();
		}
		mem = malloc(size);
	}

	return mem;
}

__attribute__((weak))
void* operator new(size_t size, const std::nothrow_t &) throw()
{
	try {
		return :: operator new(size);
	} catch (...) {
		// nothrow operator new should return NULL in case of
		// std::bad_alloc exception in new handler
		return NULL;
	}
}

__attribute__((weak))
void operator delete(void * ptr)
{
	free(ptr);
}

__attribute__((weak))
void * operator new[](size_t size)
{
	return ::operator new(size);
}

__attribute__((weak))
void * operator new[](size_t size, const std::nothrow_t &) throw()
{
	try {
		return ::operator new[](size);
	} catch (...) {
		// nothrow operator new should return NULL in case of
		// std::bad_alloc exception in new handler
		return NULL;
	}
}

__attribute__((weak))
void operator delete[](void * ptr) throw()
{
	::operator delete(ptr);
}

<|endoftext|>


<commit_before><commit_msg>- Enable V8 histograming support - All V8 measurements that had been stats timers will now be histogramed instead<commit_after><|endoftext|>