<commit_before>/*
    Unit test for Kopete::StatusMessage class.

    Copyright (c) 2006  by Michaël Larouche          <larouche@kde.org>

    Kopete    (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/
#include "xmlcontactstorage_test.h"

// Qt includes
#include <QtCore/QStringList>

// KDE includes
#include <qtest_kde.h>

// Kopete includes
#include "kopetecontactliststorage.h"
#include "xmlcontactstorage.h"
#include "kopetegroup.h"
#include "kopetemetacontact.h"

QTEST_KDEMAIN( XmlContactStorage_Test, GUI )

QStringList expectedGroupList()
{
	QStringList groupList;

	groupList << QString("Kopete Developers");
	groupList << QString("Kontact Developers");
	groupList << QString("Users");
	groupList << QString("Friends & Family");

	return groupList;
}

QStringList expectedContactList()
{
	QStringList contactList;

	contactList << QString("Duncan Mac-Vicar Prett");
	contactList << QString("Olivier Goffart");
	contactList << QString("Matt Rogers");
	contactList << QString("Will Stephenson");
	// NOTE: We need ::fromUtf8 so those string will be really read as UTF8, otherwise test fail.
	contactList << QString::fromUtf8("Michaël Larouche");
	contactList << QString::fromUtf8("André Duffeck");

	return contactList;
}

void XmlContactStorage_Test::testLoad()
{
	// TODO: Check plugin data.
	// TODO: Check more things.
	QString xmlFilename = QString( SRCDIR ) + QString("xmlcontactstorage_test_list.xml");

	Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage( xmlFilename );
	storage->load();

	// Verify that the loading went well.
	QVERIFY( storage->isValid() );
	// Check that we have the correct numbers of groups and contacts.
	QCOMPARE( storage->groups().size(), 5 );
	QCOMPARE( storage->contacts().size(), 6 );

	// Verify that we parsed the correct group names.
	QStringList groupNameList = expectedGroupList();
	QStringList::ConstIterator expectedIt, expectedItEnd = groupNameList.constEnd();

	QSKIP("This test is broken, please someone fix it", SkipAll);
	uint groupId = 1;
	Kopete::Group::List loadGroupList = storage->groups();
	Kopete::Group::List::ConstIterator it, itEnd = loadGroupList.constEnd();
	for(it = loadGroupList.constBegin(), expectedIt = groupNameList.constBegin();
		it != itEnd, expectedIt != expectedItEnd;
		++it, ++expectedIt)
	{
		Kopete::Group *group = (*it);
		QString groupName = group->displayName();
		QString expectedGroupName = (*expectedIt);
		QCOMPARE( groupName, expectedGroupName );
		QCOMPARE( group->groupId(), groupId++ );
	}

	// Verify that we parsed the correct contacts.
	QStringList contactList = expectedContactList();
	QStringList::ConstIterator contactIt, contactItEnd = contactList.constEnd();

	Kopete::MetaContact::List loadContactList = storage->contacts();
	Kopete::MetaContact::List::ConstIterator loadContactIt, loadContactItEnd = loadContactList.constEnd();
	for(loadContactIt = loadContactList.constBegin(), contactIt = contactList.constBegin();
		loadContactIt != loadContactItEnd, contactIt != contactItEnd;
		++loadContactIt, ++contactIt)
	{
		Kopete::MetaContact *contact = (*loadContactIt);
		QString expectedContactName = (*contactIt);

		QCOMPARE( contact->displayName(), expectedContactName );
		QCOMPARE( (int)contact->displayNameSource(), (int)Kopete::MetaContact::SourceCustom );
	}
}

#include "xmlcontactstorage_test.moc"
<commit_msg>Finally fix test xmlcontactstorage_test<commit_after>/*
    Unit test for Kopete::StatusMessage class.

    Copyright (c) 2006  by Michaël Larouche          <larouche@kde.org>

    Kopete    (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/
#include "xmlcontactstorage_test.h"

// Qt includes
#include <QtCore/QStringList>

// KDE includes
#include <qtest_kde.h>

// Kopete includes
#include "kopetecontactliststorage.h"
#include "xmlcontactstorage.h"
#include "kopetegroup.h"
#include "kopetemetacontact.h"

QTEST_KDEMAIN( XmlContactStorage_Test, GUI )

QStringList expectedGroupList()
{
	QStringList groupList;

	groupList << QString("Kopete Developers");
	groupList << QString("Kontact Developers");
	groupList << QString("Users");
	groupList << QString("Friends & Family");
	groupList << QString("Top Level");

	return groupList;
}

QStringList expectedContactList()
{
	QStringList contactList;

	contactList << QString("Duncan Mac-Vicar Prett");
	contactList << QString("Olivier Goffart");
	contactList << QString("Matt Rogers");
	contactList << QString("Will Stephenson");
	// NOTE: We need ::fromUtf8 so those string will be really read as UTF8, otherwise test fail.
	contactList << QString::fromUtf8("Michaël Larouche");
	contactList << QString::fromUtf8("André Duffeck");

	return contactList;
}

void XmlContactStorage_Test::testLoad()
{
	// TODO: Check plugin data.
	// TODO: Check more things.
	QString xmlFilename = QString( SRCDIR ) + QString("xmlcontactstorage_test_list.xml");

	Kopete::ContactListStorage *storage = new Kopete::XmlContactStorage( xmlFilename );
	storage->load();

	// Verify that the loading went well.
	QVERIFY( storage->isValid() );
	// Check that we have the correct numbers of groups and contacts.
	QCOMPARE( storage->groups().size(), 5 );
	QCOMPARE( storage->contacts().size(), 6 );

	// Verify that we parsed the correct group names.
	QStringList groupNameList = expectedGroupList();
	QStringList::ConstIterator expectedIt, expectedItEnd = groupNameList.constEnd();

	uint groupId = 1;
	Kopete::Group::List loadGroupList = storage->groups();
	Kopete::Group::List::ConstIterator it, itEnd = loadGroupList.constEnd();
	for(it = loadGroupList.constBegin(), expectedIt = groupNameList.constBegin();
		it != itEnd, expectedIt != expectedItEnd;
		++it, ++expectedIt)
	{
		Kopete::Group *group = (*it);
		QString groupName = group->displayName();
		QString expectedGroupName = (*expectedIt);
		QCOMPARE( groupName, expectedGroupName );
		QCOMPARE( group->groupId(), groupId++ );
	}

	// Verify that we parsed the correct contacts.
	QStringList contactList = expectedContactList();
	QStringList::ConstIterator contactIt, contactItEnd = contactList.constEnd();

	Kopete::MetaContact::List loadContactList = storage->contacts();
	Kopete::MetaContact::List::ConstIterator loadContactIt, loadContactItEnd = loadContactList.constEnd();
	for(loadContactIt = loadContactList.constBegin(), contactIt = contactList.constBegin();
		loadContactIt != loadContactItEnd, contactIt != contactItEnd;
		++loadContactIt, ++contactIt)
	{
		Kopete::MetaContact *contact = (*loadContactIt);
		QString expectedContactName = (*contactIt);

		QCOMPARE( contact->displayName(), expectedContactName );
		QCOMPARE( (int)contact->displayNameSource(), (int)Kopete::MetaContact::SourceCustom );
	}
}

#include "xmlcontactstorage_test.moc"
<|endoftext|>


<commit_before>#pragma once

#include <Eigen/Dense>

namespace LinAlg {

	/** constructors */
	inline Eigen::MatrixXf eye(size_t n) {
		return MatrixXf::Identity(n, n);
	}

}
<commit_msg>removed the rest of the old linear algebra stuff<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <boost/program_options.hpp>
#include "common.h"
#include "scope_guard.h"
#include "context.h"
#include "agenda.h"
#include "commands.h"
#include "errors.h"
#include <sys/ioctl.h>
#include <boost/bind.hpp>
#include <curl/curl.h>
#include "mimes.h"

using namespace es3;
namespace po = boost::program_options;

int es3::term_width = 80;

std::vector<po::option> subcommands_parser(stringvec& args,
										   const stringvec& subcommands)
{
	std::vector<po::option> result;
	if (args.empty())
		return result;

	stringvec::const_iterator i(args.begin());
	stringvec::const_iterator cmd_idx=std::find(subcommands.begin(),
												subcommands.end(),*i);
	if (cmd_idx!=subcommands.end())
	{
		po::option opt;
		opt.string_key = "subcommand";
		opt.value.push_back(*i);
		opt.original_tokens.push_back(*i);
		result.push_back(opt);

		for (++i; i != args.end(); ++i)
		{
			po::option opt;
			opt.string_key = "subcommand_params";
			opt.value.push_back(*i);
			opt.original_tokens.push_back(*i);
			result.push_back(opt);
		}
		args.clear();
	}
	return result;
}

static std::string get_at(const std::map<std::string, std::string> &map,
					  const std::string &key)
{
	return try_get(map, key);
}

int main(int argc, char **argv)
{
	int verbosity = 0;

	//Get terminal size (to pretty-print help text)
	struct winsize w={0};
	ioctl(0, TIOCGWINSZ, &w);
	term_width=(w.ws_col==0)? 80 : w.ws_col;

	init_mimes();
	context_ptr cd(new conn_context());

	po::options_description generic("Generic options", term_width);
	generic.add_options()
		("help", "Display this message")
		("config,c", po::value<std::string>(),
			"Path to a file that contains configuration settings")
		("verbosity,v", po::value<int>(&verbosity)->default_value(1),
			"Verbosity level [0 - the lowest, 9 - the highest]")
		("no-progress,q", "Quiet mode (no progress indicator)")
		("no-stats,t", "Quiet mode (no final stats)")
		("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_)
			->default_value(bf::temp_directory_path())->required(),
			"Path to the scratch directory")
	;

	po::options_description access("Access settings", term_width);
	access.add_options()
		("access-key,a", po::value<std::string>(
			 &cd->api_key_)->required(),
			"Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID "
			"environment variable is used.")
		("secret-key,s", po::value<std::string>(
			 &cd->secret_key)->required(),
			"Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY "
			"environment variable is used.")
		("use-ssl,l", po::value<bool>(
			 &cd->use_ssl_)->default_value(false),
			"Use SSL for communications with the Amazon S3 servers")
		("compression,m", po::value<bool>(
			 &cd->do_compression_)->default_value(true)->required(),
			"Use GZIP compression")
	;
	generic.add(access);

	int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0;
	po::options_description tuning("Tuning", term_width);
	tuning.add_options()
		("thread-num,n", po::value<int>(&thread_num)->default_value(0),
			"Number of download/upload threads used [0 - autodetect]")
		("reader-threads,r", po::value<int>(
			 &io_threads)->default_value(0),
			"Number of filesystem reader/writer threads [0 - autodetect]")
		("compressor-threads,o", po::value<int>(
			 &cpu_threads)->default_value(0),
			"Number of compressor threads [0 - autodetect]")
		("segment-size,g", po::value<int>(
			&segment_size)->default_value(0),
			"Segment size in bytes [0 - autodetect, 6291456 - minimum]")
		("segments-in-flight,f", po::value<int>(
			 &segments)->default_value(0),
			"Number of segments in-flight [0 - autodetect]")
	;
	generic.add(tuning);

	po::options_description sub_data("Subcommands");
	sub_data.add_options()
		("subcommand", po::value<std::string>())
		("subcommand_params", po::value<stringvec>()->multitoken());

	std::map< std::string,
			std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> >
			subcommands_map;
	subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4);
	subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4);
	subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4);
	subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4);
	subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4);
	subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4);
	subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4);

	stringvec subcommands;
	for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter)
		subcommands.push_back(iter->first);

	std::string cur_subcommand;
	stringvec cur_sub_params;

	po::variables_map vm;
	try
	{
		sub_data.add(generic);
		po::parsed_options parsed = po::command_line_parser(argc, argv)
				.options(sub_data)
				.extra_style_parser(boost::bind(&subcommands_parser, _1,
												subcommands))
			.run();
		po::store(parsed, vm);

		cur_subcommand=vm.count("subcommand")==0?
					"" : vm["subcommand"].as<std::string>();
		cur_sub_params=vm.count("subcommand_params")==0?
					stringvec() : vm["subcommand_params"].as<stringvec>();

		if (argc < 2 || vm.count("help"))
		{
			if (cur_subcommand.empty())
			{
				std::cout << "Extreme S3 - fast S3 client\n" << generic
						  << "\nThe following commands are supported:\n\t";
				for(auto iter=subcommands.begin();iter!=subcommands.end();++iter)
					std::cout<< *iter <<" ";
				std::cout << "\nUse --help <command_name> to get more info\n";
			} else
			{
				std::cout << "Extreme S3 - fast S3 client\n";
				subcommands_map[cur_subcommand](cd, cur_sub_params,
												agenda_ptr(), true);
			}
			return 1;
		}

		if (cur_subcommand.empty())
		{
			std::cout << "No command specified. Use --help for help\n";
			return 2;
		}
	} catch(const boost::program_options::error &err)
	{
		std::cerr << "Failed to parse command line. Error: "
				  << err.what() << std::endl;
		return 2;
	}

	try
	{
		if (vm.count("config"))
		{
			// Parse the file and store the options
			std::string config_file = vm["config"].as<std::string>();
			po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm);
		} else if (getenv("ES3_CONFIG"))
		{
			po::store(po::parse_config_file<char>(
						  getenv("ES3_CONFIG"),generic), vm);
		} else
		{
			const char *home=getenv("HOME");
			if (home)
			{
				bf::path cfg=bf::path(home) / ".es3cfg";
				if (bf::exists(cfg))
					po::store(po::parse_config_file<char>(
								  cfg.c_str(),generic), vm);
			}
		}

		//Try to parse the environment
		std::map<std::string, std::string> env_name_map;
		env_name_map["AWS_ACCESS_KEY_ID"]="access-key";
		env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key";
		po::store(po::parse_environment(generic, boost::bind(
											&get_at, env_name_map, _1)), vm);
	} catch(const boost::program_options::error &err)
	{
		std::cerr << "Failed to parse the configuration file. Error: "
				  << err.what() << std::endl;
		return 2;
	}

	bool no_progress = vm.count("no-progress");
	bool no_stats = vm.count("no-stats");

	try
	{
		po::notify(vm);
	} catch(const boost::program_options::required_option &option)
	{
		std::cerr << "Required option " << option.get_option_name()
				  << " is not present." << std::endl;
		return 1;
	}

	logger::set_verbosity(verbosity);
	curl_global_init(CURL_GLOBAL_ALL);
	ON_BLOCK_EXIT(&curl_global_cleanup);

	if (segments>MAX_IN_FLIGHT || segments<=0)
		segments=MAX_IN_FLIGHT;
	if (segment_size<MIN_SEGMENT_SIZE)
		segment_size=MIN_SEGMENT_SIZE;
	if (cpu_threads<=0)
		cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2;
	if (io_threads<=0)
		io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2;
	if (thread_num<=0)
		thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40;

	if (cur_subcommand=="cat")
	{
		no_progress=no_stats=true; //A special hack
	}

	agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads,
							 no_progress, no_stats,
							 segment_size, segments));

	try
	{
		return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false);
	} catch(const es3_exception &ex)
	{
		VLOG(0) << "" << ex.what() << std::endl;
		return 8;
	} catch(const std::exception &ex)
	{
		VLOG(0) << "Unexpected error: " << ex.what() << std::endl;
		return 8;
	}
}
<commit_msg>Tweak params<commit_after>#include <iostream>
#include <boost/program_options.hpp>
#include "common.h"
#include "scope_guard.h"
#include "context.h"
#include "agenda.h"
#include "commands.h"
#include "errors.h"
#include <sys/ioctl.h>
#include <boost/bind.hpp>
#include <curl/curl.h>
#include "mimes.h"

using namespace es3;
namespace po = boost::program_options;

int es3::term_width = 80;

std::vector<po::option> subcommands_parser(stringvec& args,
										   const stringvec& subcommands)
{
	std::vector<po::option> result;
	if (args.empty())
		return result;

	stringvec::const_iterator i(args.begin());
	stringvec::const_iterator cmd_idx=std::find(subcommands.begin(),
												subcommands.end(),*i);
	if (cmd_idx!=subcommands.end())
	{
		po::option opt;
		opt.string_key = "subcommand";
		opt.value.push_back(*i);
		opt.original_tokens.push_back(*i);
		result.push_back(opt);

		for (++i; i != args.end(); ++i)
		{
			po::option opt;
			opt.string_key = "subcommand_params";
			opt.value.push_back(*i);
			opt.original_tokens.push_back(*i);
			result.push_back(opt);
		}
		args.clear();
	}
	return result;
}

static std::string get_at(const std::map<std::string, std::string> &map,
					  const std::string &key)
{
	return try_get(map, key);
}

int main(int argc, char **argv)
{
	int verbosity = 0;

	//Get terminal size (to pretty-print help text)
	struct winsize w={0};
	ioctl(0, TIOCGWINSZ, &w);
	term_width=(w.ws_col==0)? 80 : w.ws_col;

	init_mimes();
	context_ptr cd(new conn_context());

	po::options_description generic("Generic options", term_width);
	generic.add_options()
		("help", "Display this message")
		("config,c", po::value<std::string>(),
			"Path to a file that contains configuration settings")
		("verbosity,v", po::value<int>(&verbosity)->default_value(1),
			"Verbosity level [0 - the lowest, 9 - the highest]")
		("no-progress,q", "Quiet mode (no progress indicator)")
		("no-stats,t", "Quiet mode (no final stats)")
		("scratch-dir,i", po::value<bf::path>(&cd->scratch_dir_)
			->default_value(bf::temp_directory_path())->required(),
			"Path to the scratch directory")
	;

	po::options_description access("Access settings", term_width);
	access.add_options()
		("access-key,a", po::value<std::string>(
			 &cd->api_key_)->required(),
			"Amazon S3 API key. If not set then AWS_ACCESS_KEY_ID "
			"environment variable is used.")
		("secret-key,s", po::value<std::string>(
			 &cd->secret_key)->required(),
			"Amazon S3 secret key. If not set then AWS_SECRET_ACCESS_KEY "
			"environment variable is used.")
		("use-ssl,l", po::value<bool>(
			 &cd->use_ssl_)->default_value(false),
			"Use SSL for communications with the Amazon S3 servers")
		("compression,m", po::value<bool>(
			 &cd->do_compression_)->default_value(true)->required(),
			"Use GZIP compression")
	;
	generic.add(access);

	int thread_num=0, io_threads=0, cpu_threads=0, segment_size=0, segments=0;
	po::options_description tuning("Tuning", term_width);
	tuning.add_options()
		("thread-num,n", po::value<int>(&thread_num)->default_value(0),
			"Number of download/upload threads used [0 - autodetect]")
		("reader-threads,r", po::value<int>(
			 &io_threads)->default_value(0),
			"Number of filesystem reader/writer threads [0 - autodetect]")
		("compressor-threads,o", po::value<int>(
			 &cpu_threads)->default_value(0),
			"Number of compressor threads [0 - autodetect]")
		("segment-size,g", po::value<int>(
			&segment_size)->default_value(0),
			"Segment size in bytes [0 - autodetect, 6291456 - minimum]")
		("segments-in-flight,f", po::value<int>(
			 &segments)->default_value(0),
			"Number of segments in-flight [0 - autodetect]")
	;
	generic.add(tuning);

	po::options_description sub_data("Subcommands");
	sub_data.add_options()
		("subcommand", po::value<std::string>())
		("subcommand_params", po::value<stringvec>()->multitoken());

	std::map< std::string,
			std::function<int(context_ptr, const stringvec&, agenda_ptr, bool)> >
			subcommands_map;
	subcommands_map["sync"] = boost::bind(&do_rsync, _1, _2, _3, _4);
	subcommands_map["test"] = boost::bind(&do_test, _1, _2, _3, _4);
	subcommands_map["touch"] = boost::bind(&do_touch, _1, _2, _3, _4);
	subcommands_map["rm"] = boost::bind(&do_rm, _1, _2, _3, _4);
	subcommands_map["du"] = boost::bind(&do_du, _1, _2, _3, _4);
	subcommands_map["ls"] = boost::bind(&do_ls, _1, _2, _3, _4);
	subcommands_map["cat"] = boost::bind(&do_cat, _1, _2, _3, _4);

	stringvec subcommands;
	for(auto iter=subcommands_map.begin();iter!=subcommands_map.end();++iter)
		subcommands.push_back(iter->first);

	std::string cur_subcommand;
	stringvec cur_sub_params;

	po::variables_map vm;
	try
	{
		sub_data.add(generic);
		po::parsed_options parsed = po::command_line_parser(argc, argv)
				.options(sub_data)
				.extra_style_parser(boost::bind(&subcommands_parser, _1,
												subcommands))
			.run();
		po::store(parsed, vm);

		cur_subcommand=vm.count("subcommand")==0?
					"" : vm["subcommand"].as<std::string>();
		cur_sub_params=vm.count("subcommand_params")==0?
					stringvec() : vm["subcommand_params"].as<stringvec>();

		if (argc < 2 || vm.count("help"))
		{
			if (cur_subcommand.empty())
			{
				std::cout << "Extreme S3 - fast S3 client\n" << generic
						  << "\nThe following commands are supported:\n\t";
				for(auto iter=subcommands.begin();iter!=subcommands.end();++iter)
					std::cout<< *iter <<" ";
				std::cout << "\nUse --help <command_name> to get more info\n";
			} else
			{
				std::cout << "Extreme S3 - fast S3 client\n";
				subcommands_map[cur_subcommand](cd, cur_sub_params,
												agenda_ptr(), true);
			}
			return 1;
		}

		if (cur_subcommand.empty())
		{
			std::cout << "No command specified. Use --help for help\n";
			return 2;
		}
	} catch(const boost::program_options::error &err)
	{
		std::cerr << "Failed to parse command line. Error: "
				  << err.what() << std::endl;
		return 2;
	}

	try
	{
		if (vm.count("config"))
		{
			// Parse the file and store the options
			std::string config_file = vm["config"].as<std::string>();
			po::store(po::parse_config_file<char>(config_file.c_str(),generic), vm);
		} else if (getenv("ES3_CONFIG"))
		{
			po::store(po::parse_config_file<char>(
						  getenv("ES3_CONFIG"),generic), vm);
		} else
		{
			const char *home=getenv("HOME");
			if (home)
			{
				bf::path cfg=bf::path(home) / ".es3cfg";
				if (bf::exists(cfg))
					po::store(po::parse_config_file<char>(
								  cfg.c_str(),generic), vm);
			}
		}

		//Try to parse the environment
		std::map<std::string, std::string> env_name_map;
		env_name_map["AWS_ACCESS_KEY_ID"]="access-key";
		env_name_map["AWS_SECRET_ACCESS_KEY"]="secret-key";
		po::store(po::parse_environment(generic, boost::bind(
											&get_at, env_name_map, _1)), vm);
	} catch(const boost::program_options::error &err)
	{
		std::cerr << "Failed to parse the configuration file. Error: "
				  << err.what() << std::endl;
		return 2;
	}

	bool no_progress = vm.count("no-progress");
	bool no_stats = vm.count("no-stats");

	try
	{
		po::notify(vm);
	} catch(const boost::program_options::required_option &option)
	{
		std::cerr << "Required option " << option.get_option_name()
				  << " is not present." << std::endl;
		return 1;
	}

	logger::set_verbosity(verbosity);
	curl_global_init(CURL_GLOBAL_ALL);
	ON_BLOCK_EXIT(&curl_global_cleanup);

	if (segments>MAX_IN_FLIGHT)
		segments=MAX_IN_FLIGHT;
	else if (segments<=0)
		segments=40;
	if (segment_size<MIN_SEGMENT_SIZE)
		segment_size=MIN_SEGMENT_SIZE;
	if (cpu_threads<=0)
		cpu_threads=sysconf(_SC_NPROCESSORS_ONLN)+2;
	if (io_threads<=0)
		io_threads=sysconf(_SC_NPROCESSORS_ONLN)*2+2;
	if (thread_num<=0)
		thread_num=sysconf(_SC_NPROCESSORS_ONLN)*6+40;

	if (cur_subcommand=="cat")
	{
		no_progress=no_stats=true; //A special hack
	}

	agenda_ptr ag(new agenda(thread_num, cpu_threads, io_threads,
							 no_progress, no_stats,
							 segment_size, segments));

	try
	{
		return subcommands_map[cur_subcommand](cd, cur_sub_params, ag, false);
	} catch(const es3_exception &ex)
	{
		VLOG(0) << "" << ex.what() << std::endl;
		return 8;
	} catch(const std::exception &ex)
	{
		VLOG(0) << "Unexpected error: " << ex.what() << std::endl;
		return 8;
	}
}
<|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 "chrome_frame/bho.h"

#include <shlguid.h>

#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "chrome_tab.h" // NOLINT
#include "chrome_frame/extra_system_apis.h"
#include "chrome_frame/http_negotiate.h"
#include "chrome_frame/protocol_sink_wrap.h"
#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"

static const int kIBrowserServiceOnHttpEquivIndex = 30;

PatchHelper g_patch_helper;

BEGIN_VTABLE_PATCHES(IBrowserService)
  VTABLE_PATCH_ENTRY(kIBrowserServiceOnHttpEquivIndex, Bho::OnHttpEquiv)
END_VTABLE_PATCHES()

_ATL_FUNC_INFO Bho::kBeforeNavigate2Info = {
  CC_STDCALL, VT_EMPTY, 7, {
    VT_DISPATCH,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_BOOL | VT_BYREF
  }
};

_ATL_FUNC_INFO Bho::kNavigateComplete2Info = {
  CC_STDCALL, VT_EMPTY, 2, {
    VT_DISPATCH,
    VT_VARIANT | VT_BYREF
  }
};

Bho::Bho() {
}

HRESULT Bho::FinalConstruct() {
  return S_OK;
}

void Bho::FinalRelease() {
}

STDMETHODIMP Bho::SetSite(IUnknown* site) {
  HRESULT hr = S_OK;
  if (site) {
    ScopedComPtr<IWebBrowser2> web_browser2;
    web_browser2.QueryFrom(site);
    if (web_browser2) {
      hr = DispEventAdvise(web_browser2, &DIID_DWebBrowserEvents2);
      DCHECK(SUCCEEDED(hr)) << "DispEventAdvise failed. Error: " << hr;
    }

    if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
      ScopedComPtr<IBrowserService> browser_service;
      hr = DoQueryService(SID_SShellBrowser, site, browser_service.Receive());
      DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed."
          << " Site: " << site << " Error: " << hr;
      if (browser_service) {
        g_patch_helper.PatchBrowserService(browser_service);
        DCHECK(SUCCEEDED(hr)) << "vtable_patch::PatchInterfaceMethods failed."
            << " Site: " << site << " Error: " << hr;
      }
    }
    // Save away our BHO instance in TLS which enables it to be referenced by
    // our active document/activex instances to query referrer and other
    // information for a URL.
    AddRef();
    RegisterThreadInstance();
  } else {
    UnregisterThreadInstance();
    Release();
  }

  return IObjectWithSiteImpl<Bho>::SetSite(site);
}

STDMETHODIMP Bho::BeforeNavigate2(IDispatch* dispatch, VARIANT* url,
    VARIANT* flags, VARIANT* target_frame_name, VARIANT* post_data,
    VARIANT* headers, VARIANT_BOOL* cancel) {
  if (!url || url->vt != VT_BSTR || url->bstrVal == NULL) {
    DLOG(WARNING) << "Invalid URL passed in";
    return S_OK;
  }

  ScopedComPtr<IWebBrowser2> web_browser2;
  if (dispatch)
    web_browser2.QueryFrom(dispatch);

  if (!web_browser2) {
    NOTREACHED() << "Can't find WebBrowser2 with given dispatch";
    return S_OK;
  }

  DLOG(INFO) << "BeforeNavigate2: " << url->bstrVal;
  ScopedComPtr<IBrowserService> browser_service;
  DoQueryService(SID_SShellBrowser, web_browser2, browser_service.Receive());
  if (!browser_service || !CheckForCFNavigation(browser_service, false)) {
    referrer_.clear();
  }

  VARIANT_BOOL is_top_level = VARIANT_FALSE;
  web_browser2->get_TopLevelContainer(&is_top_level);
  if (is_top_level) {
    set_url(url->bstrVal);
    ProcessOptInUrls(web_browser2, url->bstrVal);
  }

  return S_OK;
}

STDMETHODIMP_(void) Bho::NavigateComplete2(IDispatch* dispatch, VARIANT* url) {
  DLOG(INFO) << __FUNCTION__;
}

namespace {

// See comments in Bho::OnHttpEquiv for details.
void ClearDocumentContents(IUnknown* browser) {
  ScopedComPtr<IWebBrowser2> web_browser2;
  if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
                               web_browser2.Receive()))) {
    ScopedComPtr<IDispatch> doc_disp;
    web_browser2->get_Document(doc_disp.Receive());
    ScopedComPtr<IHTMLDocument2> doc;
    if (doc_disp && SUCCEEDED(doc.QueryFrom(doc_disp))) {
      SAFEARRAY* sa = ::SafeArrayCreateVector(VT_UI1, 0, 0);
      doc->write(sa);
      ::SafeArrayDestroy(sa);
    }
  }
}

// Returns true if the currently loaded document in the browser has
// any embedded items such as a frame or an iframe.
bool DocumentHasEmbeddedItems(IUnknown* browser) {
  bool has_embedded_items = false;

  ScopedComPtr<IWebBrowser2> web_browser2;
  ScopedComPtr<IDispatch> document;
  if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
                               web_browser2.Receive())) &&
      SUCCEEDED(web_browser2->get_Document(document.Receive()))) {
    ScopedComPtr<IOleContainer> container;
    if (SUCCEEDED(container.QueryFrom(document))) {
      ScopedComPtr<IEnumUnknown> enumerator;
      container->EnumObjects(OLECONTF_EMBEDDINGS, enumerator.Receive());
      if (enumerator) {
        ScopedComPtr<IUnknown> unk;
        DWORD fetched = 0;
        while (!has_embedded_items &&
               SUCCEEDED(enumerator->Next(1, unk.Receive(), &fetched))
               && fetched) {
          // If a top level document has embedded iframes then the theory is
          // that first the top level document finishes loading and then the
          // iframes load. We should only treat an embedded element as an
          // iframe if it supports the IWebBrowser interface.
          ScopedComPtr<IWebBrowser2> embedded_web_browser2;
          if (SUCCEEDED(embedded_web_browser2.QueryFrom(unk))) {
            // If we initiate a top level navigation then at times MSHTML
            // creates a temporary IWebBrowser2 interface which basically shows
            // up as a temporary iframe in the parent document. It is not clear
            // as to how we can detect this. I tried the usual stuff like
            // getting to the parent IHTMLWindow2 interface. They all end up
            // pointing to dummy tear off interfaces owned by MSHTML.
            // As a temporary workaround, we found that the location url in
            // this case is about:blank. We now check for the same and don't
            // treat it as an iframe. This should be fine in most cases as we
            // hit this code only when the actual page has a meta tag. However
            // this would break for cases like the initial src url for an
            // iframe pointing to about:blank and the page then writing to it
            // via document.write.
            // TODO(ananta)
            // Revisit this and come up with a better approach.
            ScopedBstr location_url;
            embedded_web_browser2->get_LocationURL(location_url.Receive());

            std::wstring location_url_string;
            location_url_string.assign(location_url, location_url.Length());

            if (!LowerCaseEqualsASCII(location_url_string, "about:blank")) {
              has_embedded_items = true;
            }
          }

          fetched = 0;
          unk.Release();
        }
      }
    }
  }

  return has_embedded_items;
}

}  // end namespace

HRESULT Bho::OnHttpEquiv(IBrowserService_OnHttpEquiv_Fn original_httpequiv,
    IBrowserService* browser, IShellView* shell_view, BOOL done,
    VARIANT* in_arg, VARIANT* out_arg) {
  DLOG(INFO) << __FUNCTION__ << " done:" << done;

  // OnHttpEquiv with 'done' set to TRUE is called for all pages.
  // 0 or more calls with done set to FALSE are made.
  // When done is FALSE, the current moniker may not represent the page
  // being navigated to so we always have to wait for done to be TRUE
  // before re-initiating the navigation.

  if (!done && in_arg && VT_BSTR == V_VT(in_arg)) {
    if (StrStrI(V_BSTR(in_arg), kChromeContentPrefix)) {
      // OnHttpEquiv is invoked for meta tags within sub frames as well.
      // We want to switch renderers only for the top level frame.
      // The theory here is that if there are any existing embedded items
      // (frames or iframes) in the current document, then the http-equiv
      // notification is coming from those and not the top level document.
      // The embedded items should only be created once the top level
      // doc has been created.
      if (!DocumentHasEmbeddedItems(browser)) {
        NavigationManager* mgr = NavigationManager::GetThreadInstance();
        DCHECK(mgr);
        DLOG(INFO) << "Found tag in page. Marking browser." <<
            StringPrintf(" tid=0x%08X", ::GetCurrentThreadId());
        if (mgr) {
          // TODO(tommi): See if we can't figure out a cleaner way to avoid
          // this.  For some documents we can hit a problem here.  When we
          // attempt to navigate the document again in CF, mshtml can "complete"
          // the current navigation (if all data is available) and fire off
          // script events such as onload and even render the page.
          // This will happen inside NavigateBrowserToMoniker below.
          // To work around this, we clear the contents of the document before
          // opening it up in CF.
          ClearDocumentContents(browser);
          mgr->NavigateToCurrentUrlInCF(browser);
        }
      }
    }
  } else if (done) {
    if (!CheckForCFNavigation(browser, false)) {
      DLOG(INFO) << "Releasing cached data.";
      NavigationManager* mgr = NavigationManager::GetThreadInstance();
      if (mgr)
        mgr->ReleaseRequestData();
    } else {
      DLOG(INFO) << __FUNCTION__
          << " not freeing request data - browser tagged";
    }
  }

  return original_httpequiv(browser, shell_view, done, in_arg, out_arg);
}

// static
void Bho::ProcessOptInUrls(IWebBrowser2* browser, BSTR url) {
  if (!browser || !url) {
    NOTREACHED();
    return;
  }

#ifndef NDEBUG
  // This check must already have been made.
  VARIANT_BOOL is_top_level = VARIANT_FALSE;
  browser->get_TopLevelContainer(&is_top_level);
  DCHECK(is_top_level);
#endif

  std::wstring current_url(url, SysStringLen(url));
  if (IsValidUrlScheme(current_url, false)) {
    bool cf_protocol = StartsWith(current_url, kChromeProtocolPrefix, false);
    if (!cf_protocol && IsOptInUrl(current_url.c_str())) {
      DLOG(INFO) << "Opt-in URL. Switching to cf.";
      ScopedComPtr<IBrowserService> browser_service;
      DoQueryService(SID_SShellBrowser, browser, browser_service.Receive());
      DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed.";
      MarkBrowserOnThreadForCFNavigation(browser_service);
    }
  }
}

namespace {
// Utility function that prevents the current module from ever being unloaded.
void PinModule() {
  FilePath module_path;
  if (PathService::Get(base::FILE_MODULE, &module_path)) {
    HMODULE unused;
    if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_PIN,
                           module_path.value().c_str(), &unused)) {
      NOTREACHED() << "Failed to pin module " << module_path.value().c_str()
                   << " , last error: " << GetLastError();
    }
  } else {
    NOTREACHED() << "Could not get module path.";
  }
}
}  // namespace

bool PatchHelper::InitializeAndPatchProtocolsIfNeeded() {
  bool ret = false;

  _pAtlModule->m_csStaticDataInitAndTypeInfo.Lock();

  if (state_ == UNKNOWN) {
    // If we're going to start patching things for reals, we'd better make sure
    // that we stick around for ever more:
    if (!IsUnpinnedMode())
      PinModule();

    HttpNegotiatePatch::Initialize();

    ProtocolPatchMethod patch_method =
        static_cast<ProtocolPatchMethod>(
            GetConfigInt(PATCH_METHOD_IBROWSER_AND_MONIKER, kPatchProtocols));

    if (patch_method == PATCH_METHOD_INET_PROTOCOL) {
      ProtocolSinkWrap::PatchProtocolHandlers();
      state_ = PATCH_PROTOCOL;
    } else {
      DCHECK(patch_method == PATCH_METHOD_IBROWSER ||
             patch_method == PATCH_METHOD_IBROWSER_AND_MONIKER);
      state_ = PATCH_IBROWSER;
      if (patch_method == PATCH_METHOD_IBROWSER_AND_MONIKER) {
        MonikerPatch::Initialize();
      }
    }
    ret = true;
  }

  _pAtlModule->m_csStaticDataInitAndTypeInfo.Unlock();

  return ret;
}

void PatchHelper::PatchBrowserService(IBrowserService* browser_service) {
  DCHECK(state_ == PATCH_IBROWSER);
  if (!IS_PATCHED(IBrowserService)) {
    vtable_patch::PatchInterfaceMethods(browser_service,
                                        IBrowserService_PatchInfo);
  }
}

void PatchHelper::UnpatchIfNeeded() {
  if (state_ == PATCH_PROTOCOL) {
    ProtocolSinkWrap::UnpatchProtocolHandlers();
  } else if (state_ == PATCH_IBROWSER) {
    vtable_patch::UnpatchInterfaceMethods(IBrowserService_PatchInfo);
    MonikerPatch::Uninitialize();
  }

  HttpNegotiatePatch::Uninitialize();

  state_ = UNKNOWN;
}

<commit_msg>Disabling the moniker patch in ChromeFrame as it incorrectly causes pages to switch to ChromeFrame, even when they don't specify the meta tag or the HTTP header indicating the same.<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 "chrome_frame/bho.h"

#include <shlguid.h>

#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "chrome_tab.h" // NOLINT
#include "chrome_frame/extra_system_apis.h"
#include "chrome_frame/http_negotiate.h"
#include "chrome_frame/protocol_sink_wrap.h"
#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"

static const int kIBrowserServiceOnHttpEquivIndex = 30;

PatchHelper g_patch_helper;

BEGIN_VTABLE_PATCHES(IBrowserService)
  VTABLE_PATCH_ENTRY(kIBrowserServiceOnHttpEquivIndex, Bho::OnHttpEquiv)
END_VTABLE_PATCHES()

_ATL_FUNC_INFO Bho::kBeforeNavigate2Info = {
  CC_STDCALL, VT_EMPTY, 7, {
    VT_DISPATCH,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_VARIANT | VT_BYREF,
    VT_BOOL | VT_BYREF
  }
};

_ATL_FUNC_INFO Bho::kNavigateComplete2Info = {
  CC_STDCALL, VT_EMPTY, 2, {
    VT_DISPATCH,
    VT_VARIANT | VT_BYREF
  }
};

Bho::Bho() {
}

HRESULT Bho::FinalConstruct() {
  return S_OK;
}

void Bho::FinalRelease() {
}

STDMETHODIMP Bho::SetSite(IUnknown* site) {
  HRESULT hr = S_OK;
  if (site) {
    ScopedComPtr<IWebBrowser2> web_browser2;
    web_browser2.QueryFrom(site);
    if (web_browser2) {
      hr = DispEventAdvise(web_browser2, &DIID_DWebBrowserEvents2);
      DCHECK(SUCCEEDED(hr)) << "DispEventAdvise failed. Error: " << hr;
    }

    if (g_patch_helper.state() == PatchHelper::PATCH_IBROWSER) {
      ScopedComPtr<IBrowserService> browser_service;
      hr = DoQueryService(SID_SShellBrowser, site, browser_service.Receive());
      DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed."
          << " Site: " << site << " Error: " << hr;
      if (browser_service) {
        g_patch_helper.PatchBrowserService(browser_service);
        DCHECK(SUCCEEDED(hr)) << "vtable_patch::PatchInterfaceMethods failed."
            << " Site: " << site << " Error: " << hr;
      }
    }
    // Save away our BHO instance in TLS which enables it to be referenced by
    // our active document/activex instances to query referrer and other
    // information for a URL.
    AddRef();
    RegisterThreadInstance();
  } else {
    UnregisterThreadInstance();
    Release();
  }

  return IObjectWithSiteImpl<Bho>::SetSite(site);
}

STDMETHODIMP Bho::BeforeNavigate2(IDispatch* dispatch, VARIANT* url,
    VARIANT* flags, VARIANT* target_frame_name, VARIANT* post_data,
    VARIANT* headers, VARIANT_BOOL* cancel) {
  if (!url || url->vt != VT_BSTR || url->bstrVal == NULL) {
    DLOG(WARNING) << "Invalid URL passed in";
    return S_OK;
  }

  ScopedComPtr<IWebBrowser2> web_browser2;
  if (dispatch)
    web_browser2.QueryFrom(dispatch);

  if (!web_browser2) {
    NOTREACHED() << "Can't find WebBrowser2 with given dispatch";
    return S_OK;
  }

  DLOG(INFO) << "BeforeNavigate2: " << url->bstrVal;
  ScopedComPtr<IBrowserService> browser_service;
  DoQueryService(SID_SShellBrowser, web_browser2, browser_service.Receive());
  if (!browser_service || !CheckForCFNavigation(browser_service, false)) {
    referrer_.clear();
  }

  VARIANT_BOOL is_top_level = VARIANT_FALSE;
  web_browser2->get_TopLevelContainer(&is_top_level);
  if (is_top_level) {
    set_url(url->bstrVal);
    ProcessOptInUrls(web_browser2, url->bstrVal);
  }

  return S_OK;
}

STDMETHODIMP_(void) Bho::NavigateComplete2(IDispatch* dispatch, VARIANT* url) {
  DLOG(INFO) << __FUNCTION__;
}

namespace {

// See comments in Bho::OnHttpEquiv for details.
void ClearDocumentContents(IUnknown* browser) {
  ScopedComPtr<IWebBrowser2> web_browser2;
  if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
                               web_browser2.Receive()))) {
    ScopedComPtr<IDispatch> doc_disp;
    web_browser2->get_Document(doc_disp.Receive());
    ScopedComPtr<IHTMLDocument2> doc;
    if (doc_disp && SUCCEEDED(doc.QueryFrom(doc_disp))) {
      SAFEARRAY* sa = ::SafeArrayCreateVector(VT_UI1, 0, 0);
      doc->write(sa);
      ::SafeArrayDestroy(sa);
    }
  }
}

// Returns true if the currently loaded document in the browser has
// any embedded items such as a frame or an iframe.
bool DocumentHasEmbeddedItems(IUnknown* browser) {
  bool has_embedded_items = false;

  ScopedComPtr<IWebBrowser2> web_browser2;
  ScopedComPtr<IDispatch> document;
  if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp, browser,
                               web_browser2.Receive())) &&
      SUCCEEDED(web_browser2->get_Document(document.Receive()))) {
    ScopedComPtr<IOleContainer> container;
    if (SUCCEEDED(container.QueryFrom(document))) {
      ScopedComPtr<IEnumUnknown> enumerator;
      container->EnumObjects(OLECONTF_EMBEDDINGS, enumerator.Receive());
      if (enumerator) {
        ScopedComPtr<IUnknown> unk;
        DWORD fetched = 0;
        while (!has_embedded_items &&
               SUCCEEDED(enumerator->Next(1, unk.Receive(), &fetched))
               && fetched) {
          // If a top level document has embedded iframes then the theory is
          // that first the top level document finishes loading and then the
          // iframes load. We should only treat an embedded element as an
          // iframe if it supports the IWebBrowser interface.
          ScopedComPtr<IWebBrowser2> embedded_web_browser2;
          if (SUCCEEDED(embedded_web_browser2.QueryFrom(unk))) {
            // If we initiate a top level navigation then at times MSHTML
            // creates a temporary IWebBrowser2 interface which basically shows
            // up as a temporary iframe in the parent document. It is not clear
            // as to how we can detect this. I tried the usual stuff like
            // getting to the parent IHTMLWindow2 interface. They all end up
            // pointing to dummy tear off interfaces owned by MSHTML.
            // As a temporary workaround, we found that the location url in
            // this case is about:blank. We now check for the same and don't
            // treat it as an iframe. This should be fine in most cases as we
            // hit this code only when the actual page has a meta tag. However
            // this would break for cases like the initial src url for an
            // iframe pointing to about:blank and the page then writing to it
            // via document.write.
            // TODO(ananta)
            // Revisit this and come up with a better approach.
            ScopedBstr location_url;
            embedded_web_browser2->get_LocationURL(location_url.Receive());

            std::wstring location_url_string;
            location_url_string.assign(location_url, location_url.Length());

            if (!LowerCaseEqualsASCII(location_url_string, "about:blank")) {
              has_embedded_items = true;
            }
          }

          fetched = 0;
          unk.Release();
        }
      }
    }
  }

  return has_embedded_items;
}

}  // end namespace

HRESULT Bho::OnHttpEquiv(IBrowserService_OnHttpEquiv_Fn original_httpequiv,
    IBrowserService* browser, IShellView* shell_view, BOOL done,
    VARIANT* in_arg, VARIANT* out_arg) {
  DLOG(INFO) << __FUNCTION__ << " done:" << done;

  // OnHttpEquiv with 'done' set to TRUE is called for all pages.
  // 0 or more calls with done set to FALSE are made.
  // When done is FALSE, the current moniker may not represent the page
  // being navigated to so we always have to wait for done to be TRUE
  // before re-initiating the navigation.

  if (!done && in_arg && VT_BSTR == V_VT(in_arg)) {
    if (StrStrI(V_BSTR(in_arg), kChromeContentPrefix)) {
      // OnHttpEquiv is invoked for meta tags within sub frames as well.
      // We want to switch renderers only for the top level frame.
      // The theory here is that if there are any existing embedded items
      // (frames or iframes) in the current document, then the http-equiv
      // notification is coming from those and not the top level document.
      // The embedded items should only be created once the top level
      // doc has been created.
      if (!DocumentHasEmbeddedItems(browser)) {
        NavigationManager* mgr = NavigationManager::GetThreadInstance();
        DCHECK(mgr);
        DLOG(INFO) << "Found tag in page. Marking browser." <<
            StringPrintf(" tid=0x%08X", ::GetCurrentThreadId());
        if (mgr) {
          // TODO(tommi): See if we can't figure out a cleaner way to avoid
          // this.  For some documents we can hit a problem here.  When we
          // attempt to navigate the document again in CF, mshtml can "complete"
          // the current navigation (if all data is available) and fire off
          // script events such as onload and even render the page.
          // This will happen inside NavigateBrowserToMoniker below.
          // To work around this, we clear the contents of the document before
          // opening it up in CF.
          ClearDocumentContents(browser);
          mgr->NavigateToCurrentUrlInCF(browser);
        }
      }
    }
  } else if (done) {
    if (!CheckForCFNavigation(browser, false)) {
      DLOG(INFO) << "Releasing cached data.";
      NavigationManager* mgr = NavigationManager::GetThreadInstance();
      if (mgr)
        mgr->ReleaseRequestData();
    } else {
      DLOG(INFO) << __FUNCTION__
          << " not freeing request data - browser tagged";
    }
  }

  return original_httpequiv(browser, shell_view, done, in_arg, out_arg);
}

// static
void Bho::ProcessOptInUrls(IWebBrowser2* browser, BSTR url) {
  if (!browser || !url) {
    NOTREACHED();
    return;
  }

#ifndef NDEBUG
  // This check must already have been made.
  VARIANT_BOOL is_top_level = VARIANT_FALSE;
  browser->get_TopLevelContainer(&is_top_level);
  DCHECK(is_top_level);
#endif

  std::wstring current_url(url, SysStringLen(url));
  if (IsValidUrlScheme(current_url, false)) {
    bool cf_protocol = StartsWith(current_url, kChromeProtocolPrefix, false);
    if (!cf_protocol && IsOptInUrl(current_url.c_str())) {
      DLOG(INFO) << "Opt-in URL. Switching to cf.";
      ScopedComPtr<IBrowserService> browser_service;
      DoQueryService(SID_SShellBrowser, browser, browser_service.Receive());
      DCHECK(browser_service) << "DoQueryService - SID_SShellBrowser failed.";
      MarkBrowserOnThreadForCFNavigation(browser_service);
    }
  }
}

namespace {
// Utility function that prevents the current module from ever being unloaded.
void PinModule() {
  FilePath module_path;
  if (PathService::Get(base::FILE_MODULE, &module_path)) {
    HMODULE unused;
    if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_PIN,
                           module_path.value().c_str(), &unused)) {
      NOTREACHED() << "Failed to pin module " << module_path.value().c_str()
                   << " , last error: " << GetLastError();
    }
  } else {
    NOTREACHED() << "Could not get module path.";
  }
}
}  // namespace

bool PatchHelper::InitializeAndPatchProtocolsIfNeeded() {
  bool ret = false;

  _pAtlModule->m_csStaticDataInitAndTypeInfo.Lock();

  if (state_ == UNKNOWN) {
    // If we're going to start patching things for reals, we'd better make sure
    // that we stick around for ever more:
    if (!IsUnpinnedMode())
      PinModule();

    HttpNegotiatePatch::Initialize();

    ProtocolPatchMethod patch_method =
        static_cast<ProtocolPatchMethod>(
            GetConfigInt(PATCH_METHOD_IBROWSER, kPatchProtocols));

    if (patch_method == PATCH_METHOD_INET_PROTOCOL) {
      ProtocolSinkWrap::PatchProtocolHandlers();
      state_ = PATCH_PROTOCOL;
    } else {
      DCHECK(patch_method == PATCH_METHOD_IBROWSER ||
             patch_method == PATCH_METHOD_IBROWSER_AND_MONIKER);
      state_ = PATCH_IBROWSER;
      if (patch_method == PATCH_METHOD_IBROWSER_AND_MONIKER) {
        MonikerPatch::Initialize();
      }
    }
    ret = true;
  }

  _pAtlModule->m_csStaticDataInitAndTypeInfo.Unlock();

  return ret;
}

void PatchHelper::PatchBrowserService(IBrowserService* browser_service) {
  DCHECK(state_ == PATCH_IBROWSER);
  if (!IS_PATCHED(IBrowserService)) {
    vtable_patch::PatchInterfaceMethods(browser_service,
                                        IBrowserService_PatchInfo);
  }
}

void PatchHelper::UnpatchIfNeeded() {
  if (state_ == PATCH_PROTOCOL) {
    ProtocolSinkWrap::UnpatchProtocolHandlers();
  } else if (state_ == PATCH_IBROWSER) {
    vtable_patch::UnpatchInterfaceMethods(IBrowserService_PatchInfo);
    MonikerPatch::Uninitialize();
  }

  HttpNegotiatePatch::Uninitialize();

  state_ = UNKNOWN;
}

<|endoftext|>


<commit_before>/*
 Copyright (c) 2014 Anon authors, see AUTHORS file.

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

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

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

#include "time_utils.h"
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <vector>
#include <sstream>
#include <string.h>

extern "C" int main(int argc, char** argv)
{
  if (argc != 3)
  {
    printf("usage: big_client <ip> <port>\n");
    return 1;
  }

  const char* ip = argv[1];
  const char* port = argv[2];
  printf("running big_client against \"%s\", port %s\n", ip, port);

  const int num_sockets = 200;
  const int num_sends = 5000;

  // look ip the addr for ip/port
  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
  hints.ai_socktype = SOCK_STREAM;

  struct addrinfo* result;
  if (getaddrinfo(ip,port,&hints,&result)!=0) {
    printf("getaddrinfo failed with errno: %d\n", errno);
    return 1;
  }

  // loop through and get all the sockets connected
  std::vector<int> conns;
  for (int i=0; i<num_sockets; i++) {
    int fd = socket(result->ai_addr->sa_family, SOCK_STREAM, 0);
    if (fd == -1) {
      printf("socket failed with errno: %d\n", errno);
      return 1;
    }
    if (connect(fd, result->ai_addr, result->ai_addrlen) != 0) {
      printf("connect failed with errno: %d\n", errno);
      return 1;
    }
    conns.push_back(fd);
  }
  freeaddrinfo(result);

  // construct the GET request we are going to send
  // (it needs to have the Host attribute set right)
  std::ostringstream oss;
  oss << "GET /?a=10&b=20 HTTP/1.1\r\n";
  oss << "Host: " << ip << ":" << port << "\r\n";
  oss << "User-Agent: big_client test agent\r\n";
  oss << "Accept: text/html\r\n";
  oss << "Accept-Language: en-US,en;q-0.5\r\n";
  oss << "Accept-Encoding: gzip, deflate\r\n";
  oss << "Connection: keep-alive\r\n";
  oss << "\r\n\r\n";
  std::string st = oss.str();
  const char* buf = st.c_str();
  size_t len = st.length();

  auto start_time = cur_time();

  for (int send_count=0; send_count<num_sends; send_count++) {

    // send the request to each one
    for (int sock_count=0; sock_count<num_sockets; sock_count++) {
      size_t tot_bytes = 0;
      while (tot_bytes<len) {
        auto bytes = write(conns[sock_count],&buf[tot_bytes],len-tot_bytes);
        if (bytes < 0) {
          printf("write failed, errno: %d\n", errno);
          return 1;
        }
        tot_bytes += bytes;
      }
    }

    // read the response from each one
    for (int sock_count=0; sock_count<num_sockets; sock_count++) {
      char    reply[4096];
      size_t  bytes_read = 0;
      while (true) {
        auto bytes = read(conns[sock_count],&reply[bytes_read],sizeof(reply)-bytes_read);
        if (bytes < 0) {
          printf("read failed, errno: %d\n", errno);
          return 1;
        }
        bytes_read += bytes;
        if (bytes_read == sizeof(reply)) {
          printf("reply too big!\n");
          return 1;
        }
        if (bytes_read > 4 && memcmp(&reply[bytes_read-4],"\r\n\r\n",4) == 0)
          break;
      }
    }

  }

  auto tot_time = cur_time() - start_time;
  std::ostringstream msg;
  msg << "tested " << num_sockets * num_sends << " http api calls in " << tot_time << " seconds\n";
  msg << "using " << num_sockets << " \"simutaneous\" sockets/clients, each making " << num_sends << " api calls\n";
  msg << num_sockets * num_sends / to_seconds(tot_time) << " api calls per second\n";
  printf("%s", msg.str().c_str());

  for (int i=0; i<num_sockets; i++)
    close(conns[i]);

  return 0;
}

<commit_msg>changing testing constant<commit_after>/*
 Copyright (c) 2014 Anon authors, see AUTHORS file.

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

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

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

#include "time_utils.h"
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <vector>
#include <sstream>
#include <string.h>

extern "C" int main(int argc, char** argv)
{
  if (argc != 3)
  {
    printf("usage: big_client <ip> <port>\n");
    return 1;
  }

  const char* ip = argv[1];
  const char* port = argv[2];
  printf("running big_client against \"%s\", port %s\n", ip, port);

  const int num_sockets = 400;
  const int num_sends = 2000;

  // look ip the addr for ip/port
  struct addrinfo hints;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
  hints.ai_socktype = SOCK_STREAM;

  struct addrinfo* result;
  if (getaddrinfo(ip,port,&hints,&result)!=0) {
    printf("getaddrinfo failed with errno: %d\n", errno);
    return 1;
  }

  // loop through and get all the sockets connected
  std::vector<int> conns;
  for (int i=0; i<num_sockets; i++) {
    int fd = socket(result->ai_addr->sa_family, SOCK_STREAM, 0);
    if (fd == -1) {
      printf("socket failed with errno: %d\n", errno);
      return 1;
    }
    if (connect(fd, result->ai_addr, result->ai_addrlen) != 0) {
      printf("connect failed with errno: %d\n", errno);
      return 1;
    }
    conns.push_back(fd);
  }
  freeaddrinfo(result);

  // construct the GET request we are going to send
  // (it needs to have the Host attribute set right)
  std::ostringstream oss;
  oss << "GET /?a=10&b=20 HTTP/1.1\r\n";
  oss << "Host: " << ip << ":" << port << "\r\n";
  oss << "User-Agent: big_client test agent\r\n";
  oss << "Accept: text/html\r\n";
  oss << "Accept-Language: en-US,en;q-0.5\r\n";
  oss << "Accept-Encoding: gzip, deflate\r\n";
  oss << "Connection: keep-alive\r\n";
  oss << "\r\n\r\n";
  std::string st = oss.str();
  const char* buf = st.c_str();
  size_t len = st.length();

  auto start_time = cur_time();

  for (int send_count=0; send_count<num_sends; send_count++) {

    // send the request to each one
    for (int sock_count=0; sock_count<num_sockets; sock_count++) {
      size_t tot_bytes = 0;
      while (tot_bytes<len) {
        auto bytes = write(conns[sock_count],&buf[tot_bytes],len-tot_bytes);
        if (bytes < 0) {
          printf("write failed, errno: %d\n", errno);
          return 1;
        }
        tot_bytes += bytes;
      }
    }

    // read the response from each one
    for (int sock_count=0; sock_count<num_sockets; sock_count++) {
      char    reply[4096];
      size_t  bytes_read = 0;
      while (true) {
        auto bytes = read(conns[sock_count],&reply[bytes_read],sizeof(reply)-bytes_read);
        if (bytes < 0) {
          printf("read failed, errno: %d\n", errno);
          return 1;
        }
        bytes_read += bytes;
        if (bytes_read == sizeof(reply)) {
          printf("reply too big!\n");
          return 1;
        }
        if (bytes_read > 4 && memcmp(&reply[bytes_read-4],"\r\n\r\n",4) == 0)
          break;
      }
    }

  }

  auto tot_time = cur_time() - start_time;
  std::ostringstream msg;
  msg << "tested " << num_sockets * num_sends << " http api calls in " << tot_time << " seconds\n";
  msg << "using " << num_sockets << " \"simutaneous\" sockets/clients, each making " << num_sends << " api calls\n";
  msg << num_sockets * num_sends / to_seconds(tot_time) << " api calls per second\n";
  printf("%s", msg.str().c_str());

  for (int i=0; i<num_sockets; i++)
    close(conns[i]);

  return 0;
}

<|endoftext|>


<commit_before>#include "amatrix.h"
#include "checks.h"

std::size_t TestMatrixScaleAndAdd(std::size_t TSize1, std::size_t TSize2) {
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> c_matrix(TSize1, TSize2);
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;
    double scale_factor = 0.25;

    b_matrix = a_matrix;
    c_matrix = scale_factor * a_matrix + b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(c_matrix(i, j), (1 + scale_factor) * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

std::size_t TestMatrixScaleAndAddEqual(std::size_t TSize1, std::size_t TSize2) {
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> c_matrix(TSize1, TSize2);
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;
    double scale_factor = 0.25;

    b_matrix = a_matrix;
    a_matrix += scale_factor * b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(a_matrix(i, j), (1 + scale_factor) * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;
	number_of_failed_tests += TestMatrixScaleAndAdd(1,1);

	number_of_failed_tests += TestMatrixScaleAndAdd(1,2);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,1);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,2);

	number_of_failed_tests += TestMatrixScaleAndAdd(3,1);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,2);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(1,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,3);

 	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,1);

	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,2);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,1);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,2);

	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,1);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,2);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,3);

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<commit_msg>Modifying the test to cover more complex cases<commit_after>#include "amatrix.h"
#include "checks.h"

std::size_t TestMatrixScaleAndAdd(std::size_t TSize1, std::size_t TSize2) {
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> c_matrix(TSize1, TSize2);
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;
    double scale_factor = 0.25;

    b_matrix = a_matrix.transpose();
    c_matrix = scale_factor * a_matrix + b_matrix.transpose();

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(c_matrix(i, j), (1 + scale_factor) * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

std::size_t TestMatrixScaleAndAddEqual(std::size_t TSize1, std::size_t TSize2) {
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> a_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> b_matrix(TSize1, TSize2);
    AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic> c_matrix(TSize1, TSize2);
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;
    double scale_factor = 0.25;

    b_matrix = a_matrix;
    a_matrix += scale_factor * b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(a_matrix(i, j), (1 + scale_factor) * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;
	number_of_failed_tests += TestMatrixScaleAndAdd(1,1);

	number_of_failed_tests += TestMatrixScaleAndAdd(1,2);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,1);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,2);

	number_of_failed_tests += TestMatrixScaleAndAdd(3,1);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,2);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(1,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(2,3);
	number_of_failed_tests += TestMatrixScaleAndAdd(3,3);

 	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,1);

	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,2);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,1);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,2);

	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,1);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,2);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(1,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(2,3);
	number_of_failed_tests += TestMatrixScaleAndAddEqual(3,3);

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<|endoftext|>


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

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "vtkStreamingContourRepresentation.h"

#include "vtkAlgorithmOutput.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkGeometryRepresentation.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkPVLODActor.h"
#include "vtkPVRenderView.h"
#include "vtkPVStreamingMacros.h"
#include "vtkPVTrivialProducer.h"
#include "vtkRenderer.h"
#include "vtkStreamingWorker.h"

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

vtkStandardNewMacro(vtkStreamingContourRepresentation);
//----------------------------------------------------------------------------
vtkStreamingContourRepresentation::vtkStreamingContourRepresentation()
{
  this->ContourValue = 90;
  this->StreamingCapablePipeline = false;
  this->InStreamingUpdate = false;

  this->Worker = vtkSmartPointer<vtkStreamingWorker>::New();
  this->Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();

  this->Actor = vtkSmartPointer<vtkPVLODActor>::New();
  this->Actor->SetMapper(this->Mapper);
  this->Actor->GetProperty()->SetRepresentationToSurface();
  this->Actor->GetProperty()->SetAmbient(1.0);
  this->Actor->GetProperty()->SetDiffuse(0.0);
  this->Actor->GetProperty()->SetSpecular(0.0);
  this->Actor->SetPickable(0);
}

//----------------------------------------------------------------------------
vtkStreamingContourRepresentation::~vtkStreamingContourRepresentation()
{
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetVisibility(bool val)
{
  this->Actor->SetVisibility(val);
  this->Superclass::SetVisibility(val);
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetOpacity(double val)
{
  this->Actor->GetProperty()->SetOpacity(val);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::ProcessViewRequest(
  vtkInformationRequestKey* request_type, vtkInformation* inInfo, vtkInformation* outInfo)
{
  // always forward to superclass first. Superclass returns 0 if the
  // representation is not visible (among other things). In which case there's
  // nothing to do.
  if (!this->Superclass::ProcessViewRequest(request_type, inInfo, outInfo))
    {
    return 0;
    }

  if (request_type == vtkPVView::REQUEST_UPDATE())
    {
    // Standard representation stuff, first.
    // 1. Provide the data being rendered.
    vtkPVRenderView::SetPiece(inInfo, this, this->ProcessedData);

    // 2. Provide the bounds.
    double bounds[6];
    this->DataBounds.GetBounds(bounds);

    // Just let the view know of out data bounds.
    vtkPVRenderView::SetGeometryBounds(inInfo, bounds);

    // The only thing extra we need to do here is that we need to let the view
    // know that this representation is streaming capable (or not).
    vtkPVRenderView::SetStreamable(inInfo, this, this->GetStreamingCapablePipeline());
    }
  else if (request_type == vtkPVRenderView::REQUEST_STREAMING_UPDATE())
    {
    if (this->GetStreamingCapablePipeline())
      {
      // This is a streaming update request, request next piece.
      double view_planes[24];
      inInfo->Get(vtkPVRenderView::VIEW_PLANES(), view_planes);
      if (this->StreamingUpdate(view_planes))
        {
        // since we indeed "had" a next piece to produce, give it to the view
        // so it can deliver it to the rendering nodes.
        vtkPVRenderView::SetNextStreamedPiece(
          inInfo, this, this->ProcessedPiece);
        }
      }
    }
  else if (request_type == vtkPVView::REQUEST_RENDER())
    {
    if (this->RenderedData == NULL)
      {
      vtkStreamingStatusMacro(<< this << ": cloning delivered data.");
      vtkAlgorithmOutput* producerPort = vtkPVRenderView::GetPieceProducer(inInfo, this);
      vtkAlgorithm* producer = producerPort->GetProducer();

      this->RenderedData =
        producer->GetOutputDataObject(producerPort->GetIndex());
      this->Mapper->SetInputDataObject(this->RenderedData);
      }
    }

  else if (request_type == vtkPVRenderView::REQUEST_PROCESS_STREAMED_PIECE())
    {
    assert (this->RenderedData != NULL);
    vtkStreamingStatusMacro( << this << ": received new piece.");

    this->RenderedData = this->Worker->GetFinishedPieces();
    this->DataBounds.SetBounds(this->RenderedData->GetBounds());
    this->Mapper->SetInputDataObject(this->RenderedData);
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestInformation(vtkInformation *rqst,
    vtkInformationVector **inputVector,
    vtkInformationVector *outputVector)
{
  // Determine if the input is streaming capable. Unlike most streaming
  // representations we don't care that our input isn't a multi-block. Instead
  // all we care about is that the view has streaming enabled. We can ignore
  // the multi-block requirements since we do our own subdivision.

  this->StreamingCapablePipeline = false;
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
    if (vtkPVView::GetEnableStreaming())
      {
      this->StreamingCapablePipeline = true;
      }
    }

  vtkStreamingStatusMacro(
    << this << ": streaming capable input pipeline? "
    << (this->StreamingCapablePipeline? "yes" : "no"));
  return this->Superclass::RequestInformation(rqst, inputVector, outputVector);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestUpdateExtent(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  //we are doing our own block delivery so we have no need to
  //ask the input to give us more blocks
  return this->Superclass::RequestUpdateExtent(request,
                                               inputVector,
                                               outputVector);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestData(vtkInformation *rqst,
  vtkInformationVector **inputVector, vtkInformationVector *outputVector)
{
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
    if (this->GetStreamingCapablePipeline() && !this->GetInStreamingUpdate())
      {
      // Since the representation re-executed, it means that the input changed
      // and we should initialize our streaming.
      vtkImageData *inputImage = vtkImageData::GetData(inputVector[0],0);
      vtkDataArray *inScalars = this->GetInputArrayToProcess(0,inputVector);

      this->Worker->StartContour(inputImage,inScalars,this->GetContourValue());
      }
    }

  this->ProcessedPiece = 0;
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    // Do the streaming independent "transformation" of the data here, in our
    // case, generate the polydata from the input.

    vtkImageData *input = vtkImageData::GetData(inputVector[0],0);
    if (!this->GetInStreamingUpdate())
      {
        this->ProcessedData = vtkSmartPointer<vtkImageData>::New();
        this->ProcessedData->ShallowCopy(input);

        this->DataBounds.SetBounds(input->GetBounds());
      }
    else
      {
      this->ProcessedPiece = input;
      }
    }
  else
    {
    // create an empty dataset. This is needed so that view knows what dataset
    // to expect from the other processes on this node.
    this->ProcessedData = vtkSmartPointer<vtkImageData>::New();
    this->DataBounds.Reset();
    }

  if (!this->GetInStreamingUpdate())
    {
    this->RenderedData = 0;

    // provide the mapper with an empty input. This is needed only because
    // mappers die when input is NULL, currently.
    vtkNew<vtkPolyData> tmp;
    this->Mapper->SetInputDataObject(tmp.GetPointer());
    }

  return this->Superclass::RequestData(rqst, inputVector, outputVector);
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::StreamingUpdate(const double view_planes[24])
{
  assert(this->InStreamingUpdate == false);

  if (this->Worker->IsFinished())
    {
    return false;
    }

  // We've determined we need to request something. Do it.
  this->InStreamingUpdate = true;
  vtkStreamingStatusMacro(<< this << ": doing streaming-update.");

  // This ensure that the representation re-executes.
  this->MarkModified();

  // Execute the pipeline.
  this->Update();

  this->InStreamingUpdate = false;
  return true;
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::FillInputPortInformation(
  int vtkNotUsed(port), vtkInformation* info)
{

  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData");

  // Saying INPUT_IS_OPTIONAL() is essential, since representations don't have
  // any inputs on client-side (in client-server, client-render-server mode) and
  // render-server-side (in client-render-server mode).
  info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);

  return 1;
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::AddToView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
    {
    rview->GetRenderer()->AddActor(this->Actor);
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::RemoveFromView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
    {
    rview->GetRenderer()->RemoveActor(this->Actor);
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "StreamingCapablePipeline: " << this->StreamingCapablePipeline << endl;
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetInputArrayToProcess(
  int idx, int port, int connection, int fieldAssociation, const char *name)
{
  this->Superclass::SetInputArrayToProcess(
    idx, port, connection, fieldAssociation, name);

  if (name && name[0])
    {
    this->Mapper->SetScalarVisibility(1);
    this->Mapper->SelectColorArray(name);
    this->Mapper->SetUseLookupTableScalarRange(1);
    }
  else
    {
    this->Mapper->SetScalarVisibility(0);
    this->Mapper->SelectColorArray(static_cast<const char*>(NULL));
    }

  switch (fieldAssociation)
    {
  case vtkDataObject::FIELD_ASSOCIATION_CELLS:
    this->Mapper->SetScalarMode(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA);
    break;

  case vtkDataObject::FIELD_ASSOCIATION_POINTS:
  default:
    this->Mapper->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA);
    break;
    }
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetLookupTable(vtkScalarsToColors* lut)
{
  this->Mapper->SetLookupTable(lut);
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetPointSize(double val)
{
  this->Actor->GetProperty()->SetPointSize(val);
}
<commit_msg>Fixed Rob's rendering issues - leave default lighting<commit_after>/******************************************************************************

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "vtkStreamingContourRepresentation.h"

#include "vtkAlgorithmOutput.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkGeometryRepresentation.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkPVLODActor.h"
#include "vtkPVRenderView.h"
#include "vtkPVStreamingMacros.h"
#include "vtkPVTrivialProducer.h"
#include "vtkRenderer.h"
#include "vtkStreamingWorker.h"

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

vtkStandardNewMacro(vtkStreamingContourRepresentation);
//----------------------------------------------------------------------------
vtkStreamingContourRepresentation::vtkStreamingContourRepresentation()
{
  this->ContourValue = 90;
  this->StreamingCapablePipeline = false;
  this->InStreamingUpdate = false;

  this->Worker = vtkSmartPointer<vtkStreamingWorker>::New();
  this->Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();

  this->Actor = vtkSmartPointer<vtkPVLODActor>::New();
  this->Actor->SetMapper(this->Mapper);
  this->Actor->GetProperty()->SetRepresentationToSurface();
  this->Actor->SetPickable(0);
}

//----------------------------------------------------------------------------
vtkStreamingContourRepresentation::~vtkStreamingContourRepresentation()
{
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetVisibility(bool val)
{
  this->Actor->SetVisibility(val);
  this->Superclass::SetVisibility(val);
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetOpacity(double val)
{
  this->Actor->GetProperty()->SetOpacity(val);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::ProcessViewRequest(
  vtkInformationRequestKey* request_type, vtkInformation* inInfo, vtkInformation* outInfo)
{
  // always forward to superclass first. Superclass returns 0 if the
  // representation is not visible (among other things). In which case there's
  // nothing to do.
  if (!this->Superclass::ProcessViewRequest(request_type, inInfo, outInfo))
    {
    return 0;
    }

  if (request_type == vtkPVView::REQUEST_UPDATE())
    {
    // Standard representation stuff, first.
    // 1. Provide the data being rendered.
    vtkPVRenderView::SetPiece(inInfo, this, this->ProcessedData);

    // 2. Provide the bounds.
    double bounds[6];
    this->DataBounds.GetBounds(bounds);

    // Just let the view know of out data bounds.
    vtkPVRenderView::SetGeometryBounds(inInfo, bounds);

    // The only thing extra we need to do here is that we need to let the view
    // know that this representation is streaming capable (or not).
    vtkPVRenderView::SetStreamable(inInfo, this, this->GetStreamingCapablePipeline());
    }
  else if (request_type == vtkPVRenderView::REQUEST_STREAMING_UPDATE())
    {
    if (this->GetStreamingCapablePipeline())
      {
      // This is a streaming update request, request next piece.
      double view_planes[24];
      inInfo->Get(vtkPVRenderView::VIEW_PLANES(), view_planes);
      if (this->StreamingUpdate(view_planes))
        {
        // since we indeed "had" a next piece to produce, give it to the view
        // so it can deliver it to the rendering nodes.
        vtkPVRenderView::SetNextStreamedPiece(
          inInfo, this, this->ProcessedPiece);
        }
      }
    }
  else if (request_type == vtkPVView::REQUEST_RENDER())
    {
    if (this->RenderedData == NULL)
      {
      vtkStreamingStatusMacro(<< this << ": cloning delivered data.");
      vtkAlgorithmOutput* producerPort = vtkPVRenderView::GetPieceProducer(inInfo, this);
      vtkAlgorithm* producer = producerPort->GetProducer();

      this->RenderedData =
        producer->GetOutputDataObject(producerPort->GetIndex());
      this->Mapper->SetInputDataObject(this->RenderedData);
      }
    }

  else if (request_type == vtkPVRenderView::REQUEST_PROCESS_STREAMED_PIECE())
    {
    assert (this->RenderedData != NULL);
    vtkStreamingStatusMacro( << this << ": received new piece.");

    this->RenderedData = this->Worker->GetFinishedPieces();
    this->DataBounds.SetBounds(this->RenderedData->GetBounds());
    this->Mapper->SetInputDataObject(this->RenderedData);
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestInformation(vtkInformation *rqst,
    vtkInformationVector **inputVector,
    vtkInformationVector *outputVector)
{
  // Determine if the input is streaming capable. Unlike most streaming
  // representations we don't care that our input isn't a multi-block. Instead
  // all we care about is that the view has streaming enabled. We can ignore
  // the multi-block requirements since we do our own subdivision.

  this->StreamingCapablePipeline = false;
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
    if (vtkPVView::GetEnableStreaming())
      {
      this->StreamingCapablePipeline = true;
      }
    }

  vtkStreamingStatusMacro(
    << this << ": streaming capable input pipeline? "
    << (this->StreamingCapablePipeline? "yes" : "no"));
  return this->Superclass::RequestInformation(rqst, inputVector, outputVector);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestUpdateExtent(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  //we are doing our own block delivery so we have no need to
  //ask the input to give us more blocks
  return this->Superclass::RequestUpdateExtent(request,
                                               inputVector,
                                               outputVector);
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::RequestData(vtkInformation *rqst,
  vtkInformationVector **inputVector, vtkInformationVector *outputVector)
{
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
    if (this->GetStreamingCapablePipeline() && !this->GetInStreamingUpdate())
      {
      // Since the representation re-executed, it means that the input changed
      // and we should initialize our streaming.
      vtkImageData *inputImage = vtkImageData::GetData(inputVector[0],0);
      vtkDataArray *inScalars = this->GetInputArrayToProcess(0,inputVector);

      this->Worker->StartContour(inputImage,inScalars,this->GetContourValue());
      }
    }

  this->ProcessedPiece = 0;
  if (inputVector[0]->GetNumberOfInformationObjects() == 1)
    {
    // Do the streaming independent "transformation" of the data here, in our
    // case, generate the polydata from the input.

    vtkImageData *input = vtkImageData::GetData(inputVector[0],0);
    if (!this->GetInStreamingUpdate())
      {
        this->ProcessedData = vtkSmartPointer<vtkImageData>::New();
        this->ProcessedData->ShallowCopy(input);

        this->DataBounds.SetBounds(input->GetBounds());
      }
    else
      {
      this->ProcessedPiece = input;
      }
    }
  else
    {
    // create an empty dataset. This is needed so that view knows what dataset
    // to expect from the other processes on this node.
    this->ProcessedData = vtkSmartPointer<vtkImageData>::New();
    this->DataBounds.Reset();
    }

  if (!this->GetInStreamingUpdate())
    {
    this->RenderedData = 0;

    // provide the mapper with an empty input. This is needed only because
    // mappers die when input is NULL, currently.
    vtkNew<vtkPolyData> tmp;
    this->Mapper->SetInputDataObject(tmp.GetPointer());
    }

  return this->Superclass::RequestData(rqst, inputVector, outputVector);
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::StreamingUpdate(const double view_planes[24])
{
  assert(this->InStreamingUpdate == false);

  if (this->Worker->IsFinished())
    {
    return false;
    }

  // We've determined we need to request something. Do it.
  this->InStreamingUpdate = true;
  vtkStreamingStatusMacro(<< this << ": doing streaming-update.");

  // This ensure that the representation re-executes.
  this->MarkModified();

  // Execute the pipeline.
  this->Update();

  this->InStreamingUpdate = false;
  return true;
}

//----------------------------------------------------------------------------
int vtkStreamingContourRepresentation::FillInputPortInformation(
  int vtkNotUsed(port), vtkInformation* info)
{

  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData");

  // Saying INPUT_IS_OPTIONAL() is essential, since representations don't have
  // any inputs on client-side (in client-server, client-render-server mode) and
  // render-server-side (in client-render-server mode).
  info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);

  return 1;
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::AddToView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
    {
    rview->GetRenderer()->AddActor(this->Actor);
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
bool vtkStreamingContourRepresentation::RemoveFromView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
    {
    rview->GetRenderer()->RemoveActor(this->Actor);
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "StreamingCapablePipeline: " << this->StreamingCapablePipeline << endl;
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetInputArrayToProcess(
  int idx, int port, int connection, int fieldAssociation, const char *name)
{
  this->Superclass::SetInputArrayToProcess(
    idx, port, connection, fieldAssociation, name);

  if (name && name[0])
    {
    this->Mapper->SetScalarVisibility(1);
    this->Mapper->SelectColorArray(name);
    this->Mapper->SetUseLookupTableScalarRange(1);
    }
  else
    {
    this->Mapper->SetScalarVisibility(0);
    this->Mapper->SelectColorArray(static_cast<const char*>(NULL));
    }

  switch (fieldAssociation)
    {
  case vtkDataObject::FIELD_ASSOCIATION_CELLS:
    this->Mapper->SetScalarMode(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA);
    break;

  case vtkDataObject::FIELD_ASSOCIATION_POINTS:
  default:
    this->Mapper->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA);
    break;
    }
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetLookupTable(vtkScalarsToColors* lut)
{
  this->Mapper->SetLookupTable(lut);
}

//----------------------------------------------------------------------------
void vtkStreamingContourRepresentation::SetPointSize(double val)
{
  this->Actor->GetProperty()->SetPointSize(val);
}
<|endoftext|>