<commit_before>/*
   Copyright 2013 The Trustees of Princeton University
   All Rights Reserved
*/

#include <driver.h>
#include <libgateway.h>

// server config
struct md_syndicate_conf DRIVER_CONF;

// set of files we're exposing
content_map DATA;

// Metadata service client of the AG
ms_client *mc = NULL;

// Location of local files we're exposing
char *datapath = NULL;

// Length of datapath varaiable
size_t  datapath_len = 0;

// publish_func exit code
int pfunc_exit_code = 0;

// Is false if the driver is not initialized
bool initialized = false;

// generate a manifest for an existing file, putting it into the gateway context
extern "C" int gateway_generate_manifest( struct gateway_context* replica_ctx, struct gateway_ctx* ctx, struct md_entry* ent ) {
   errorf("%s", "INFO: gateway_generate_manifest\n");
   // populate a manifest
   Serialization::ManifestMsg* mmsg = new Serialization::ManifestMsg();
   mmsg->set_size( ent->size );
   mmsg->set_file_version( 1 );
   mmsg->set_mtime_sec( ent->mtime_sec );
   mmsg->set_mtime_nsec( 0 );

   uint64_t num_blocks = ent->size / ctx->blocking_factor;
   if( ent->size % ctx->blocking_factor != 0 )
      num_blocks++;

   Serialization::BlockURLSetMsg *bbmsg = mmsg->add_block_url_set();
   bbmsg->set_start_id( 0 );
   bbmsg->set_end_id( num_blocks );

   for( uint64_t i = 0; i < num_blocks; i++ ) {
      bbmsg->add_block_versions( 0 );
   }

   // sign the message
   int rc = gateway_sign_manifest( mc->my_key, mmsg );
   if( rc != 0 ) {
      errorf("gateway_sign_manifest rc = %d\n", rc );
      delete mmsg;
      return rc;
   }

   // serialize
   string mmsg_str;
   bool src = mmsg->SerializeToString( &mmsg_str );
   if( !src ) {
      // failed
      errorf( "%s", "failed to serialize" );
      delete mmsg;
      return -EINVAL;
   }

   ctx->data_len = mmsg_str.size();
   ctx->data = CALLOC_LIST( char, mmsg_str.size() );
   replica_ctx->last_mod = ent->mtime_sec;
   memcpy( ctx->data, mmsg_str.data(), mmsg_str.size() );

   delete mmsg;

   return 0;
}

// read dataset or manifest
extern "C" ssize_t get_dataset( struct gateway_context* dat, char* buf, size_t len, void* user_cls ) {
   errorf("%s", "INFO: get_dataset\n");
   ssize_t ret = 0;
   struct gateway_ctx* ctx = (struct gateway_ctx*)user_cls;

   if( ctx->request_type == GATEWAY_REQUEST_TYPE_LOCAL_FILE ) {
      // read from disk
      ssize_t nr = 0;
      size_t num_read = 0;
      while( num_read < len ) {
         nr = read( ctx->fd, buf + num_read, len - num_read );
         if( nr == 0 ) {
            // EOF
            break;
         }
         if( nr < 0 ) {
            // error
            int errsv = -errno;
            errorf( "read(%d) errno = %d\n", ctx->fd, errsv );
            ret = errsv;
         }
         num_read += nr;
      }

      if( ret == 0 )
         ret = num_read;
   }
   else if( ctx->request_type == GATEWAY_REQUEST_TYPE_MANIFEST ) {
      // read from RAM
      memcpy( buf, ctx->data + ctx->data_offset, MIN( len, ctx->data_len - ctx->data_offset ) );
      ctx->data_offset += len;
      ret = (ssize_t)len;
   }
   else {
      // invalid structure
      ret = -EINVAL;
   }

   return ret;
}

// get metadata for a dataset
extern "C" int metadata_dataset( struct gateway_context* dat, ms::ms_gateway_blockinfo* info, void* usercls ) {
   errorf("%s","INFO: metadata_dataset\n");

   content_map::iterator itr = DATA.find( string( dat->reqdat.fs_path ) );
   if( itr == DATA.end() ) {
      // not here
      return -ENOENT;
   }

   // give back the file_id and last-mod, since that's all the disk has for now.
   // TODO: give back the block hash, maybe?

   struct md_entry* ent = itr->second;

   info->set_file_id( ent->file_id );
   info->set_file_mtime_sec( ent->mtime_sec );
   info->set_file_mtime_nsec( ent->mtime_nsec );

   return 0;
}

// interpret an inbound GET request
extern "C" void* connect_dataset( struct gateway_context* replica_ctx ) {

   errorf("%s", "INFO: connect_dataset\n");

   struct gateway_ctx* ctx = CALLOC_LIST( struct gateway_ctx, 1 );

   // is there metadata for this file?
   string fs_path( replica_ctx->reqdat.fs_path );
   content_map::iterator itr = DATA.find( fs_path );
   if( itr == DATA.end() ) {
      // no entry; nothing to do
      return NULL;
   }

   struct md_entry* ent = DATA[ fs_path ];

   // is this a request for a manifest?
   if( replica_ctx->reqdat.manifest_timestamp.tv_sec > 0 ) {
      // request for a manifest
      int rc = gateway_generate_manifest( replica_ctx, ctx, ent );
      if( rc != 0 ) {
         // failed
         errorf( "gateway_generate_manifest rc = %d\n", rc );

         // meaningful error code
         if( rc == -ENOENT )
            replica_ctx->err = -404;
         else if( rc == -EACCES )
            replica_ctx->err = -403;
         else
            replica_ctx->err = -500;

         free( ctx );

         return NULL;
      }

      ctx->request_type = GATEWAY_REQUEST_TYPE_MANIFEST;
      ctx->data_offset = 0;
      ctx->block_id = 0;
      ctx->num_read = 0;
      replica_ctx->size = ctx->data_len;
   }
   else {
      if ( !global_conf->data_root) {
         errorf( "Conf's data_root = %s\n", global_conf->data_root );
         return NULL;
      }
      int rc = 0;

      // request for local file
      char* fp = md_fullpath( global_conf->data_root, fs_path.c_str(), NULL );
      ctx->fd = open( fp, O_RDONLY );
      if( ctx->fd < 0 ) {
         rc = -errno;
         errorf( "open(%s) errno = %d\n", fp, rc );
         free( fp );
         free( ctx );
         return NULL;
      }
      else {
         free( fp );
	 // Set blocking factor for this volume from replica_ctx
	 ctx->blocking_factor = DRIVER_CONF.ag_block_size;
         // set up for reading
         off_t offset = ctx->blocking_factor * replica_ctx->reqdat.block_id;
         rc = lseek( ctx->fd, offset, SEEK_SET );
         if( rc != 0 ) {
            rc = -errno;
            errorf( "lseek errno = %d\n", rc );
            free( ctx );
            return NULL;
         }
      }

      ctx->num_read = 0;
      ctx->block_id = replica_ctx->reqdat.block_id;
      ctx->request_type = GATEWAY_REQUEST_TYPE_LOCAL_FILE;
      replica_ctx->size = ctx->blocking_factor;
   }

   return ctx;
}

// clean up a transfer
extern "C" void cleanup_dataset( void* cls ) {

   errorf("%s", "INFO: cleanup_dataset\n");
   struct gateway_ctx* ctx = (struct gateway_ctx*)cls;
   if (ctx) {
      close( ctx->fd );
      if( ctx->data )
        free( ctx->data );

      ctx->data = NULL;

      free( ctx );
   }
}

extern "C" int publish_dataset (struct gateway_context*, ms_client *client,
	char* dataset ) {
    if (!initialized)
	init();
    int flags = FTW_PHYS;
    mc = client;
    datapath = dataset;
    datapath_len = strlen(datapath);
    if ( datapath[datapath_len - 1] == '/')
	   datapath_len--;
    if (nftw(dataset, publish_to_volumes, 20, flags) == -1) {
	return pfunc_exit_code;
    }
    return 0;
}

static int publish_to_volumes(const char *fpath, const struct stat *sb,
	int tflag, struct FTW *ftwbuf) {
    int nr_volumes = ms_client_get_num_volumes(mc);
    int vol_counter=0;
    for (vol_counter=0; vol_counter<nr_volumes; vol_counter++) {
	uint64_t volume_id = ms_client_get_volume_id(mc, vol_counter);
	publish(fpath, sb, tflag, ftwbuf, volume_id);
    }
    return 0;
}

static int publish(const char *fpath, const struct stat *sb,
	int tflag, struct FTW *ftwbuf, uint64_t volume_id)
{
    int i = 0;
    struct md_entry* ment = new struct md_entry;
    size_t len = strlen(fpath);
    if ( len < datapath_len ) {
	pfunc_exit_code = -EINVAL;
	return -EINVAL;
    }
    if ( len == datapath_len ) {
	pfunc_exit_code = 0;
	return 0;
    }

    //Set volume path
    size_t path_len = ( len - datapath_len ) + 1;
    char* path = (char*)malloc( path_len );
    memset( path, 0, path_len );
    strncpy( path, fpath + datapath_len, path_len );

    ment->ctime_sec = sb->st_ctime;
    ment->ctime_nsec = 0;
    ment->mtime_sec = sb->st_mtime;
    ment->mtime_nsec = 0;
    ment->mode = sb->st_mode;
    ment->version = 1;
    ment->max_read_freshness = 360000;
    ment->max_write_freshness = 1;
    ment->volume = volume_id;
    ment->size = sb->st_size;
    switch (tflag) {
	case FTW_D:
	    ment->type = MD_ENTRY_DIR;
	    if ( (i = ms_client_mkdir(mc, &ment->file_id, ment)) < 0 ) {
		cout<<"ms client mkdir "<<i<<endl;
	    }
	    break;
	case FTW_F:
	    ment->type = MD_ENTRY_FILE;
	    if ( (i = ms_client_create(mc, &ment->file_id, ment)) < 0 ) {
		cout<<"ms client create "<<i<<endl;
	    }
	    break;
	case FTW_SL:
	    break;
	case FTW_DP:
	    break;
	case FTW_DNR:
	    break;
	default:
	    break;
    }
    DATA[path] = ment;
    //delete ment;
    pfunc_exit_code = 0;
    return 0;
}

extern "C" int controller(pid_t pid, int ctrl_flag) {
    return controller_signal_handler(pid, ctrl_flag);
}

void init() {
    if (!initialized)
	initialized = true;
    else
	return;
    add_driver_event_handler(DRIVER_TERMINATE, term_handler, NULL);
    driver_event_start();
}

void* term_handler(void *cls) {
    //Nothing to do here.
    exit(0);
}

<commit_msg>Make sure an md_entry is 0'ed. Set parent name and entry name in disk driver.<commit_after>/*
   Copyright 2013 The Trustees of Princeton University
   All Rights Reserved
*/

#include <driver.h>
#include <libgateway.h>

// server config
struct md_syndicate_conf DRIVER_CONF;

// set of files we're exposing
content_map DATA;

// Metadata service client of the AG
ms_client *mc = NULL;

// Location of local files we're exposing
char *datapath = NULL;

// Length of datapath varaiable
size_t  datapath_len = 0;

// publish_func exit code
int pfunc_exit_code = 0;

// Is false if the driver is not initialized
bool initialized = false;

// generate a manifest for an existing file, putting it into the gateway context
extern "C" int gateway_generate_manifest( struct gateway_context* replica_ctx, struct gateway_ctx* ctx, struct md_entry* ent ) {
   errorf("%s", "INFO: gateway_generate_manifest\n");
   // populate a manifest
   Serialization::ManifestMsg* mmsg = new Serialization::ManifestMsg();
   mmsg->set_size( ent->size );
   mmsg->set_file_version( 1 );
   mmsg->set_mtime_sec( ent->mtime_sec );
   mmsg->set_mtime_nsec( 0 );

   uint64_t num_blocks = ent->size / ctx->blocking_factor;
   if( ent->size % ctx->blocking_factor != 0 )
      num_blocks++;

   Serialization::BlockURLSetMsg *bbmsg = mmsg->add_block_url_set();
   bbmsg->set_start_id( 0 );
   bbmsg->set_end_id( num_blocks );

   for( uint64_t i = 0; i < num_blocks; i++ ) {
      bbmsg->add_block_versions( 0 );
   }

   // sign the message
   int rc = gateway_sign_manifest( mc->my_key, mmsg );
   if( rc != 0 ) {
      errorf("gateway_sign_manifest rc = %d\n", rc );
      delete mmsg;
      return rc;
   }

   // serialize
   string mmsg_str;
   bool src = mmsg->SerializeToString( &mmsg_str );
   if( !src ) {
      // failed
      errorf( "%s", "failed to serialize" );
      delete mmsg;
      return -EINVAL;
   }

   ctx->data_len = mmsg_str.size();
   ctx->data = CALLOC_LIST( char, mmsg_str.size() );
   replica_ctx->last_mod = ent->mtime_sec;
   memcpy( ctx->data, mmsg_str.data(), mmsg_str.size() );

   delete mmsg;

   return 0;
}

// read dataset or manifest
extern "C" ssize_t get_dataset( struct gateway_context* dat, char* buf, size_t len, void* user_cls ) {
   errorf("%s", "INFO: get_dataset\n");
   ssize_t ret = 0;
   struct gateway_ctx* ctx = (struct gateway_ctx*)user_cls;

   if( ctx->request_type == GATEWAY_REQUEST_TYPE_LOCAL_FILE ) {
      // read from disk
      ssize_t nr = 0;
      size_t num_read = 0;
      while( num_read < len ) {
         nr = read( ctx->fd, buf + num_read, len - num_read );
         if( nr == 0 ) {
            // EOF
            break;
         }
         if( nr < 0 ) {
            // error
            int errsv = -errno;
            errorf( "read(%d) errno = %d\n", ctx->fd, errsv );
            ret = errsv;
         }
         num_read += nr;
      }

      if( ret == 0 )
         ret = num_read;
   }
   else if( ctx->request_type == GATEWAY_REQUEST_TYPE_MANIFEST ) {
      // read from RAM
      memcpy( buf, ctx->data + ctx->data_offset, MIN( len, ctx->data_len - ctx->data_offset ) );
      ctx->data_offset += len;
      ret = (ssize_t)len;
   }
   else {
      // invalid structure
      ret = -EINVAL;
   }

   return ret;
}

// get metadata for a dataset
extern "C" int metadata_dataset( struct gateway_context* dat, ms::ms_gateway_blockinfo* info, void* usercls ) {
   errorf("%s","INFO: metadata_dataset\n");

   content_map::iterator itr = DATA.find( string( dat->reqdat.fs_path ) );
   if( itr == DATA.end() ) {
      // not here
      return -ENOENT;
   }

   // give back the file_id and last-mod, since that's all the disk has for now.
   // TODO: give back the block hash, maybe?

   struct md_entry* ent = itr->second;

   info->set_file_id( ent->file_id );
   info->set_file_mtime_sec( ent->mtime_sec );
   info->set_file_mtime_nsec( ent->mtime_nsec );

   return 0;
}

// interpret an inbound GET request
extern "C" void* connect_dataset( struct gateway_context* replica_ctx ) {

   errorf("%s", "INFO: connect_dataset\n");

   struct gateway_ctx* ctx = CALLOC_LIST( struct gateway_ctx, 1 );

   // is there metadata for this file?
   string fs_path( replica_ctx->reqdat.fs_path );
   content_map::iterator itr = DATA.find( fs_path );
   if( itr == DATA.end() ) {
      // no entry; nothing to do
      return NULL;
   }

   struct md_entry* ent = DATA[ fs_path ];

   // is this a request for a manifest?
   if( replica_ctx->reqdat.manifest_timestamp.tv_sec > 0 ) {
      // request for a manifest
      int rc = gateway_generate_manifest( replica_ctx, ctx, ent );
      if( rc != 0 ) {
         // failed
         errorf( "gateway_generate_manifest rc = %d\n", rc );

         // meaningful error code
         if( rc == -ENOENT )
            replica_ctx->err = -404;
         else if( rc == -EACCES )
            replica_ctx->err = -403;
         else
            replica_ctx->err = -500;

         free( ctx );

         return NULL;
      }

      ctx->request_type = GATEWAY_REQUEST_TYPE_MANIFEST;
      ctx->data_offset = 0;
      ctx->block_id = 0;
      ctx->num_read = 0;
      replica_ctx->size = ctx->data_len;
   }
   else {
      if ( !global_conf->data_root) {
         errorf( "Conf's data_root = %s\n", global_conf->data_root );
         return NULL;
      }
      int rc = 0;

      // request for local file
      char* fp = md_fullpath( global_conf->data_root, fs_path.c_str(), NULL );
      ctx->fd = open( fp, O_RDONLY );
      if( ctx->fd < 0 ) {
         rc = -errno;
         errorf( "open(%s) errno = %d\n", fp, rc );
         free( fp );
         free( ctx );
         return NULL;
      }
      else {
         free( fp );
	 // Set blocking factor for this volume from replica_ctx
	 ctx->blocking_factor = DRIVER_CONF.ag_block_size;
         // set up for reading
         off_t offset = ctx->blocking_factor * replica_ctx->reqdat.block_id;
         rc = lseek( ctx->fd, offset, SEEK_SET );
         if( rc != 0 ) {
            rc = -errno;
            errorf( "lseek errno = %d\n", rc );
            free( ctx );
            return NULL;
         }
      }

      ctx->num_read = 0;
      ctx->block_id = replica_ctx->reqdat.block_id;
      ctx->request_type = GATEWAY_REQUEST_TYPE_LOCAL_FILE;
      replica_ctx->size = ctx->blocking_factor;
   }

   return ctx;
}

// clean up a transfer
extern "C" void cleanup_dataset( void* cls ) {

   errorf("%s", "INFO: cleanup_dataset\n");
   struct gateway_ctx* ctx = (struct gateway_ctx*)cls;
   if (ctx) {
      close( ctx->fd );
      if( ctx->data )
        free( ctx->data );

      ctx->data = NULL;

      free( ctx );
   }
}

extern "C" int publish_dataset (struct gateway_context*, ms_client *client,
	char* dataset ) {
    if (!initialized)
	init();
    int flags = FTW_PHYS;
    mc = client;
    datapath = dataset;
    datapath_len = strlen(datapath);
    if ( datapath[datapath_len - 1] == '/')
	   datapath_len--;
    if (nftw(dataset, publish_to_volumes, 20, flags) == -1) {
	return pfunc_exit_code;
    }
    return 0;
}

static int publish_to_volumes(const char *fpath, const struct stat *sb,
	int tflag, struct FTW *ftwbuf) {
    int nr_volumes = ms_client_get_num_volumes(mc);
    int vol_counter=0;
    for (vol_counter=0; vol_counter<nr_volumes; vol_counter++) {
	uint64_t volume_id = ms_client_get_volume_id(mc, vol_counter);
	publish(fpath, sb, tflag, ftwbuf, volume_id);
    }
    return 0;
}

static int publish(const char *fpath, const struct stat *sb,
	int tflag, struct FTW *ftwbuf, uint64_t volume_id)
{
    int i = 0;
    struct md_entry* ment = new struct md_entry;
    memset( ment, 0, sizeof(struct md_entry) );

    size_t len = strlen(fpath);
    if ( len < datapath_len ) {
	pfunc_exit_code = -EINVAL;
	return -EINVAL;
    }
    if ( len == datapath_len ) {
	pfunc_exit_code = 0;
	return 0;
    }

    //Set volume path
    size_t path_len = ( len - datapath_len ) + 1;
    char* path = (char*)malloc( path_len );
    memset( path, 0, path_len );
    strncpy( path, fpath + datapath_len, path_len );

    char* parent_name_tmp = md_dirname( path, NULL );
    ment->parent_name = md_basename( parent_name_tmp, NULL );
    free( parent_name_tmp );

    ment->name = md_basename( path, NULL );

    ment->ctime_sec = sb->st_ctime;
    ment->ctime_nsec = 0;
    ment->mtime_sec = sb->st_mtime;
    ment->mtime_nsec = 0;
    ment->mode = sb->st_mode;
    ment->version = 1;
    ment->max_read_freshness = 360000;
    ment->max_write_freshness = 1;
    ment->volume = volume_id;
    ment->size = sb->st_size;
    switch (tflag) {
	case FTW_D:
	    ment->type = MD_ENTRY_DIR;
	    if ( (i = ms_client_mkdir(mc, &ment->file_id, ment)) < 0 ) {
		cout<<"ms client mkdir "<<i<<endl;
	    }
	    break;
	case FTW_F:
	    ment->type = MD_ENTRY_FILE;
	    if ( (i = ms_client_create(mc, &ment->file_id, ment)) < 0 ) {
		cout<<"ms client create "<<i<<endl;
	    }
	    break;
	case FTW_SL:
	    break;
	case FTW_DP:
	    break;
	case FTW_DNR:
	    break;
	default:
	    break;
    }
    DATA[path] = ment;
    //delete ment;
    pfunc_exit_code = 0;
    return 0;
}

extern "C" int controller(pid_t pid, int ctrl_flag) {
    return controller_signal_handler(pid, ctrl_flag);
}

void init() {
    if (!initialized)
	initialized = true;
    else
	return;
    add_driver_event_handler(DRIVER_TERMINATE, term_handler, NULL);
    driver_event_start();
}

void* term_handler(void *cls) {
    //Nothing to do here.
    exit(0);
}

<|endoftext|>


<commit_before>/**
 * sopnet main file. Initializes all objects, views, and visualizers.
 */

#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/progress.hpp>

#include <util/exceptions.h>
#include <gui/ContainerView.h>
#include <gui/HorizontalPlacing.h>
#include <gui/ImageView.h>
#include <gui/NamedView.h>
#include <gui/RotateView.h>
#include <gui/Window.h>
#include <gui/ZoomView.h>
#include <inference/io/RandomForestHdf5Writer.h>
#include <imageprocessing/ImageExtractor.h>
#include <imageprocessing/SubStackSelector.h>
#include <imageprocessing/gui/ImageStackView.h>
#include <imageprocessing/io/ImageStackHdf5Reader.h>
#include <imageprocessing/io/ImageStackDirectoryReader.h>
#include <sopnet/Sopnet.h>
#include <sopnet/gui/SegmentsView.h>
#include <sopnet/gui/SegmentsStackView.h>
#include <sopnet/gui/SopnetDialog.h>
#include <util/hdf5.h>
#include <util/ProgramOptions.h>

using std::cout;
using std::endl;
using namespace gui;
using namespace logger;

util::ProgramOption optionProjectName(
		_long_name        = "project",
		_short_name       = "p",
		_description_text = "The HDF5 project file.");

util::ProgramOption optionTraining(
		_long_name        = "train",
		_short_name       = "t",
		_description_text = "Train the segment random forest classifier.");

util::ProgramOption optionFirstSection(
		_module           = "sopnet",
		_long_name        = "firstSection",
		_description_text = "The number of the first section to process.",
		_default_value    = 0);

util::ProgramOption optionLastSection(
		_module           = "sopnet",
		_long_name        = "lastSection",
		_description_text = "The number of the last section to process. If set to -1, all sections after <firstSection> will be used.",
		_default_value    = -1);

util::ProgramOption optionShowResult(
		_module           = "sopnet",
		_long_name        = "showResult",
		_description_text = "Show a 3D view of the result.");

util::ProgramOption optionShowGroundTruth(
		_module           = "sopnet",
		_long_name        = "showGroundTruth",
		_description_text = "Show a 3D view of the ground-truth.");

util::ProgramOption optionShowGoldStandard(
		_module           = "sopnet",
		_long_name        = "showGoldStandard",
		_description_text = "Show a 3D view of the gold-standard.");

util::ProgramOption optionShowNegativeSamples(
		_module           = "sopnet",
		_long_name        = "showNegativeSamples",
		_description_text = "Show a 3D view of all negative training samples.");

void handleException(boost::exception& e) {

	LOG_ERROR(out) << "[window thread] caught exception: ";

	if (boost::get_error_info<error_message>(e))
		LOG_ERROR(out) << *boost::get_error_info<error_message>(e);

	if (boost::get_error_info<stack_trace>(e))
		LOG_ERROR(out) << *boost::get_error_info<stack_trace>(e);

	LOG_ERROR(out) << std::endl;

	LOG_ERROR(out) << "[window thread] details: " << std::endl
	               << boost::diagnostic_information(e)
	               << std::endl;

	exit(-1);
}

void processEvents(boost::shared_ptr<gui::Window> window) {

	LOG_USER(out) << " started as " << window->getCaption() << " at " << window.get() << std::endl;

	while (!window->closed()) {

		try {

			usleep(100);
			window->processEvents();

		} catch (boost::exception& e) {

			handleException(e);
		}
	}

	LOG_USER(out) << "[window thread] releasing shared pointer to window" << std::endl;

	LOG_USER(out) << "[window thread] quitting" << std::endl;
}

int main(int optionc, char** optionv) {

	try {

		/********
		 * INIT *
		 ********/

		// init command line parser
		util::ProgramOptions::init(optionc, optionv);

		// init logger
		LogManager::init();

		LOG_USER(out) << "[main] starting..." << std::endl;

		/*********
		 * SETUP *
		 *********/

		// create a window
		boost::shared_ptr<gui::Window> window = boost::make_shared<gui::Window>("sopnet");
		window->processEvents();

		// create a zoom view for this window
		boost::shared_ptr<gui::ZoomView> zoomView = boost::make_shared<gui::ZoomView>();
		window->setInput(zoomView->getOutput());

		// create two rows of views
		boost::shared_ptr<ContainerView<VerticalPlacing> >   mainContainer       = boost::make_shared<ContainerView<VerticalPlacing> >();
		boost::shared_ptr<ContainerView<HorizontalPlacing> > imageStackContainer = boost::make_shared<ContainerView<HorizontalPlacing> >();
		boost::shared_ptr<ContainerView<HorizontalPlacing> > segmentsContainer   = boost::make_shared<ContainerView<HorizontalPlacing> >();

		// create sopnet dialog
		boost::shared_ptr<SopnetDialog> sopnetDialog = boost::make_shared<SopnetDialog>();

		// connect them to the window via the zoom view
		mainContainer->addInput(imageStackContainer->getOutput());
		mainContainer->addInput(sopnetDialog->getOutput("painter"));
		mainContainer->addInput(segmentsContainer->getOutput());
		zoomView->setInput(mainContainer->getOutput());

		// create basic views
		boost::shared_ptr<ImageStackView> rawSectionsView = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> membranesView   = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> slicesView      = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> groundTruthView = boost::make_shared<ImageStackView>();

		// fill first row
		imageStackContainer->addInput(rawSectionsView->getOutput());
		imageStackContainer->addInput(membranesView->getOutput());
		imageStackContainer->addInput(slicesView->getOutput());
		imageStackContainer->addInput(groundTruthView->getOutput());

		// create section readers
		boost::shared_ptr<pipeline::ProcessNode> rawSectionsReader;
		boost::shared_ptr<pipeline::ProcessNode> membranesReader;
		boost::shared_ptr<pipeline::ProcessNode> slicesReader;
		boost::shared_ptr<pipeline::ProcessNode> groundTruthReader;

		// create image stack readers
		if (!optionProjectName) {

			// if no project filename was given, try to read from default
			// directoryies
			rawSectionsReader = boost::make_shared<ImageStackDirectoryReader>("./raw/");
			membranesReader   = boost::make_shared<ImageStackDirectoryReader>("./membranes/");
			slicesReader      = boost::make_shared<ImageStackDirectoryReader>("./slices/");
			groundTruthReader = boost::make_shared<ImageStackDirectoryReader>("./groundtruth/");

		} else {

			// get the project filename
			std::string projectFilename = optionProjectName;

			// try to read from project hdf5 file
			rawSectionsReader = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "raw");
			membranesReader   = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "membranes");
			slicesReader      = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "slices");
			groundTruthReader = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "groundtruth");
		}

		// select a substack, if options are set
		if (optionFirstSection || optionLastSection) {

			int firstSection = optionFirstSection;
			int lastSection  = optionLastSection;

			// create section selectors
			boost::shared_ptr<SubStackSelector> rawSelector         = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> membranesSelector   = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> slicesSelector      = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> groundTruthSelector = boost::make_shared<SubStackSelector>(firstSection, lastSection);

			// set their inputs to the outputs of the section readers
			rawSelector->setInput(rawSectionsReader->getOutput());
			membranesSelector->setInput(membranesReader->getOutput());
			slicesSelector->setInput(slicesReader->getOutput());
			groundTruthSelector->setInput(groundTruthReader->getOutput());

			// sneakily pretend the selectors are the readers
			rawSectionsReader = rawSelector;
			membranesReader   = membranesSelector;
			slicesReader      = slicesSelector;
			groundTruthReader = groundTruthSelector;
		}

		// set input for image stack views
		rawSectionsView->setInput(rawSectionsReader->getOutput());
		membranesView->setInput(membranesReader->getOutput());
		slicesView->setInput(slicesReader->getOutput());
		groundTruthView->setInput(groundTruthReader->getOutput());

		// create sopnet pipeline
		boost::shared_ptr<Sopnet> sopnet = boost::make_shared<Sopnet>("projects dir not yet implemented");

		// set input to sopnet pipeline
		sopnet->setInput("raw sections", rawSectionsReader->getOutput());
		sopnet->setInput("membranes", slicesReader->getOutput());
		sopnet->setInput("ground truth", groundTruthReader->getOutput());
		sopnet->setInput("segmentation cost parameters", sopnetDialog->getOutput("segmentation cost parameters"));
		sopnet->setInput("force explanation", sopnetDialog->getOutput("force explanation"));

		if (optionShowResult) {

			boost::shared_ptr<ContainerView<OverlayPlacing> > overlay      = boost::make_shared<ContainerView<OverlayPlacing> >();
			boost::shared_ptr<ImageStackView>                 sectionsView = boost::make_shared<ImageStackView>();
			boost::shared_ptr<SegmentsStackView>              resultView   = boost::make_shared<SegmentsStackView>();
			boost::shared_ptr<RotateView>                     rotateView   = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>                      namedView    = boost::make_shared<NamedView>("Result:");

			resultView->setInput(sopnet->getOutput("solution"));
			sectionsView->setInput(rawSectionsReader->getOutput());
			overlay->addInput(sectionsView->getOutput());
			overlay->addInput(resultView->getOutput());
			rotateView->setInput(overlay->getOutput());
			namedView->setInput(rotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowGroundTruth) {

			boost::shared_ptr<SegmentsView> groundTruthView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   gtRotateView    = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView       = boost::make_shared<NamedView>("Ground-truth:");

			groundTruthView->setInput(sopnet->getOutput("ground truth segments"));
			groundTruthView->setInput("raw sections", rawSectionsReader->getOutput());
			gtRotateView->setInput(groundTruthView->getOutput());
			namedView->setInput(gtRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowGoldStandard) {

			boost::shared_ptr<SegmentsView> goldstandardView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   gsRotateView     = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView        = boost::make_shared<NamedView>("Gold Standard:");

			goldstandardView->setInput(sopnet->getOutput("gold standard"));
			goldstandardView->setInput("raw sections", rawSectionsReader->getOutput());
			gsRotateView->setInput(goldstandardView->getOutput());
			namedView->setInput(gsRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowNegativeSamples) {

			boost::shared_ptr<SegmentsView> negativeView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   neRotateView = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView    = boost::make_shared<NamedView>("Negative Samples:");

			negativeView->setInput(sopnet->getOutput("negative samples"));
			negativeView->setInput("raw sections", rawSectionsReader->getOutput());
			neRotateView->setInput(negativeView->getOutput());
			namedView->setInput(neRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionTraining) {

			boost::shared_ptr<RandomForestHdf5Writer> rfWriter = boost::make_shared<RandomForestHdf5Writer>("./segment_rf.hdf");

			rfWriter->setInput("random forest", sopnet->getOutput("random forest"));
			rfWriter->write();

			LOG_USER(out) << "[main] training finished!" << std::endl;
		}

		while (!window->closed()) {

			window->processEvents();
			usleep(1000);
		}

		LOG_USER(out) << "[main] exiting..." << std::endl;

	} catch (Exception& e) {

		handleException(e);
	}
}
<commit_msg>added program option to show result in 3d (default is stack view)<commit_after>/**
 * sopnet main file. Initializes all objects, views, and visualizers.
 */

#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/progress.hpp>

#include <util/exceptions.h>
#include <gui/ContainerView.h>
#include <gui/HorizontalPlacing.h>
#include <gui/ImageView.h>
#include <gui/NamedView.h>
#include <gui/RotateView.h>
#include <gui/Window.h>
#include <gui/ZoomView.h>
#include <inference/io/RandomForestHdf5Writer.h>
#include <imageprocessing/ImageExtractor.h>
#include <imageprocessing/SubStackSelector.h>
#include <imageprocessing/gui/ImageStackView.h>
#include <imageprocessing/io/ImageStackHdf5Reader.h>
#include <imageprocessing/io/ImageStackDirectoryReader.h>
#include <sopnet/Sopnet.h>
#include <sopnet/gui/SegmentsView.h>
#include <sopnet/gui/SegmentsStackView.h>
#include <sopnet/gui/SopnetDialog.h>
#include <util/hdf5.h>
#include <util/ProgramOptions.h>

using std::cout;
using std::endl;
using namespace gui;
using namespace logger;

util::ProgramOption optionProjectName(
		_long_name        = "project",
		_short_name       = "p",
		_description_text = "The HDF5 project file.");

util::ProgramOption optionTraining(
		_long_name        = "train",
		_short_name       = "t",
		_description_text = "Train the segment random forest classifier.");

util::ProgramOption optionFirstSection(
		_module           = "sopnet",
		_long_name        = "firstSection",
		_description_text = "The number of the first section to process.",
		_default_value    = 0);

util::ProgramOption optionLastSection(
		_module           = "sopnet",
		_long_name        = "lastSection",
		_description_text = "The number of the last section to process. If set to -1, all sections after <firstSection> will be used.",
		_default_value    = -1);

util::ProgramOption optionShowResult(
		_module           = "sopnet",
		_long_name        = "showResult",
		_description_text = "Show the result.");

util::ProgramOption optionShowResult3d(
		_module           = "sopnet",
		_long_name        = "showResult3d",
		_description_text = "Show a 3D view of the result.");

util::ProgramOption optionShowGroundTruth(
		_module           = "sopnet",
		_long_name        = "showGroundTruth",
		_description_text = "Show a 3D view of the ground-truth.");

util::ProgramOption optionShowGoldStandard(
		_module           = "sopnet",
		_long_name        = "showGoldStandard",
		_description_text = "Show a 3D view of the gold-standard.");

util::ProgramOption optionShowNegativeSamples(
		_module           = "sopnet",
		_long_name        = "showNegativeSamples",
		_description_text = "Show a 3D view of all negative training samples.");

void handleException(boost::exception& e) {

	LOG_ERROR(out) << "[window thread] caught exception: ";

	if (boost::get_error_info<error_message>(e))
		LOG_ERROR(out) << *boost::get_error_info<error_message>(e);

	if (boost::get_error_info<stack_trace>(e))
		LOG_ERROR(out) << *boost::get_error_info<stack_trace>(e);

	LOG_ERROR(out) << std::endl;

	LOG_ERROR(out) << "[window thread] details: " << std::endl
	               << boost::diagnostic_information(e)
	               << std::endl;

	exit(-1);
}

void processEvents(boost::shared_ptr<gui::Window> window) {

	LOG_USER(out) << " started as " << window->getCaption() << " at " << window.get() << std::endl;

	while (!window->closed()) {

		try {

			usleep(100);
			window->processEvents();

		} catch (boost::exception& e) {

			handleException(e);
		}
	}

	LOG_USER(out) << "[window thread] releasing shared pointer to window" << std::endl;

	LOG_USER(out) << "[window thread] quitting" << std::endl;
}

int main(int optionc, char** optionv) {

	try {

		/********
		 * INIT *
		 ********/

		// init command line parser
		util::ProgramOptions::init(optionc, optionv);

		// init logger
		LogManager::init();

		LOG_USER(out) << "[main] starting..." << std::endl;

		/*********
		 * SETUP *
		 *********/

		// create a window
		boost::shared_ptr<gui::Window> window = boost::make_shared<gui::Window>("sopnet");
		window->processEvents();

		// create a zoom view for this window
		boost::shared_ptr<gui::ZoomView> zoomView = boost::make_shared<gui::ZoomView>();
		window->setInput(zoomView->getOutput());

		// create two rows of views
		boost::shared_ptr<ContainerView<VerticalPlacing> >   mainContainer       = boost::make_shared<ContainerView<VerticalPlacing> >();
		boost::shared_ptr<ContainerView<HorizontalPlacing> > imageStackContainer = boost::make_shared<ContainerView<HorizontalPlacing> >();
		boost::shared_ptr<ContainerView<HorizontalPlacing> > segmentsContainer   = boost::make_shared<ContainerView<HorizontalPlacing> >();

		// create sopnet dialog
		boost::shared_ptr<SopnetDialog> sopnetDialog = boost::make_shared<SopnetDialog>();

		// connect them to the window via the zoom view
		mainContainer->addInput(imageStackContainer->getOutput());
		mainContainer->addInput(sopnetDialog->getOutput("painter"));
		mainContainer->addInput(segmentsContainer->getOutput());
		zoomView->setInput(mainContainer->getOutput());

		// create basic views
		boost::shared_ptr<ImageStackView> rawSectionsView = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> membranesView   = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> slicesView      = boost::make_shared<ImageStackView>();
		boost::shared_ptr<ImageStackView> groundTruthView = boost::make_shared<ImageStackView>();

		// fill first row
		imageStackContainer->addInput(rawSectionsView->getOutput());
		imageStackContainer->addInput(membranesView->getOutput());
		imageStackContainer->addInput(slicesView->getOutput());
		imageStackContainer->addInput(groundTruthView->getOutput());

		// create section readers
		boost::shared_ptr<pipeline::ProcessNode> rawSectionsReader;
		boost::shared_ptr<pipeline::ProcessNode> membranesReader;
		boost::shared_ptr<pipeline::ProcessNode> slicesReader;
		boost::shared_ptr<pipeline::ProcessNode> groundTruthReader;

		// create image stack readers
		if (!optionProjectName) {

			// if no project filename was given, try to read from default
			// directoryies
			rawSectionsReader = boost::make_shared<ImageStackDirectoryReader>("./raw/");
			membranesReader   = boost::make_shared<ImageStackDirectoryReader>("./membranes/");
			slicesReader      = boost::make_shared<ImageStackDirectoryReader>("./slices/");
			groundTruthReader = boost::make_shared<ImageStackDirectoryReader>("./groundtruth/");

		} else {

			// get the project filename
			std::string projectFilename = optionProjectName;

			// try to read from project hdf5 file
			rawSectionsReader = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "raw");
			membranesReader   = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "membranes");
			slicesReader      = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "slices");
			groundTruthReader = boost::make_shared<ImageStackHdf5Reader>(projectFilename, "vncstack", "groundtruth");
		}

		// select a substack, if options are set
		if (optionFirstSection || optionLastSection) {

			int firstSection = optionFirstSection;
			int lastSection  = optionLastSection;

			// create section selectors
			boost::shared_ptr<SubStackSelector> rawSelector         = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> membranesSelector   = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> slicesSelector      = boost::make_shared<SubStackSelector>(firstSection, lastSection);
			boost::shared_ptr<SubStackSelector> groundTruthSelector = boost::make_shared<SubStackSelector>(firstSection, lastSection);

			// set their inputs to the outputs of the section readers
			rawSelector->setInput(rawSectionsReader->getOutput());
			membranesSelector->setInput(membranesReader->getOutput());
			slicesSelector->setInput(slicesReader->getOutput());
			groundTruthSelector->setInput(groundTruthReader->getOutput());

			// sneakily pretend the selectors are the readers
			rawSectionsReader = rawSelector;
			membranesReader   = membranesSelector;
			slicesReader      = slicesSelector;
			groundTruthReader = groundTruthSelector;
		}

		// set input for image stack views
		rawSectionsView->setInput(rawSectionsReader->getOutput());
		membranesView->setInput(membranesReader->getOutput());
		slicesView->setInput(slicesReader->getOutput());
		groundTruthView->setInput(groundTruthReader->getOutput());

		// create sopnet pipeline
		boost::shared_ptr<Sopnet> sopnet = boost::make_shared<Sopnet>("projects dir not yet implemented");

		// set input to sopnet pipeline
		sopnet->setInput("raw sections", rawSectionsReader->getOutput());
		sopnet->setInput("membranes", slicesReader->getOutput());
		sopnet->setInput("ground truth", groundTruthReader->getOutput());
		sopnet->setInput("segmentation cost parameters", sopnetDialog->getOutput("segmentation cost parameters"));
		sopnet->setInput("prior cost parameters", sopnetDialog->getOutput("prior cost parameters"));
		sopnet->setInput("force explanation", sopnetDialog->getOutput("force explanation"));

		if (optionShowResult) {

			boost::shared_ptr<ContainerView<OverlayPlacing> > overlay      = boost::make_shared<ContainerView<OverlayPlacing> >();
			boost::shared_ptr<ImageStackView>                 sectionsView = boost::make_shared<ImageStackView>();
			boost::shared_ptr<SegmentsStackView>              resultView   = boost::make_shared<SegmentsStackView>();
			boost::shared_ptr<RotateView>                     rotateView   = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>                      namedView    = boost::make_shared<NamedView>("Result:");

			resultView->setInput(sopnet->getOutput("solution"));
			sectionsView->setInput(rawSectionsReader->getOutput());
			overlay->addInput(sectionsView->getOutput());
			overlay->addInput(resultView->getOutput());
			rotateView->setInput(overlay->getOutput());
			namedView->setInput(rotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowResult3d) {

			boost::shared_ptr<SegmentsView> resultView   = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   rotateView   = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView    = boost::make_shared<NamedView>("Result:");

			resultView->setInput(sopnet->getOutput("solution"));
			rotateView->setInput(resultView->getOutput());
			namedView->setInput(rotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowGroundTruth) {

			boost::shared_ptr<SegmentsView> groundTruthView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   gtRotateView    = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView       = boost::make_shared<NamedView>("Ground-truth:");

			groundTruthView->setInput(sopnet->getOutput("ground truth segments"));
			groundTruthView->setInput("raw sections", rawSectionsReader->getOutput());
			gtRotateView->setInput(groundTruthView->getOutput());
			namedView->setInput(gtRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowGoldStandard) {

			boost::shared_ptr<SegmentsView> goldstandardView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   gsRotateView     = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView        = boost::make_shared<NamedView>("Gold Standard:");

			goldstandardView->setInput(sopnet->getOutput("gold standard"));
			goldstandardView->setInput("raw sections", rawSectionsReader->getOutput());
			gsRotateView->setInput(goldstandardView->getOutput());
			namedView->setInput(gsRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionShowNegativeSamples) {

			boost::shared_ptr<SegmentsView> negativeView = boost::make_shared<SegmentsView>();
			boost::shared_ptr<RotateView>   neRotateView = boost::make_shared<RotateView>();
			boost::shared_ptr<NamedView>    namedView    = boost::make_shared<NamedView>("Negative Samples:");

			negativeView->setInput(sopnet->getOutput("negative samples"));
			negativeView->setInput("raw sections", rawSectionsReader->getOutput());
			neRotateView->setInput(negativeView->getOutput());
			namedView->setInput(neRotateView->getOutput());

			segmentsContainer->addInput(namedView->getOutput());
		}

		if (optionTraining) {

			boost::shared_ptr<RandomForestHdf5Writer> rfWriter = boost::make_shared<RandomForestHdf5Writer>("./segment_rf.hdf");

			rfWriter->setInput("random forest", sopnet->getOutput("random forest"));
			rfWriter->write();

			LOG_USER(out) << "[main] training finished!" << std::endl;
		}

		while (!window->closed()) {

			window->processEvents();
			usleep(1000);
		}

		LOG_USER(out) << "[main] exiting..." << std::endl;

	} catch (Exception& e) {

		handleException(e);
	}
}
<|endoftext|>


<commit_before>#include "AbstrRenderer.h"
#include "../Controller/MasterController.h"

using namespace std;

bool AbstrRenderer::LoadDataset(const string& strFilename) {
	if (m_pMasterController == NULL) return false;
	if (m_pMasterController->MemMan() == NULL) {
		m_pMasterController->DebugOut()->printf("AbstrRenderer::LoadDataset: Cannont load dataset because m_pMasterController->MemMan() == NULL");
		return false;
	}

	m_pDataset = m_pMasterController->MemMan()->LoadDataset(strFilename);

	if (m_pDataset == NULL) {
		m_pMasterController->DebugOut()->printf("AbstrRenderer::LoadDataset: MemMan call to load dataset failed");
		return false;
	}

	return true;
}

AbstrRenderer::~AbstrRenderer() {
	m_pMasterController->MemMan()->FreeDataset(m_pDataset);
}<commit_msg><commit_after>#include "AbstrRenderer.h"
#include "../Controller/MasterController.h"

using namespace std;

bool AbstrRenderer::LoadDataset(const string& strFilename) {
	if (m_pMasterController == NULL) return false;
	if (m_pMasterController->MemMan() == NULL) {
		m_pMasterController->DebugOut()->printf("AbstrRenderer::LoadDataset: Cannont load dataset because m_pMasterController->MemMan() == NULL");
		return false;
	}

	m_pDataset = m_pMasterController->MemMan()->LoadDataset(strFilename);

	if (m_pDataset == NULL) {
		m_pMasterController->DebugOut()->printf("AbstrRenderer::LoadDataset: MemMan call to load dataset failed");
		return false;
	}

	return true;
}

AbstrRenderer::~AbstrRenderer() {
	m_pMasterController->MemMan()->FreeDataset(m_pDataset);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkViewTheme.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkViewTheme.h"

#include "vtkLookupTable.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkViewTheme, "1.5");
vtkStandardNewMacro(vtkViewTheme);

vtkViewTheme::vtkViewTheme()
{
  this->PointSize = 5;
  this->LineWidth = 1;

  this->PointColor[0] = this->PointColor[1] = this->PointColor[2] = 1;
  this->PointOpacity = 1;
  this->PointHueRange[0] = 0.667;
  this->PointHueRange[1] = 0;
  this->PointSaturationRange[0] = this->PointSaturationRange[1] = 1;
  this->PointValueRange[0] = this->PointValueRange[1] = 1;
  this->PointAlphaRange[0] = this->PointAlphaRange[1] = 1;

  this->CellColor[0] = this->CellColor[1] = this->CellColor[2] = 1;
  this->CellOpacity = 0.5;
  this->CellHueRange[0] = 0.667;
  this->CellHueRange[1] = 0;
  this->CellSaturationRange[0] = 0.5;
  this->CellSaturationRange[1] = 1;
  this->CellValueRange[0] = 0.5;
  this->CellValueRange[1] = 1;
  this->CellAlphaRange[0] = 0.5;
  this->CellAlphaRange[1] = 1;

  this->OutlineColor[0] = this->OutlineColor[1] = this->OutlineColor[2] = 0;

  this->SelectedPointColor[0] = this->SelectedPointColor[2] = 1;
  this->SelectedPointColor[1] = 0;
  this->SelectedPointOpacity = 1;
  this->SelectedCellColor[0] = this->SelectedCellColor[2] = 1;
  this->SelectedCellColor[1] = 0;
  this->SelectedCellOpacity = 1;

  this->BackgroundColor[0] = this->BackgroundColor[1] =
    this->BackgroundColor[2] = 0.0;
  this->BackgroundColor2[0] = this->BackgroundColor2[1] =
    this->BackgroundColor2[2] = 0.3;
  this->VertexLabelColor[0] = this->VertexLabelColor[1] =
    this->VertexLabelColor[2] = 1;
  this->EdgeLabelColor[0] = this->EdgeLabelColor[1] =
    this->EdgeLabelColor[2] = 0.7;
}

vtkViewTheme::~vtkViewTheme()
{
}

vtkViewTheme* vtkViewTheme::CreateOceanTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(3);

  theme->SetBackgroundColor(.8, .8, .8);
  theme->SetBackgroundColor2(1, 1, 1);
  theme->SetVertexLabelColor(0, 0, 0);
  theme->SetEdgeLabelColor(.2, .2, .2);

  theme->SetPointColor(0.5, 0.5, 0.5);
  theme->SetPointHueRange(0.667, 0);
  theme->SetPointSaturationRange(1, 1);
  theme->SetPointValueRange(0.75, 0.75);

  theme->SetCellColor(0.25, 0.25, 0.25);
  theme->SetCellOpacity(0.5);
  theme->SetCellHueRange(0.667, 0);
  theme->SetCellAlphaRange(0.75, 1);
  theme->SetCellValueRange(0.75, .75);
  theme->SetCellSaturationRange(1, 1);

  theme->SetOutlineColor(0,0,0);

  theme->SetSelectedPointColor(.9, .4, .9);
  theme->SetSelectedCellColor(.8, .3, .8);

  return theme;
}

vtkViewTheme* vtkViewTheme::CreateNeonTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(3);

  theme->SetBackgroundColor(.2,.2,.4);
  theme->SetBackgroundColor2(.1,.1,.2);
  theme->SetVertexLabelColor(1, 1, 1);
  theme->SetEdgeLabelColor(.7, .7, .7);

  theme->SetPointColor(0.5, 0.5, 1);
  theme->SetPointHueRange(0.6, 0);
  theme->SetPointSaturationRange(1, 1);
  theme->SetPointValueRange(1, 1);

  theme->SetCellColor(0.3, 0.3, 0.7);
  theme->SetCellOpacity(0.5);
  theme->SetCellHueRange(0.57, 0);
  theme->SetCellAlphaRange(0.75, 1);
  theme->SetCellValueRange(0.75, 1);
  theme->SetCellSaturationRange(1, 1);

  theme->SetOutlineColor(0, 0, 0);

  theme->SetSelectedPointColor(.9, .4, .9);
  theme->SetSelectedCellColor(.8, .3, .8);

  return theme;
}

vtkViewTheme* vtkViewTheme::CreateMellowTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(2);

  theme->SetBackgroundColor(0.3, 0.3, 0.25); // Darker Tan
  theme->SetBackgroundColor2(0.6, 0.6, 0.5); // Tan
  theme->SetVertexLabelColor(1, 1, 1);
  theme->SetEdgeLabelColor(.7, .7, 1);

  theme->SetPointColor(0.0, 0.0, 1.0);
  theme->SetPointHueRange(0.667, 0);

  theme->SetCellColor(0.25, 0.25, 0.25);
  theme->SetCellOpacity(0.4);
  theme->SetCellHueRange(0.667, 0);
  theme->SetCellAlphaRange(0.4, 1);
  theme->SetCellValueRange(0.5, 1);
  theme->SetCellSaturationRange(0.5, 1);

  theme->SetOutlineColor(0, 0, 0);

  theme->SetSelectedPointColor(1, 1, 1);
  theme->SetSelectedCellColor(0, 0, 0);

  return theme;
}

bool vtkViewTheme::LookupMatchesPointTheme(vtkScalarsToColors* s2c)
{
  if (!s2c)
    {
    return false;
    }
  vtkLookupTable* lut = vtkLookupTable::SafeDownCast(s2c);
  if (!lut)
    {
    return false;
    }
  if (lut->GetHueRange()[0] == this->PointHueRange[0] &&
      lut->GetHueRange()[1] == this->PointHueRange[1] &&
      lut->GetSaturationRange()[0] == this->PointSaturationRange[0] &&
      lut->GetSaturationRange()[1] == this->PointSaturationRange[1] &&
      lut->GetValueRange()[0] == this->PointValueRange[0] &&
      lut->GetValueRange()[1] == this->PointValueRange[1] &&
      lut->GetAlphaRange()[0] == this->PointAlphaRange[0] &&
      lut->GetAlphaRange()[1] == this->PointAlphaRange[1])
    {
    return true;
    }
  return false;
}

bool vtkViewTheme::LookupMatchesCellTheme(vtkScalarsToColors* s2c)
{
  if (!s2c)
    {
    return false;
    }
  vtkLookupTable* lut = vtkLookupTable::SafeDownCast(s2c);
  if (!lut)
    {
    return false;
    }
  if (lut->GetHueRange()[0] == this->CellHueRange[0] &&
      lut->GetHueRange()[1] == this->CellHueRange[1] &&
      lut->GetSaturationRange()[0] == this->CellSaturationRange[0] &&
      lut->GetSaturationRange()[1] == this->CellSaturationRange[1] &&
      lut->GetValueRange()[0] == this->CellValueRange[0] &&
      lut->GetValueRange()[1] == this->CellValueRange[1] &&
      lut->GetAlphaRange()[0] == this->CellAlphaRange[0] &&
      lut->GetAlphaRange()[1] == this->CellAlphaRange[1])
    {
    return true;
    }
  return false;
}

void vtkViewTheme::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "PointSize: "
     << this->PointSize << endl;
  os << indent << "LineWidth: "
     << this->LineWidth << endl;
  os << indent << "PointColor: "
     << this->PointColor[0] << ","
     << this->PointColor[1] << ","
     << this->PointColor[2] << endl;
  os << indent << "PointOpacity: " << this->PointOpacity << endl;
  os << indent << "PointHueRange: "
     << this->PointHueRange[0] << ","
     << this->PointHueRange[1] << endl;
  os << indent << "PointSaturationRange: "
     << this->PointSaturationRange[0] << ","
     << this->PointSaturationRange[1] << endl;
  os << indent << "PointValueRange: "
     << this->PointValueRange[0] << ","
     << this->PointValueRange[1] << endl;
  os << indent << "PointAlphaRange: "
     << this->PointAlphaRange[0] << ","
     << this->PointAlphaRange[1] << endl;
  os << indent << "CellColor: "
     << this->CellColor[0] << ","
     << this->CellColor[1] << ","
     << this->CellColor[2] << endl;
  os << indent << "CellOpacity: " << this->CellOpacity << endl;
  os << indent << "CellHueRange: "
     << this->CellHueRange[0] << ","
     << this->CellHueRange[1] << endl;
  os << indent << "CellSaturationRange: "
     << this->CellSaturationRange[0] << ","
     << this->CellSaturationRange[1] << endl;
  os << indent << "CellValueRange: "
     << this->CellValueRange[0] << ","
     << this->CellValueRange[1] << endl;
  os << indent << "CellAlphaRange: "
     << this->CellAlphaRange[0] << ","
     << this->CellAlphaRange[1] << endl;
  os << indent << "OutlineColor: "
     << this->OutlineColor[0] << ","
     << this->OutlineColor[1] << ","
     << this->OutlineColor[2] << endl;
  os << indent << "SelectedPointColor: "
     << this->SelectedPointColor[0] << ","
     << this->SelectedPointColor[1] << ","
     << this->SelectedPointColor[2] << endl;
  os << indent << "SelectedPointOpacity: " << this->SelectedPointOpacity << endl;
  os << indent << "SelectedCellColor: "
     << this->SelectedCellColor[0] << ","
     << this->SelectedCellColor[1] << ","
     << this->SelectedCellColor[2] << endl;
  os << indent << "SelectedCellOpacity: " << this->SelectedCellOpacity << endl;
  os << indent << "BackgroundColor: "
     << this->BackgroundColor[0] << ","
     << this->BackgroundColor[1] << ","
     << this->BackgroundColor[2] << endl;
  os << indent << "BackgroundColor2: "
     << this->BackgroundColor2[0] << ","
     << this->BackgroundColor2[1] << ","
     << this->BackgroundColor2[2] << endl;
  os << indent << "VertexLabelColor: "
     << this->VertexLabelColor[0] << ","
     << this->VertexLabelColor[1] << ","
     << this->VertexLabelColor[2] << endl;
  os << indent << "EdgeLabelColor: "
     << this->EdgeLabelColor[0] << ","
     << this->EdgeLabelColor[1] << ","
     << this->EdgeLabelColor[2] << endl;
}

<commit_msg>ENH: Small tweak to Neon theme.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkViewTheme.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkViewTheme.h"

#include "vtkLookupTable.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkViewTheme, "1.6");
vtkStandardNewMacro(vtkViewTheme);

vtkViewTheme::vtkViewTheme()
{
  this->PointSize = 5;
  this->LineWidth = 1;

  this->PointColor[0] = this->PointColor[1] = this->PointColor[2] = 1;
  this->PointOpacity = 1;
  this->PointHueRange[0] = 0.667;
  this->PointHueRange[1] = 0;
  this->PointSaturationRange[0] = this->PointSaturationRange[1] = 1;
  this->PointValueRange[0] = this->PointValueRange[1] = 1;
  this->PointAlphaRange[0] = this->PointAlphaRange[1] = 1;

  this->CellColor[0] = this->CellColor[1] = this->CellColor[2] = 1;
  this->CellOpacity = 0.5;
  this->CellHueRange[0] = 0.667;
  this->CellHueRange[1] = 0;
  this->CellSaturationRange[0] = 0.5;
  this->CellSaturationRange[1] = 1;
  this->CellValueRange[0] = 0.5;
  this->CellValueRange[1] = 1;
  this->CellAlphaRange[0] = 0.5;
  this->CellAlphaRange[1] = 1;

  this->OutlineColor[0] = this->OutlineColor[1] = this->OutlineColor[2] = 0;

  this->SelectedPointColor[0] = this->SelectedPointColor[2] = 1;
  this->SelectedPointColor[1] = 0;
  this->SelectedPointOpacity = 1;
  this->SelectedCellColor[0] = this->SelectedCellColor[2] = 1;
  this->SelectedCellColor[1] = 0;
  this->SelectedCellOpacity = 1;

  this->BackgroundColor[0] = this->BackgroundColor[1] =
    this->BackgroundColor[2] = 0.0;
  this->BackgroundColor2[0] = this->BackgroundColor2[1] =
    this->BackgroundColor2[2] = 0.3;
  this->VertexLabelColor[0] = this->VertexLabelColor[1] =
    this->VertexLabelColor[2] = 1;
  this->EdgeLabelColor[0] = this->EdgeLabelColor[1] =
    this->EdgeLabelColor[2] = 0.7;
}

vtkViewTheme::~vtkViewTheme()
{
}

vtkViewTheme* vtkViewTheme::CreateOceanTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(3);

  theme->SetBackgroundColor(.8, .8, .8);
  theme->SetBackgroundColor2(1, 1, 1);
  theme->SetVertexLabelColor(0, 0, 0);
  theme->SetEdgeLabelColor(.2, .2, .2);

  theme->SetPointColor(0.5, 0.5, 0.5);
  theme->SetPointHueRange(0.667, 0);
  theme->SetPointSaturationRange(1, 1);
  theme->SetPointValueRange(0.75, 0.75);

  theme->SetCellColor(0.25, 0.25, 0.25);
  theme->SetCellOpacity(0.5);
  theme->SetCellHueRange(0.667, 0);
  theme->SetCellAlphaRange(0.75, 1);
  theme->SetCellValueRange(0.75, .75);
  theme->SetCellSaturationRange(1, 1);

  theme->SetOutlineColor(0,0,0);

  theme->SetSelectedPointColor(.9, .4, .9);
  theme->SetSelectedCellColor(.8, .3, .8);

  return theme;
}

vtkViewTheme* vtkViewTheme::CreateNeonTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(3);

  theme->SetBackgroundColor(.2,.2,.4);
  theme->SetBackgroundColor2(.1,.1,.2);
  theme->SetVertexLabelColor(1, 1, 1);
  theme->SetEdgeLabelColor(.7, .7, .7);

  theme->SetPointColor(0.5, 0.5, 0.6);
  theme->SetPointHueRange(0.6, 0);
  theme->SetPointSaturationRange(1, 1);
  theme->SetPointValueRange(1, 1);

  theme->SetCellColor(0.5, 0.5, 0.7);
  theme->SetCellOpacity(0.5);
  theme->SetCellHueRange(0.57, 0);
  theme->SetCellAlphaRange(0.75, 1);
  theme->SetCellValueRange(0.75, 1);
  theme->SetCellSaturationRange(1, 1);

  theme->SetOutlineColor(0, 0, 0);

  theme->SetSelectedPointColor(.9, .4, .9);
  theme->SetSelectedCellColor(.8, .3, .8);

  return theme;
}

vtkViewTheme* vtkViewTheme::CreateMellowTheme()
{
  vtkViewTheme* theme = vtkViewTheme::New();

  theme->SetPointSize(7);
  theme->SetLineWidth(2);

  theme->SetBackgroundColor(0.3, 0.3, 0.25); // Darker Tan
  theme->SetBackgroundColor2(0.6, 0.6, 0.5); // Tan
  theme->SetVertexLabelColor(1, 1, 1);
  theme->SetEdgeLabelColor(.7, .7, 1);

  theme->SetPointColor(0.0, 0.0, 1.0);
  theme->SetPointHueRange(0.667, 0);

  theme->SetCellColor(0.25, 0.25, 0.25);
  theme->SetCellOpacity(0.4);
  theme->SetCellHueRange(0.667, 0);
  theme->SetCellAlphaRange(0.4, 1);
  theme->SetCellValueRange(0.5, 1);
  theme->SetCellSaturationRange(0.5, 1);

  theme->SetOutlineColor(0, 0, 0);

  theme->SetSelectedPointColor(1, 1, 1);
  theme->SetSelectedCellColor(0, 0, 0);

  return theme;
}

bool vtkViewTheme::LookupMatchesPointTheme(vtkScalarsToColors* s2c)
{
  if (!s2c)
    {
    return false;
    }
  vtkLookupTable* lut = vtkLookupTable::SafeDownCast(s2c);
  if (!lut)
    {
    return false;
    }
  if (lut->GetHueRange()[0] == this->PointHueRange[0] &&
      lut->GetHueRange()[1] == this->PointHueRange[1] &&
      lut->GetSaturationRange()[0] == this->PointSaturationRange[0] &&
      lut->GetSaturationRange()[1] == this->PointSaturationRange[1] &&
      lut->GetValueRange()[0] == this->PointValueRange[0] &&
      lut->GetValueRange()[1] == this->PointValueRange[1] &&
      lut->GetAlphaRange()[0] == this->PointAlphaRange[0] &&
      lut->GetAlphaRange()[1] == this->PointAlphaRange[1])
    {
    return true;
    }
  return false;
}

bool vtkViewTheme::LookupMatchesCellTheme(vtkScalarsToColors* s2c)
{
  if (!s2c)
    {
    return false;
    }
  vtkLookupTable* lut = vtkLookupTable::SafeDownCast(s2c);
  if (!lut)
    {
    return false;
    }
  if (lut->GetHueRange()[0] == this->CellHueRange[0] &&
      lut->GetHueRange()[1] == this->CellHueRange[1] &&
      lut->GetSaturationRange()[0] == this->CellSaturationRange[0] &&
      lut->GetSaturationRange()[1] == this->CellSaturationRange[1] &&
      lut->GetValueRange()[0] == this->CellValueRange[0] &&
      lut->GetValueRange()[1] == this->CellValueRange[1] &&
      lut->GetAlphaRange()[0] == this->CellAlphaRange[0] &&
      lut->GetAlphaRange()[1] == this->CellAlphaRange[1])
    {
    return true;
    }
  return false;
}

void vtkViewTheme::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "PointSize: "
     << this->PointSize << endl;
  os << indent << "LineWidth: "
     << this->LineWidth << endl;
  os << indent << "PointColor: "
     << this->PointColor[0] << ","
     << this->PointColor[1] << ","
     << this->PointColor[2] << endl;
  os << indent << "PointOpacity: " << this->PointOpacity << endl;
  os << indent << "PointHueRange: "
     << this->PointHueRange[0] << ","
     << this->PointHueRange[1] << endl;
  os << indent << "PointSaturationRange: "
     << this->PointSaturationRange[0] << ","
     << this->PointSaturationRange[1] << endl;
  os << indent << "PointValueRange: "
     << this->PointValueRange[0] << ","
     << this->PointValueRange[1] << endl;
  os << indent << "PointAlphaRange: "
     << this->PointAlphaRange[0] << ","
     << this->PointAlphaRange[1] << endl;
  os << indent << "CellColor: "
     << this->CellColor[0] << ","
     << this->CellColor[1] << ","
     << this->CellColor[2] << endl;
  os << indent << "CellOpacity: " << this->CellOpacity << endl;
  os << indent << "CellHueRange: "
     << this->CellHueRange[0] << ","
     << this->CellHueRange[1] << endl;
  os << indent << "CellSaturationRange: "
     << this->CellSaturationRange[0] << ","
     << this->CellSaturationRange[1] << endl;
  os << indent << "CellValueRange: "
     << this->CellValueRange[0] << ","
     << this->CellValueRange[1] << endl;
  os << indent << "CellAlphaRange: "
     << this->CellAlphaRange[0] << ","
     << this->CellAlphaRange[1] << endl;
  os << indent << "OutlineColor: "
     << this->OutlineColor[0] << ","
     << this->OutlineColor[1] << ","
     << this->OutlineColor[2] << endl;
  os << indent << "SelectedPointColor: "
     << this->SelectedPointColor[0] << ","
     << this->SelectedPointColor[1] << ","
     << this->SelectedPointColor[2] << endl;
  os << indent << "SelectedPointOpacity: " << this->SelectedPointOpacity << endl;
  os << indent << "SelectedCellColor: "
     << this->SelectedCellColor[0] << ","
     << this->SelectedCellColor[1] << ","
     << this->SelectedCellColor[2] << endl;
  os << indent << "SelectedCellOpacity: " << this->SelectedCellOpacity << endl;
  os << indent << "BackgroundColor: "
     << this->BackgroundColor[0] << ","
     << this->BackgroundColor[1] << ","
     << this->BackgroundColor[2] << endl;
  os << indent << "BackgroundColor2: "
     << this->BackgroundColor2[0] << ","
     << this->BackgroundColor2[1] << ","
     << this->BackgroundColor2[2] << endl;
  os << indent << "VertexLabelColor: "
     << this->VertexLabelColor[0] << ","
     << this->VertexLabelColor[1] << ","
     << this->VertexLabelColor[2] << endl;
  os << indent << "EdgeLabelColor: "
     << this->EdgeLabelColor[0] << ","
     << this->EdgeLabelColor[1] << ","
     << this->EdgeLabelColor[2] << endl;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010, The Infrastructure Developers Group
 * All rights reserved.
 *
 * This file is subject to the New BSD License (see the LICENSE file).
 */

#include "node_service_handler.h"

#include <txmpp/logging.h>
#include "node_loop.h"

namespace tyrion {

NodeServiceHandler::NodeServiceHandler() {
  FD_ZERO(&rfds_);
  highest_fd_ = 0;
  polling_ = 0;
}

void NodeServiceHandler::Request(NodeEnvelope* envelope) {
  Post(this, MSG_REQUEST, new NodeServiceHandlerData(envelope));
}

void NodeServiceHandler::WakeTasks() {
  txmpp::Thread::Current()->Post(this);
}

void NodeServiceHandler::DoRequest(ServiceData* service) {
  NodeEnvelope* envelope = service->envelope();

  bool issue = false;
  std::string config = "service:" + envelope->type();

  std::string user = NodeSettings::Instance()->Get(config, "user");
  bool user_lock = NodeSettings::Instance()->GetBool(config, "user_lock");

  std::string group = NodeSettings::Instance()->Get(config, "group");
  bool group_lock = NodeSettings::Instance()->GetBool(config, "group_lock");

  int timeout = NodeSettings::Instance()->GetInt(config, "timeout");
  bool timeout_lock = NodeSettings::Instance()->GetBool(config, "timeout_lock");

  if (!issue && user_lock) {
    if (user.empty()) {
      envelope->append_error(
          CreateError("user.lock", "Unable to lock user because none set."));
      issue = true;
    }
  } else if (!issue && !envelope->user().empty()) {
    user = envelope->user();
  }

  if (!issue && group_lock) {
    if (group.empty()) {
      envelope->append_error(
          CreateError("group.lock", "Unable to lock group because none set."));
      issue = true;
    }
  } else if (!issue && !envelope->group().empty())
    group = envelope->group();

  if (!issue && timeout_lock) {
    if (!timeout > 0) {
      envelope->append_error(
          CreateError("timeout.lock",
                      "Unable to lock timeout because none set."));
      issue = true;
    }
  } else {
    timeout = envelope->timeout();
  }

  NodeProcess* process = new NodeProcess(envelope->Path(), false, timeout);
  service->set_process(process);

  if (!issue && !user.empty() && !process->set_user(user)) {
    envelope->append_error(
        CreateError("user.lookup", "Unable to find user '" + user + "'"));
    issue = true;
  }

  if (!issue && !group.empty() && !process->set_group(group)) {
    envelope->append_error(
        CreateError("group.lookup", "Unable to find group '" + group + "'"));
    issue = true;
  }

  if (!issue) {
    FD_SET(process->outfd[NodeProcess::Stdout][0], &rfds_);
    FD_SET(process->outfd[NodeProcess::Stderr][0], &rfds_);

    if (process->outfd[NodeProcess::Stdout][0] > highest_fd_)
      highest_fd_ = process->outfd[NodeProcess::Stdout][0];

    if (process->outfd[NodeProcess::Stderr][0] > highest_fd_)
      highest_fd_ = process->outfd[NodeProcess::Stderr][0];

    process->Run();
    process->Write(envelope->input());

    list_.push_back(service);

    Poll();
  } else {
    Post(this, MSG_RESPONSE, service);
  }
}

void NodeServiceHandler::DoResponse(ServiceData* service) {
  NodeEnvelope* envelope = service->envelope();
  NodeProcess* process = service->process();

  ServiceList::iterator remove = list_.end();
  int highest_fd = 0;

  NodeEnvelope* e = NULL;
  NodeProcess* p = NULL;
  for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) {
    e = (*it)->envelope();
    p = (*it)->process();
    if (*it == service) {
      remove = it;
    } else {
      // Get highest fd that are not the two we're removing
      if (p->outfd[NodeProcess::Stdout][0] >= highest_fd)
        highest_fd = p->outfd[NodeProcess::Stdout][0];
      if (p->outfd[NodeProcess::Stderr][0] >= highest_fd)
        highest_fd = p->outfd[NodeProcess::Stderr][0];
    }
  }
  highest_fd_ = highest_fd;

  if (remove != list_.end()) {
    envelope->set_code(process->Close());

    FD_CLR(process->outfd[NodeProcess::Stdout][0], &rfds_);
    FD_CLR(process->outfd[NodeProcess::Stderr][0], &rfds_);

    list_.erase(remove);
  }

  delete process;
  delete service;

  NodeLoop::Instance()->Response(envelope);
}

void NodeServiceHandler::DoPoll() {
  polling_--;
  if (list_.empty())
    return;

  struct timeval tv;
  tv.tv_sec = PROCESS_BUFFER_SLEEP;
  tv.tv_usec = 0;

  fd_set rfds;
  FD_ZERO(&rfds);
  FD_COPY(&rfds_, &rfds);

  int sr = select(highest_fd_ + 1, &rfds, NULL, NULL, &tv);

  NodeEnvelope* e;
  NodeProcess *p;
  for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) {
    e = (*it)->envelope();
    p = (*it)->process();
    if (sr > 0) {
      // check both stdout and stderr
      for (int i = NodeProcess::Stdout; i <= NodeProcess::Stderr; i++) {
        // check if ready for reading
        if (FD_ISSET(p->outfd[i][0], &rfds)) {
          char data[PROCESS_BUFFER];
          int rc = read(p->outfd[i][0], data, PROCESS_BUFFER-1);

          if (rc == 0) {
            // got eof for this fd
            p->outfdeof[i] = true;
          } else {
            // update output/error in process
            data[rc] = 0;
            if (NodeProcess::Stdout == i) {
              e->append_output(data);
            } else {
              e->append_error(data);
            }
          }
        }
      }
    }
    if (p->Done()) {
      Post(this, MSG_RESPONSE, *it);
    }
  }

  Poll(PROCESS_POLL_TIMEOUT);
}

bool NodeServiceHandler::Poll(int timeout) {
  if (polling_ > 0) {
    return false;
  }
  polling_++;
  PostDelayed(timeout, this, MSG_POLL);
  return true;
}

void NodeServiceHandler::OnMessage(txmpp::Message *pmsg) {
  switch (pmsg->message_id) {
    case MSG_REQUEST:
      assert(pmsg->pdata);
      DoRequest(reinterpret_cast<ServiceData*>(pmsg->pdata));
      break;
    case MSG_RESPONSE:
      assert(pmsg->pdata);
      DoResponse(reinterpret_cast<ServiceData*>(pmsg->pdata));
      break;
    case MSG_POLL:
      DoPoll();
      break;
    default:
      assert(false);
  }
}

int64 NodeServiceHandler::CurrentTime() {
  return (int64)txmpp::Time();
}

}  // namespace tyrion
<commit_msg>Add FD_COPY fallback<commit_after>/*
 * Copyright (c) 2010, The Infrastructure Developers Group
 * All rights reserved.
 *
 * This file is subject to the New BSD License (see the LICENSE file).
 */

#include "node_service_handler.h"

#include <txmpp/logging.h>
#include "node_loop.h"

#ifndef FD_COPY
#define FD_COPY(f, t) memcpy(t, f, sizeof(*(f)))
#endif

namespace tyrion {

NodeServiceHandler::NodeServiceHandler() {
  FD_ZERO(&rfds_);
  highest_fd_ = 0;
  polling_ = 0;
}

void NodeServiceHandler::Request(NodeEnvelope* envelope) {
  Post(this, MSG_REQUEST, new NodeServiceHandlerData(envelope));
}

void NodeServiceHandler::WakeTasks() {
  txmpp::Thread::Current()->Post(this);
}

void NodeServiceHandler::DoRequest(ServiceData* service) {
  NodeEnvelope* envelope = service->envelope();

  bool issue = false;
  std::string config = "service:" + envelope->type();

  std::string user = NodeSettings::Instance()->Get(config, "user");
  bool user_lock = NodeSettings::Instance()->GetBool(config, "user_lock");

  std::string group = NodeSettings::Instance()->Get(config, "group");
  bool group_lock = NodeSettings::Instance()->GetBool(config, "group_lock");

  int timeout = NodeSettings::Instance()->GetInt(config, "timeout");
  bool timeout_lock = NodeSettings::Instance()->GetBool(config, "timeout_lock");

  if (!issue && user_lock) {
    if (user.empty()) {
      envelope->append_error(
          CreateError("user.lock", "Unable to lock user because none set."));
      issue = true;
    }
  } else if (!issue && !envelope->user().empty()) {
    user = envelope->user();
  }

  if (!issue && group_lock) {
    if (group.empty()) {
      envelope->append_error(
          CreateError("group.lock", "Unable to lock group because none set."));
      issue = true;
    }
  } else if (!issue && !envelope->group().empty())
    group = envelope->group();

  if (!issue && timeout_lock) {
    if (!timeout > 0) {
      envelope->append_error(
          CreateError("timeout.lock",
                      "Unable to lock timeout because none set."));
      issue = true;
    }
  } else {
    timeout = envelope->timeout();
  }

  NodeProcess* process = new NodeProcess(envelope->Path(), false, timeout);
  service->set_process(process);

  if (!issue && !user.empty() && !process->set_user(user)) {
    envelope->append_error(
        CreateError("user.lookup", "Unable to find user '" + user + "'"));
    issue = true;
  }

  if (!issue && !group.empty() && !process->set_group(group)) {
    envelope->append_error(
        CreateError("group.lookup", "Unable to find group '" + group + "'"));
    issue = true;
  }

  if (!issue) {
    FD_SET(process->outfd[NodeProcess::Stdout][0], &rfds_);
    FD_SET(process->outfd[NodeProcess::Stderr][0], &rfds_);

    if (process->outfd[NodeProcess::Stdout][0] > highest_fd_)
      highest_fd_ = process->outfd[NodeProcess::Stdout][0];

    if (process->outfd[NodeProcess::Stderr][0] > highest_fd_)
      highest_fd_ = process->outfd[NodeProcess::Stderr][0];

    process->Run();
    process->Write(envelope->input());

    list_.push_back(service);

    Poll();
  } else {
    Post(this, MSG_RESPONSE, service);
  }
}

void NodeServiceHandler::DoResponse(ServiceData* service) {
  NodeEnvelope* envelope = service->envelope();
  NodeProcess* process = service->process();

  ServiceList::iterator remove = list_.end();
  int highest_fd = 0;

  NodeEnvelope* e = NULL;
  NodeProcess* p = NULL;
  for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) {
    e = (*it)->envelope();
    p = (*it)->process();
    if (*it == service) {
      remove = it;
    } else {
      // Get highest fd that are not the two we're removing
      if (p->outfd[NodeProcess::Stdout][0] >= highest_fd)
        highest_fd = p->outfd[NodeProcess::Stdout][0];
      if (p->outfd[NodeProcess::Stderr][0] >= highest_fd)
        highest_fd = p->outfd[NodeProcess::Stderr][0];
    }
  }
  highest_fd_ = highest_fd;

  if (remove != list_.end()) {
    envelope->set_code(process->Close());

    FD_CLR(process->outfd[NodeProcess::Stdout][0], &rfds_);
    FD_CLR(process->outfd[NodeProcess::Stderr][0], &rfds_);

    list_.erase(remove);
  }

  delete process;
  delete service;

  NodeLoop::Instance()->Response(envelope);
}

void NodeServiceHandler::DoPoll() {
  polling_--;
  if (list_.empty())
    return;

  struct timeval tv;
  tv.tv_sec = PROCESS_BUFFER_SLEEP;
  tv.tv_usec = 0;

  fd_set rfds;
  FD_ZERO(&rfds);
  FD_COPY(&rfds_, &rfds);

  int sr = select(highest_fd_ + 1, &rfds, NULL, NULL, &tv);

  NodeEnvelope* e;
  NodeProcess *p;
  for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) {
    e = (*it)->envelope();
    p = (*it)->process();
    if (sr > 0) {
      // check both stdout and stderr
      for (int i = NodeProcess::Stdout; i <= NodeProcess::Stderr; i++) {
        // check if ready for reading
        if (FD_ISSET(p->outfd[i][0], &rfds)) {
          char data[PROCESS_BUFFER];
          int rc = read(p->outfd[i][0], data, PROCESS_BUFFER-1);

          if (rc == 0) {
            // got eof for this fd
            p->outfdeof[i] = true;
          } else {
            // update output/error in process
            data[rc] = 0;
            if (NodeProcess::Stdout == i) {
              e->append_output(data);
            } else {
              e->append_error(data);
            }
          }
        }
      }
    }
    if (p->Done()) {
      Post(this, MSG_RESPONSE, *it);
    }
  }

  Poll(PROCESS_POLL_TIMEOUT);
}

bool NodeServiceHandler::Poll(int timeout) {
  if (polling_ > 0) {
    return false;
  }
  polling_++;
  PostDelayed(timeout, this, MSG_POLL);
  return true;
}

void NodeServiceHandler::OnMessage(txmpp::Message *pmsg) {
  switch (pmsg->message_id) {
    case MSG_REQUEST:
      assert(pmsg->pdata);
      DoRequest(reinterpret_cast<ServiceData*>(pmsg->pdata));
      break;
    case MSG_RESPONSE:
      assert(pmsg->pdata);
      DoResponse(reinterpret_cast<ServiceData*>(pmsg->pdata));
      break;
    case MSG_POLL:
      DoPoll();
      break;
    default:
      assert(false);
  }
}

int64 NodeServiceHandler::CurrentTime() {
  return (int64)txmpp::Time();
}

}  // namespace tyrion
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
// NoLifeNxBench - Part of the NoLifeStory project                          //
// Copyright (C) 2013 Peter Atashian                                        //
//                                                                          //
// This program is free software: you can redistribute it and/or modify     //
// it under the terms of the GNU Affero General Public License as           //
// published by the Free Software Foundation, either version 3 of the       //
// License, or (at your option) any later version.                          //
//                                                                          //
// This program 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 Affero General Public License for more details.                      //
//                                                                          //
// You should have received a copy of the GNU Affero General Public License //
// along with this program.  If not, see <http://www.gnu.org/licenses/>.    //
//////////////////////////////////////////////////////////////////////////////
#include "../NoLifeNx/NX.hpp"
#include <cstdio>
#include <ctime>
#include <Windows.h>
NL::File const file("Data.nx");
NL::Node const node = file.Base()["Map"]["Map"]["Map1"]["105060000.img"]["1"]["tile"];
size_t c;
uint64_t freq;
void stringsearch() {
    for (NL::Node n : node) if (node[n.NameFast()] != n) throw;
}
void fileload() {
    delete new NL::File("Data.nx");
}
void recurse(NL::Node n) {
    c++;
    for (NL::Node nn : n) recurse(nn);
}
void initialrecurse() {
    NL::File f("Data.nx");
    recurse(f.Base());
}
void morerecurse() {
    recurse(file.Base());
}
extern "C" {
    extern void asmrecurse( char const *,  char const *);
}
void recurseoptimal() {
    NL::Node n = file.Base();
    char const * f = *(reinterpret_cast<char const **>(&n) + 1);
    char const * d = *reinterpret_cast<char const **>(&n);
    asmrecurse(f, d);
}
uint64_t gethpc() {
    LARGE_INTEGER n;
    QueryPerformanceCounter(&n);
    return n.QuadPart;
}
void getfreq() {
    LARGE_INTEGER n;
    QueryPerformanceFrequency(&n);
    freq = n.QuadPart;
}
template <typename T>
void test(const char * name, T f) {
    uint64_t best = -1;
    uint64_t c0 = gethpc();
    do {
        uint64_t c1 = gethpc();
        f();
        uint64_t c2 = gethpc();
        uint64_t dif = c2 - c1;
        if (dif < best) best = dif;
    } while (gethpc() - c0 < freq);
    printf("%s: %uus\n", name, best * 1000000ULL / freq);
}
std::pair<uint64_t, uint64_t> results[0x10000] = {};
void stringrecurse(NL::Node n) {
    for (NL::Node nn : n) stringrecurse(nn);
    uint64_t c0 = gethpc();
    for (size_t i = 0x10; i; --i) for (NL::Node nn : n) if (n[nn.NameFast()] != nn) throw;
    uint64_t c1 = gethpc();
    results[n.Size()].first += c1 - c0;
    results[n.Size()].second += 1;
}
void stringtest() {
    stringrecurse(file.Base());
    for (size_t i = 1; i < 0x10000; ++i) {
        auto && r = results[i];
        if (r.second) printf("%u: %uns\n", i, r.first * 1000000000ULL / (r.second * freq * i * 0x10));
    }
}
int main() {
    getfreq();
    test("File Loading", fileload);
    test("String Searching", stringsearch);
    test("Initial Recursion", initialrecurse);
    test("C++ Recursion", morerecurse);
    test("ASM Recursion", recurseoptimal);
    stringtest();
}<commit_msg>Added an alternate C++ recursion method that is slightly faster.<commit_after>//////////////////////////////////////////////////////////////////////////////
// NoLifeNxBench - Part of the NoLifeStory project                          //
// Copyright (C) 2013 Peter Atashian                                        //
//                                                                          //
// This program is free software: you can redistribute it and/or modify     //
// it under the terms of the GNU Affero General Public License as           //
// published by the Free Software Foundation, either version 3 of the       //
// License, or (at your option) any later version.                          //
//                                                                          //
// This program 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 Affero General Public License for more details.                      //
//                                                                          //
// You should have received a copy of the GNU Affero General Public License //
// along with this program.  If not, see <http://www.gnu.org/licenses/>.    //
//////////////////////////////////////////////////////////////////////////////
#include "../NoLifeNx/NX.hpp"
#include <cstdio>
#include <cmath>
#include <ctime>
#include <Windows.h>
NL::File const file("Data.nx");
NL::Node const node = file.Base()["Map"]["Map"]["Map1"]["105060000.img"]["1"]["tile"];
size_t c;
uint64_t freq;
void stringsearch() {
    for (NL::Node n : node) if (node[n.NameFast()] != n) throw;
}
void fileload() {
    delete new NL::File("Data.nx");
}
void recursealternate2(NL::Node n) {
    NL::Node nn = n.begin();
    for (auto i =  n.Size(); i; --i, ++nn) recursealternate2(nn);
}
void recursealternate() {
    recursealternate2(file.Base());
}
void recurse(NL::Node n) {
    c++;
    for (NL::Node nn : n) recurse(nn);
}
void initialrecurse() {
    NL::File f("Data.nx");
    recurse(f.Base());
}
void morerecurse() {
    recurse(file.Base());
}
extern "C" {
    extern void asmrecurse(char const *,  char const *);
}
void recurseoptimal() {
    NL::Node n = file.Base();
    char const * f = *(reinterpret_cast<char const **>(&n) + 1);
    char const * d = *reinterpret_cast<char const **>(&n);
    asmrecurse(f, d);
}
uint64_t gethpc() {
    LARGE_INTEGER n;
    QueryPerformanceCounter(&n);
    return n.QuadPart;
}
void getfreq() {
    LARGE_INTEGER n;
    QueryPerformanceFrequency(&n);
    freq = n.QuadPart;
}
template <typename T>
void test(const char * name, T f) {
    uint64_t best = -1;
    uint64_t c0 = gethpc();
    do {
        uint64_t c1 = gethpc();
        f();
        uint64_t c2 = gethpc();
        uint64_t dif = c2 - c1;
        if (dif < best) best = dif;
    } while (gethpc() - c0 < freq);
    printf("%s: %uus\n", name, best * 1000000ULL / freq);
}
std::pair<uint64_t, uint64_t> results[0x10000] = {};
void stringrecurse(NL::Node n) {
    for (NL::Node nn : n) stringrecurse(nn);
    uint64_t c0 = gethpc();
    for (size_t i = 0x10; i; --i) for (NL::Node nn : n) if (n[nn.NameFast()] != nn) throw;
    uint64_t c1 = gethpc();
    results[n.Size()].first += c1 - c0;
    results[n.Size()].second += 1;
}
void stringtest() {
    stringrecurse(file.Base());
    for (size_t i = 1; i < 0x10000; ++i) {
        auto && r = results[i];
        double t = r.first * 1000000000. / (r.second * freq * i * 0x10);
        if (r.second) printf("%u: %fns\n", i, t);
    }
}
int main() {
    getfreq();
    test("File Loading", fileload);
    test("String Searching", stringsearch);
    test("Initial Recursion", initialrecurse);
    test("C++ Recursion", morerecurse);
    test("Alternate C++ Recursion", recursealternate);
    test("ASM Recursion", recurseoptimal);
    stringtest();
}<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/process.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/renderer_host/audio_renderer_host.h"
#include "chrome/common/render_messages.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::SetArgumentPointee;

namespace {

const int kInvalidId = -1;
const int kProcessId = 100;
const int kRouteId = 200;
const int kBufferCapacity = 65536;
const int kPacketSize = 16384;

}  // namespace

class MockAudioRendererHost : public AudioRendererHost {
 public:
  MockAudioRendererHost(MessageLoop* loop)
      : AudioRendererHost(loop) {
  }

  // A list of mock methods.
  MOCK_METHOD4(OnRequestPacket,
               void(int routing_id, int stream_id,
                    size_t bytes_in_buffer, int64 message_timestamp));

  MOCK_METHOD3(OnStreamCreated,
               void(int routing_id, int stream_id, int length));

  MOCK_METHOD4(OnStreamStateChanged,
               void(int routing_id, int stream_id,
                    AudioOutputStream::State state, int info));

  MOCK_METHOD4(OnStreamVolume,
               void(int routing_id, int stream_id, double left, double right));

  base::SharedMemory* shared_memory() { return shared_memory_.get(); }

 protected:
  // This method is used to dispatch IPC messages to the renderer. We intercept
  // these messages here and dispatch to our mock methods to verify the
  // conversation between this object and the renderer.
  virtual void Send(IPC::Message* message) {
    CHECK(message);

    // In this method we dispatch the messages to the according handlers as if
    // we are the renderer.
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(MockAudioRendererHost, *message)
      IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged,
                          OnStreamStateChanged)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    EXPECT_TRUE(handled);

    delete message;
  }

 private:
  // These handler methods do minimal things and delegate to the mock methods.
  void OnRequestPacket(const IPC::Message& msg, int stream_id,
                       size_t bytes_in_buffer, int64 message_timestamp) {
    OnRequestPacket(msg.routing_id(), stream_id, bytes_in_buffer,
                    message_timestamp);
  }

  void OnStreamCreated(const IPC::Message& msg, int stream_id,
                       base::SharedMemoryHandle handle, int length) {
    // Maps the shared memory.
    shared_memory_.reset(new base::SharedMemory(handle, true));
    CHECK(shared_memory_->Map(length));
    CHECK(shared_memory_->memory());

    // And then delegate the call to the mock method.
    OnStreamCreated(msg.routing_id(), stream_id, length);
  }

  void OnStreamStateChanged(const IPC::Message& msg, int stream_id,
                            AudioOutputStream::State state, int info) {
    OnStreamStateChanged(msg.routing_id(), stream_id, state, info);
  }

  void OnStreamVolume(const IPC::Message& msg, int stream_id,
                      double left, double right) {
    OnStreamVolume(msg.routing_id(), stream_id, left, right);
  }

  scoped_ptr<base::SharedMemory> shared_memory_;

  DISALLOW_COPY_AND_ASSIGN(MockAudioRendererHost);
};

class AudioRendererHostTest : public testing::Test {
 public:
  AudioRendererHostTest()
      : current_stream_id_(0) {
  }

 protected:
  virtual void SetUp() {
    // Create a message loop so AudioRendererHost can use it.
    message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO));
    host_ = new MockAudioRendererHost(message_loop_.get());
    CHECK(host_);
  }

  virtual void TearDown() {
    // This task post a task to message_loop_ to do internal destruction on
    // message_loop_.
    host_->Destroy();
    // We need to continue running message_loop_ to complete all destructions.
    message_loop_->RunAllPending();
  }

  AudioRendererHost::IPCAudioSource* CreateAudioStream(
      AudioManager::Format format) {
    InSequence s;

    // 1. We will first receive a OnStreamCreated() signal.
    EXPECT_CALL(*host_,
                OnStreamCreated(kRouteId, current_stream_id_, kPacketSize));

    // 2. First packet request will arrive. This request is sent by
    //    IPCAudioSource::CreateIPCAudioSource to start buffering.
    EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 0, _));

    AudioRendererHost::IPCAudioSource* source =
        AudioRendererHost::IPCAudioSource::CreateIPCAudioSource(
            host_,
            kProcessId,
            kRouteId,
            current_stream_id_,
            base::GetCurrentProcessHandle(),
            format,
            2,
            AudioManager::kAudioCDSampleRate,
            16,
            kPacketSize,
            kBufferCapacity);
    EXPECT_TRUE(source);
    EXPECT_EQ(kProcessId, source->process_id());
    EXPECT_EQ(kRouteId, source->route_id());
    EXPECT_EQ(current_stream_id_, source->stream_id());
    return source;
  }

  AudioRendererHost::IPCAudioSource* CreateRealStream() {
    return CreateAudioStream(AudioManager::AUDIO_PCM_LINEAR);
  }

  AudioRendererHost::IPCAudioSource* CreateMockStream() {
    return CreateAudioStream(AudioManager::AUDIO_MOCK);
  }

  int current_stream_id_;
  scoped_refptr<MockAudioRendererHost> host_;
  scoped_ptr<MessageLoop> message_loop_;

 private:
  DISALLOW_COPY_AND_ASSIGN(AudioRendererHostTest);
};

// Audio output stream only works stably on windows. Also there's no mock
// audio output streams for mac and linux.
// TODO(hclam): make these tests work on mac and linux.
#if defined(OS_WIN)

TEST_F(AudioRendererHostTest, CreateMockStream) {
  scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream());
}

TEST_F(AudioRendererHostTest, MockStreamDataConversation) {
  scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream());

  // We will receive packet requests until the buffer is full. We first send
  // three packets of 16KB, then we send packets of 1KB until the buffer is
  // full. Then there will no more packet requests.
  EXPECT_CALL(*host_,
      OnRequestPacket(kRouteId, current_stream_id_, kPacketSize, _));
  EXPECT_CALL(*host_,
      OnRequestPacket(kRouteId, current_stream_id_, 2 * kPacketSize, _));
  for (int size = 3 * kPacketSize; size < kBufferCapacity; size += 1024) {
    EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, size, _));
  }

  source->NotifyPacketReady(kPacketSize);
  source->NotifyPacketReady(kPacketSize);
  source->NotifyPacketReady(kPacketSize);
  for (int size = 0; size < kPacketSize; size += 1024) {
    source->NotifyPacketReady(1024);
  }
}

#endif
<commit_msg>Revert "Unit tests for AudioRendererHost"<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/process.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/renderer_host/audio_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"

class AudioRendererHostTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // Create a message loop so AudioRendererHost can use it.
    message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO));
    host_ = new AudioRendererHost(message_loop_.get());
  }

  virtual void TearDown() {
    // This task post a task to message_loop_ to do internal destruction on
    // message_loop_.
    host_->Destroy();
    // We need to continue running message_loop_ to complete all destructions.
    message_loop_->RunAllPending();
  }

  scoped_refptr<AudioRendererHost> host_;
  scoped_ptr<MessageLoop> message_loop_;
};

TEST_F(AudioRendererHostTest, NoTest) {
  // TODO(hclam): come up with useful tests.
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/gtk/bookmarks/bookmark_bar_gtk.h"

#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/gtk/tabstrip_origin_provider.h"
#include "chrome/test/base/testing_profile.h"
#include "content/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

using content::BrowserThread;

// Dummy implementation that's good enough for the tests; we don't test
// rendering here so all we need is a non-NULL object.
class EmptyTabstripOriginProvider : public TabstripOriginProvider {
 public:
  virtual gfx::Point GetTabStripOriginForWidget(GtkWidget* widget) {
    return gfx::Point(0, 0);
  }
};

class BookmarkBarGtkUnittest : public testing::Test {
 protected:
  BookmarkBarGtkUnittest()
      : ui_thread_(BrowserThread::UI, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_) {
  }

  virtual void SetUp() {
    profile_.reset(new TestingProfile());
    profile_->CreateBookmarkModel(true);
    profile_->BlockUntilBookmarkModelLoaded();
    browser_.reset(new Browser(Browser::TYPE_TABBED, profile_.get()));

    origin_provider_.reset(new EmptyTabstripOriginProvider);
    bookmark_bar_.reset(new BookmarkBarGtk(NULL, browser_.get(),
                                           origin_provider_.get()));
  }

  virtual void TearDown() {
    message_loop_.RunAllPending();

    bookmark_bar_.reset();
    origin_provider_.reset();
    browser_.reset();
    profile_.reset();
  }

  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;

  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<Browser> browser_;
  scoped_ptr<TabstripOriginProvider> origin_provider_;
  scoped_ptr<BookmarkBarGtk> bookmark_bar_;
};

TEST_F(BookmarkBarGtkUnittest, DisplaysHelpMessageOnEmpty) {
  BookmarkModel* model = profile_->GetBookmarkModel();
  bookmark_bar_->Loaded(model, false);

  // There are no bookmarks in the model by default. Expect that the
  // |instructions_label| is shown.
  EXPECT_TRUE(bookmark_bar_->show_instructions_);
}

TEST_F(BookmarkBarGtkUnittest, HidesHelpMessageWithBookmark) {
  BookmarkModel* model = profile_->GetBookmarkModel();

  const BookmarkNode* parent = model->bookmark_bar_node();
  model->AddURL(parent, parent->child_count(),
                ASCIIToUTF16("title"), GURL("http://one.com"));

  bookmark_bar_->Loaded(model, false);
  EXPECT_FALSE(bookmark_bar_->show_instructions_);
}

TEST_F(BookmarkBarGtkUnittest, BuildsButtons) {
  BookmarkModel* model = profile_->GetBookmarkModel();

  const BookmarkNode* parent = model->bookmark_bar_node();
  model->AddURL(parent, parent->child_count(),
                ASCIIToUTF16("title"), GURL("http://one.com"));
  model->AddURL(parent, parent->child_count(),
                ASCIIToUTF16("other"), GURL("http://two.com"));

  bookmark_bar_->Loaded(model, false);

  // We should expect two children to the bookmark bar's toolbar.
  GList* children = gtk_container_get_children(
      GTK_CONTAINER(bookmark_bar_->bookmark_toolbar_.get()));
  EXPECT_EQ(2U, g_list_length(children));
  g_list_free(children);
}
<commit_msg>gtk/bookmarks: Reuse |model_| in BookmarkBarGtkUnittest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/gtk/bookmarks/bookmark_bar_gtk.h"

#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/gtk/tabstrip_origin_provider.h"
#include "chrome/test/base/testing_profile.h"
#include "content/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

using content::BrowserThread;

// Dummy implementation that's good enough for the tests; we don't test
// rendering here so all we need is a non-NULL object.
class EmptyTabstripOriginProvider : public TabstripOriginProvider {
 public:
  virtual gfx::Point GetTabStripOriginForWidget(GtkWidget* widget) {
    return gfx::Point(0, 0);
  }
};

class BookmarkBarGtkUnittest : public testing::Test {
 protected:
  BookmarkBarGtkUnittest()
      : ui_thread_(BrowserThread::UI, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_) {
  }

  virtual void SetUp() OVERRIDE {
    profile_.reset(new TestingProfile());
    profile_->CreateBookmarkModel(true);
    profile_->BlockUntilBookmarkModelLoaded();
    model_ = profile_->GetBookmarkModel();

    browser_.reset(new Browser(Browser::TYPE_TABBED, profile_.get()));
    origin_provider_.reset(new EmptyTabstripOriginProvider);
    bookmark_bar_.reset(new BookmarkBarGtk(NULL, browser_.get(),
                                           origin_provider_.get()));
  }

  virtual void TearDown() OVERRIDE {
    message_loop_.RunAllPending();

    bookmark_bar_.reset();
    origin_provider_.reset();
    browser_.reset();
    profile_.reset();
  }

  BookmarkModel* model_;

  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;

  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<Browser> browser_;
  scoped_ptr<TabstripOriginProvider> origin_provider_;
  scoped_ptr<BookmarkBarGtk> bookmark_bar_;
};

TEST_F(BookmarkBarGtkUnittest, DisplaysHelpMessageOnEmpty) {
  bookmark_bar_->Loaded(model_, false);

  // There are no bookmarks in the model by default. Expect that the
  // |instructions_label| is shown.
  EXPECT_TRUE(bookmark_bar_->show_instructions_);
}

TEST_F(BookmarkBarGtkUnittest, HidesHelpMessageWithBookmark) {
  const BookmarkNode* parent = model_->bookmark_bar_node();
  model_->AddURL(parent, parent->child_count(),
                 ASCIIToUTF16("title"), GURL("http://one.com"));

  bookmark_bar_->Loaded(model_, false);
  EXPECT_FALSE(bookmark_bar_->show_instructions_);
}

TEST_F(BookmarkBarGtkUnittest, BuildsButtons) {
  const BookmarkNode* parent = model_->bookmark_bar_node();
  model_->AddURL(parent, parent->child_count(),
                 ASCIIToUTF16("title"), GURL("http://one.com"));
  model_->AddURL(parent, parent->child_count(),
                 ASCIIToUTF16("other"), GURL("http://two.com"));

  bookmark_bar_->Loaded(model_, false);

  // We should expect two children to the bookmark bar's toolbar.
  GList* children = gtk_container_get_children(
      GTK_CONTAINER(bookmark_bar_->bookmark_toolbar_.get()));
  EXPECT_EQ(2U, g_list_length(children));
  g_list_free(children);
}
<|endoftext|>