<commit_before>#include "actiondb.h"
#include "main.h"

#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>
//#include <boost/serialization/base_object.hpp>

// I don't know WHY I need this, I'm just glad I found out I did...
BOOST_CLASS_EXPORT(StrokeSet)

BOOST_CLASS_EXPORT(Action)
BOOST_CLASS_EXPORT(Command)
BOOST_CLASS_EXPORT(ModAction)
BOOST_CLASS_EXPORT(SendKey)
BOOST_CLASS_EXPORT(Scroll)
BOOST_CLASS_EXPORT(Ignore)

template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) {
}

template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<Action>(*this);
	ar & cmd;
}

template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<Action>(*this);
	ar & mods;
}

template<class Archive> void SendKey::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
	ar & key;
	ar & code;
	ar & xtest;
}

template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
}

template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
}

template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<std::set<RStroke> >(*this);
}

template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) {
	ar & strokes;
	ar & action;
	if (version == 0) return;
	ar & name;
}

using namespace std;

bool Command::run() {
	system(cmd.c_str());
	return true;
}

ActionDB::ActionDB() : filename(config_dir+"actions"), current_id(0) {}

template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) {
	if (version >= 1) {
		ar & strokes;
		current_id = strokes.size();
		return;
	}
	std::map<std::string, StrokeInfo> strokes2;
	ar & strokes2;
	for (std::map<std::string, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i) {
		i->second.name = i->first;
		add(i->second);
	}
}

void ActionDB::read() {
	try {
		ifstream ifs(filename.c_str(), ios::binary);
		boost::archive::text_iarchive ia(ifs);
		ia >> *this;
		if (verbosity >= 2)
			cout << "Loaded " << strokes.size() << " actions." << endl;
	} catch (...) {
		cout << "Error: Couldn't read action database." << endl;
	}
}

bool ActionDB::write() const {
	try {
		ofstream ofs(filename.c_str());
		boost::archive::text_oarchive oa(ofs);
		const ActionDB db = *this;
		oa << db;
		if (verbosity >= 2)
			cout << "Saved " << strokes.size() << " actions." << endl;
		return true;
	} catch (...) {
		cout << "Error: Couldn't save action database." << endl;
		return false;
	}
}

bool ActionDB::remove(int id) {
	return strokes.erase(id);
}

int ActionDB::add(StrokeInfo &si) {
	strokes[current_id] = si;
	return current_id++;
}

int ActionDB::addCmd(RStroke stroke, const string& name, const string& cmd) {
	StrokeInfo si;
	if (stroke)
		si.strokes.insert(stroke);
	si.name = name;
	si.action = Command::create(cmd);
	return add(si);
}

int ActionDB::nested_size() const {
	int size = 0;
	for (const_iterator i = begin(); i != end(); i++)
		size += i->second.strokes.size();
	return size;
}

Ranking ActionDB::handle(RStroke s) {
	Ranking r;
	r.stroke = s;
	r.score = -1;
	bool success = false;
	if (!s)
		return r;
	for (StrokeIterator i = strokes_begin(); i; i++) {
		if (!i.stroke())
			continue;
		double score = Stroke::compare(s, i.stroke());
		r.r.insert(pair<double, pair<std::string, RStroke> >(score, pair<std::string, RStroke>(strokes[i.id()].name, i.stroke())));
		if (score >= r.score) {
			r.score = score;
			if (score >= 0.7) {
				r.id = i.id();
				r.name = strokes[r.id].name;
				r.action = i.action();
				success = true;
			}
		}
	}
	if (success) {
		if (verbosity >= 1)
			cout << "Excecuting Action " << r.name << "..." << endl;
		if (r.action)
			r.action->run();
	} else {
		if (verbosity >= 1)
			cout << "Couldn't find matching stroke." << endl;
	}
	return r;
}

LActionDB& actions() {
	static LActionDB actions_;
	return actions_;
}
<commit_msg>fixed a serious thinko<commit_after>#include "actiondb.h"
#include "main.h"

#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>
//#include <boost/serialization/base_object.hpp>

// I don't know WHY I need this, I'm just glad I found out I did...
BOOST_CLASS_EXPORT(StrokeSet)

BOOST_CLASS_EXPORT(Action)
BOOST_CLASS_EXPORT(Command)
BOOST_CLASS_EXPORT(ModAction)
BOOST_CLASS_EXPORT(SendKey)
BOOST_CLASS_EXPORT(Scroll)
BOOST_CLASS_EXPORT(Ignore)

template<class Archive> void Action::serialize(Archive & ar, const unsigned int version) {
}

template<class Archive> void Command::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<Action>(*this);
	ar & cmd;
}

template<class Archive> void ModAction::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<Action>(*this);
	ar & mods;
}

template<class Archive> void SendKey::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
	ar & key;
	ar & code;
	ar & xtest;
}

template<class Archive> void Scroll::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
}

template<class Archive> void Ignore::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<ModAction>(*this);
}

template<class Archive> void StrokeSet::serialize(Archive & ar, const unsigned int version) {
	ar & boost::serialization::base_object<std::set<RStroke> >(*this);
}

template<class Archive> void StrokeInfo::serialize(Archive & ar, const unsigned int version) {
	ar & strokes;
	ar & action;
	if (version == 0) return;
	ar & name;
}

using namespace std;

bool Command::run() {
	system(cmd.c_str());
	return true;
}

ActionDB::ActionDB() : filename(config_dir+"actions"), current_id(0) {}

template<class Archive> void ActionDB::load(Archive & ar, const unsigned int version) {
	if (version >= 1) {
		std::map<int, StrokeInfo> strokes2;
		ar & strokes2;
		for (std::map<int, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i)
			add(i->second);
		return;
	} else {
		std::map<std::string, StrokeInfo> strokes2;
		ar & strokes2;
		for (std::map<std::string, StrokeInfo>::iterator i = strokes2.begin(); i != strokes2.end(); ++i) {
			i->second.name = i->first;
			add(i->second);
		}
		return;
	}
}

void ActionDB::read() {
	try {
		ifstream ifs(filename.c_str(), ios::binary);
		boost::archive::text_iarchive ia(ifs);
		ia >> *this;
		if (verbosity >= 2)
			cout << "Loaded " << strokes.size() << " actions." << endl;
	} catch (...) {
		cout << "Error: Couldn't read action database." << endl;
	}
}

bool ActionDB::write() const {
	try {
		ofstream ofs(filename.c_str());
		boost::archive::text_oarchive oa(ofs);
		const ActionDB db = *this;
		oa << db;
		if (verbosity >= 2)
			cout << "Saved " << strokes.size() << " actions." << endl;
		return true;
	} catch (...) {
		cout << "Error: Couldn't save action database." << endl;
		return false;
	}
}

bool ActionDB::remove(int id) {
	return strokes.erase(id);
}

int ActionDB::add(StrokeInfo &si) {
	strokes[current_id] = si;
	return current_id++;
}

int ActionDB::addCmd(RStroke stroke, const string& name, const string& cmd) {
	StrokeInfo si;
	if (stroke)
		si.strokes.insert(stroke);
	si.name = name;
	si.action = Command::create(cmd);
	return add(si);
}

int ActionDB::nested_size() const {
	int size = 0;
	for (const_iterator i = begin(); i != end(); i++)
		size += i->second.strokes.size();
	return size;
}

Ranking ActionDB::handle(RStroke s) {
	Ranking r;
	r.stroke = s;
	r.score = -1;
	bool success = false;
	if (!s)
		return r;
	for (StrokeIterator i = strokes_begin(); i; i++) {
		if (!i.stroke())
			continue;
		double score = Stroke::compare(s, i.stroke());
		r.r.insert(pair<double, pair<std::string, RStroke> >(score, pair<std::string, RStroke>(strokes[i.id()].name, i.stroke())));
		if (score >= r.score) {
			r.score = score;
			if (score >= 0.7) {
				r.id = i.id();
				r.name = strokes[r.id].name;
				r.action = i.action();
				success = true;
			}
		}
	}
	if (success) {
		if (verbosity >= 1)
			cout << "Excecuting Action " << r.name << "..." << endl;
		if (r.action)
			r.action->run();
	} else {
		if (verbosity >= 1)
			cout << "Couldn't find matching stroke." << endl;
	}
	return r;
}

LActionDB& actions() {
	static LActionDB actions_;
	return actions_;
}
<|endoftext|>


<commit_before>//----------------------------  expand_instantiations.cc  -------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2007 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  expand_instantiations.cc  -------------------

// This is the program that we use to generate explicit instantiations for a
// variety of template arguments. It takes two kinds of input files. The first
// is given as arguments on the command line and contains entries of the
// following form:
// --------------------
// REAL_SCALARS    := { double; float; long double }
// COMPLEX_SCALARS := { std::complex<double>;
//                      std::complex<float>;
//                      std::complex<long double> }
// VECTORS := { Vector<double>; Vector<float>; Vector<long double> }
// --------------------
//
// The input file of this form is typically located in the common/ directory
// and is generated by ./configure to contain the list of vectors etc that
// make sense for the current configuration. For example, the list of VECTORS
// is going to contain PETSc vectors if so configured.
//
// The second intput is read from the command line and consists of a sequence
// of statements of the following form:
// --------------------
// for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); }
// --------------------
// Here, everything between {...} will be copied as many times as there are
// combinations of arguments u,v in the list of substitutions given by
// VECTORS. For each copy, the arguments u,v will be replaced by one of these
// combinations.

// Author: Wolfgang Bangerth, 2007

#include <iostream>
#include <fstream>
#include <map>
#include <list>

// a map from the keys in the expansion lists to the list itself. For
// instance, the example above will lead to the entry
//      expansion_lists[REAL_SCALARS] = (double, float, long double)
// in this map, among others
std::map<std::string, std::list<std::string> >  expansion_lists;

/* ======================== auxiliary functions ================= */

// extract from the start of #in the part of the string that ends with one of
// the characters in #delim_list. The extracted part is deleted from #in
std::string
get_substring_with_delim (std::string       &in,
			  const std::string &delim_list)
{
  std::string x;
  while ((in.size() != 0)
	 &&
	 (delim_list.find (in[0]) == std::string::npos))
    {
      x += in[0];
      in.erase (0, 1);
    }

  return x;
}

// delete all whitespace at the beginning of the given argument
void
skip_space (std::string &in)
{
  while ((in.size() != 0)
	 &&
	 ((in[0] == ' ') || (in[0] == '\t') || (in[0] == '\n')))
    in.erase (0, 1);
}

// read the whole file specified by the stream given as argument into a string
// for simpler parsing, and return it
std::string read_whole_file (std::istream &in)
{
  std::string whole_file;
  while (in)
    {
      std::string line;
      getline (in, line);

      if (line.find ("//") != 0)
	{
	  whole_file += line;
	  whole_file += '\n';
	}
    }
				   // substitute tabs by spaces, multiple
				   // spaces by single ones
  for (unsigned int i=0; i<whole_file.size(); ++i)
    if (whole_file[i] == '\t')
      whole_file[i] = ' ';
  while (whole_file.find("  ") != std::string::npos)
    whole_file.replace (whole_file.find("  "), 2, " ");

  return whole_file;
}

// split a given string assumed to consist of a list of substrings delimited
// by a particular character into its components
std::list<std::string>
split_string_list (const std::string &s,
		   const char         delimiter)
{
  std::string tmp = s;
  std::list<std::string> split_list;

				   // split the input list
  while (tmp.length() != 0)
    {
      std::string name;
      name = tmp;

      if (name.find(delimiter) != std::string::npos)
	{
	  name.erase (name.find(delimiter), std::string::npos);
	  tmp.erase (0, tmp.find(delimiter)+1);
	}
      else
	tmp = "";

      while ((name.length() != 0) &&
	     (name[0] == ' '))
	name.erase (0,1);

      while (name[name.length()-1] == ' ')
	name.erase (name.length()-1, 1);

      split_list.push_back (name);
    }

  return split_list;
}

// determine whether a given substring at position #pos and length #length in
// the string #text is a real token, i.e. not just part of another word
bool is_real_token (const std::string &text,
		    const std::string::size_type pos,
		    const std::string::size_type length)
{
  static const std::string token_chars ("abcdefghijklmnopqrstuvwxyz"
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
					"0123456789"
					"_");
  if ((pos != 0) && (token_chars.find (text[pos-1]) != std::string::npos))
    return false;

  if ((pos+length < text.size()) &&
      (token_chars.find (text[pos+length]) != std::string::npos))
    return false;

  return true;
}

// substitute all occurrences of #token in #text by #substitute
std::string substitute_tokens (const std::string &text,
			       const std::string &token,
			       const std::string &substitute)
{
  std::string x_text = text;
  std::string::size_type pos = 0;
  while ((pos = x_text.find(token, pos)) != std::string::npos)
    {
      if (is_real_token (x_text, pos, token.size()))
	{
	  x_text.replace (pos, token.size(), substitute);
	  pos += substitute.size();
	}
      else
	++pos;
    }

  return x_text;
}

/* ======================== the main functions ================= */

// read and parse the expansion lists like
//     REAL_SCALARS    := { double; float; long double }
// as specified at the top of the file and store them in
// the global expansion_lists variable
void read_expansion_lists (const std::string &filename)
{
  std::ifstream in (filename.c_str());

  if (! in)
    {
      std::cerr << "Instantiation list file can not be read!"
		<< std::endl;
      std::exit (1);
    }

				   // read the entire file into a string for
				   // simpler processing. replace end-of-line
				   // characters by spaces
  std::string whole_file = read_whole_file (in);

				   // now process entries of the form
				   // NAME := { class1; class2; ...}.
  while (whole_file.size() != 0)
    {
      const std::string
	name = get_substring_with_delim (whole_file, " :");

      skip_space (whole_file);
      if (whole_file.find (":=") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 2);
      skip_space (whole_file);
      if (whole_file.find ("{") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      std::string
	expansion = get_substring_with_delim (whole_file, "}");

      if (whole_file.find ("}") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      expansion_lists[name] = split_string_list (expansion, ';');
    }
}

// produce all combinations of substitutions of the tokens given in the
// #substitutions list in #text and output it to std::cout
void substitute (const std::string &text,
		 const std::list<std::pair<std::string, std::string> > &substitutions)
{
				   // do things recursively: if the list of
				   // substiutions has a single entry, then
				   // process all of them. otherwise, process
				   // the first in the list and call the
				   // function recursively with the rest of
				   // the substitutions
  if (substitutions.size() > 1)
    {
				       // do the first substitution, then call
				       // function recursively
      const std::string name    = substitutions.front().first,
			pattern = substitutions.front().second;

      const std::list<std::pair<std::string, std::string> >
	rest_of_substitutions (++substitutions.begin(),
			       substitutions.end());

      for (std::list<std::string>::const_iterator
	     expansion = expansion_lists[pattern].begin();
	   expansion != expansion_lists[pattern].end();
	   ++expansion)
	{
	  std::string new_text
	    = substitute_tokens (text, name, *expansion);

	  substitute (new_text, rest_of_substitutions);
	}
    }
  else if (substitutions.size() == 1)
    {
				       // do the substitutions
      const std::string name    = substitutions.front().first,
			pattern = substitutions.front().second;

      for (std::list<std::string>::const_iterator
	     expansion = expansion_lists[pattern].begin();
	   expansion != expansion_lists[pattern].end();
	   ++expansion)
	std::cout << substitute_tokens (text, name, *expansion)
		  << std::endl;
    }
  else
    {
      std::cout << text
		<< std::endl;
    }
}

// process the list of instantiations given in the form
// --------------------
// for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); }
// --------------------
void process_instantiations ()
{
  std::string whole_file = read_whole_file (std::cin);

				   // process entries of the form
				   //  for (X:Y; A:B) { INST }
  while (whole_file.size() != 0)
    {
      skip_space (whole_file);
      if (whole_file.find ("for") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 3);
      skip_space (whole_file);
      if (whole_file.find ("(") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      const std::list<std::string>
	substitutions_list
	= split_string_list (get_substring_with_delim (whole_file,
								     ")"),
					   ';');
      if (whole_file.find (")") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

				       // process the header
      std::list<std::pair<std::string, std::string> >
	substitutions;

      for (std::list<std::string>::const_iterator
	     s = substitutions_list.begin();
	   s != substitutions_list.end(); ++s)
	{
	  const std::list<std::string>
	    names_and_type = split_string_list (*s, ':');
	  if (names_and_type.size() != 2)
	    {
	      std::cerr << "Invalid instantiation header" << std::endl;
	      std::exit (1);
	    }

	  const std::list<std::string>
	    names = split_string_list (names_and_type.front(), ',');

	  for (std::list<std::string>::const_iterator
		 x = names.begin(); x != names.end(); ++x)
	    substitutions.push_back (std::make_pair (*x,
						     names_and_type.back()));
	}

				       // now read the part in {...}
      skip_space (whole_file);
      if (whole_file.find ("{") != 0)
	{
	  std::cerr << "Invalid substitution text" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);
      const std::string text_to_substitute
	= get_substring_with_delim (whole_file, "}");
      whole_file.erase (0,1);
      skip_space (whole_file);

				       // now produce the substitutions
      substitute (text_to_substitute, substitutions);
    }
}

int main (int argc, char **argv)
{
  if (argc < 2)
    {
      std::cerr << "Usage: " << std::endl
		<< "  expand_instantiations class_list_files < in_file > out_file"
		<< std::endl;
      std::exit (1);
    }

  for (int i=1; i<argc; ++i)
    read_expansion_lists (argv[i]);

  process_instantiations ();
}
<commit_msg>Eat all sorts of whitespace when splitting a string.<commit_after>//----------------------------  expand_instantiations.cc  -------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2007 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  expand_instantiations.cc  -------------------

// This is the program that we use to generate explicit instantiations for a
// variety of template arguments. It takes two kinds of input files. The first
// is given as arguments on the command line and contains entries of the
// following form:
// --------------------
// REAL_SCALARS    := { double; float; long double }
// COMPLEX_SCALARS := { std::complex<double>;
//                      std::complex<float>;
//                      std::complex<long double> }
// VECTORS := { Vector<double>; Vector<float>; Vector<long double> }
// --------------------
//
// The input file of this form is typically located in the common/ directory
// and is generated by ./configure to contain the list of vectors etc that
// make sense for the current configuration. For example, the list of VECTORS
// is going to contain PETSc vectors if so configured.
//
// The second intput is read from the command line and consists of a sequence
// of statements of the following form:
// --------------------
// for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); }
// --------------------
// Here, everything between {...} will be copied as many times as there are
// combinations of arguments u,v in the list of substitutions given by
// VECTORS. For each copy, the arguments u,v will be replaced by one of these
// combinations.

// Author: Wolfgang Bangerth, 2007

#include <iostream>
#include <fstream>
#include <map>
#include <list>

// a map from the keys in the expansion lists to the list itself. For
// instance, the example above will lead to the entry
//      expansion_lists[REAL_SCALARS] = (double, float, long double)
// in this map, among others
std::map<std::string, std::list<std::string> >  expansion_lists;

/* ======================== auxiliary functions ================= */

// extract from the start of #in the part of the string that ends with one of
// the characters in #delim_list. The extracted part is deleted from #in
std::string
get_substring_with_delim (std::string       &in,
			  const std::string &delim_list)
{
  std::string x;
  while ((in.size() != 0)
	 &&
	 (delim_list.find (in[0]) == std::string::npos))
    {
      x += in[0];
      in.erase (0, 1);
    }

  return x;
}

// delete all whitespace at the beginning of the given argument
void
skip_space (std::string &in)
{
  while ((in.size() != 0)
	 &&
	 ((in[0] == ' ') || (in[0] == '\t') || (in[0] == '\n')))
    in.erase (0, 1);
}

// read the whole file specified by the stream given as argument into a string
// for simpler parsing, and return it
std::string read_whole_file (std::istream &in)
{
  std::string whole_file;
  while (in)
    {
      std::string line;
      getline (in, line);

      if (line.find ("//") != 0)
	{
	  whole_file += line;
	  whole_file += '\n';
	}
    }
				   // substitute tabs by spaces, multiple
				   // spaces by single ones
  for (unsigned int i=0; i<whole_file.size(); ++i)
    if (whole_file[i] == '\t')
      whole_file[i] = ' ';
  while (whole_file.find("  ") != std::string::npos)
    whole_file.replace (whole_file.find("  "), 2, " ");

  return whole_file;
}

// split a given string assumed to consist of a list of substrings delimited
// by a particular character into its components
std::list<std::string>
split_string_list (const std::string &s,
		   const char         delimiter)
{
  std::string tmp = s;
  std::list<std::string> split_list;

				   // split the input list
  while (tmp.length() != 0)
    {
      std::string name;
      name = tmp;

      if (name.find(delimiter) != std::string::npos)
	{
	  name.erase (name.find(delimiter), std::string::npos);
	  tmp.erase (0, tmp.find(delimiter)+1);
	}
      else
	tmp = "";

      skip_space (name);

      while (name[name.length()-1] == ' ')
	name.erase (name.length()-1, 1);

      split_list.push_back (name);
    }

  return split_list;
}

// determine whether a given substring at position #pos and length #length in
// the string #text is a real token, i.e. not just part of another word
bool is_real_token (const std::string &text,
		    const std::string::size_type pos,
		    const std::string::size_type length)
{
  static const std::string token_chars ("abcdefghijklmnopqrstuvwxyz"
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
					"0123456789"
					"_");
  if ((pos != 0) && (token_chars.find (text[pos-1]) != std::string::npos))
    return false;

  if ((pos+length < text.size()) &&
      (token_chars.find (text[pos+length]) != std::string::npos))
    return false;

  return true;
}

// substitute all occurrences of #token in #text by #substitute
std::string substitute_tokens (const std::string &text,
			       const std::string &token,
			       const std::string &substitute)
{
  std::string x_text = text;
  std::string::size_type pos = 0;
  while ((pos = x_text.find(token, pos)) != std::string::npos)
    {
      if (is_real_token (x_text, pos, token.size()))
	{
	  x_text.replace (pos, token.size(), substitute);
	  pos += substitute.size();
	}
      else
	++pos;
    }

  return x_text;
}

/* ======================== the main functions ================= */

// read and parse the expansion lists like
//     REAL_SCALARS    := { double; float; long double }
// as specified at the top of the file and store them in
// the global expansion_lists variable
void read_expansion_lists (const std::string &filename)
{
  std::ifstream in (filename.c_str());

  if (! in)
    {
      std::cerr << "Instantiation list file can not be read!"
		<< std::endl;
      std::exit (1);
    }

				   // read the entire file into a string for
				   // simpler processing. replace end-of-line
				   // characters by spaces
  std::string whole_file = read_whole_file (in);

				   // now process entries of the form
				   // NAME := { class1; class2; ...}.
  while (whole_file.size() != 0)
    {
      const std::string
	name = get_substring_with_delim (whole_file, " :");

      skip_space (whole_file);
      if (whole_file.find (":=") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 2);
      skip_space (whole_file);
      if (whole_file.find ("{") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      std::string
	expansion = get_substring_with_delim (whole_file, "}");

      if (whole_file.find ("}") != 0)
	{
	  std::cerr << "Invalid entry <" << name << '>' << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      expansion_lists[name] = split_string_list (expansion, ';');
    }
}

// produce all combinations of substitutions of the tokens given in the
// #substitutions list in #text and output it to std::cout
void substitute (const std::string &text,
		 const std::list<std::pair<std::string, std::string> > &substitutions)
{
				   // do things recursively: if the list of
				   // substiutions has a single entry, then
				   // process all of them. otherwise, process
				   // the first in the list and call the
				   // function recursively with the rest of
				   // the substitutions
  if (substitutions.size() > 1)
    {
				       // do the first substitution, then call
				       // function recursively
      const std::string name    = substitutions.front().first,
			pattern = substitutions.front().second;

      const std::list<std::pair<std::string, std::string> >
	rest_of_substitutions (++substitutions.begin(),
			       substitutions.end());

      for (std::list<std::string>::const_iterator
	     expansion = expansion_lists[pattern].begin();
	   expansion != expansion_lists[pattern].end();
	   ++expansion)
	{
	  std::string new_text
	    = substitute_tokens (text, name, *expansion);

	  substitute (new_text, rest_of_substitutions);
	}
    }
  else if (substitutions.size() == 1)
    {
				       // do the substitutions
      const std::string name    = substitutions.front().first,
			pattern = substitutions.front().second;

      for (std::list<std::string>::const_iterator
	     expansion = expansion_lists[pattern].begin();
	   expansion != expansion_lists[pattern].end();
	   ++expansion)
	std::cout << substitute_tokens (text, name, *expansion)
		  << std::endl;
    }
  else
    {
      std::cout << text
		<< std::endl;
    }
}

// process the list of instantiations given in the form
// --------------------
// for (u,v:VECTORS; z:SCALARS) { f(u, z, const v &); }
// --------------------
void process_instantiations ()
{
  std::string whole_file = read_whole_file (std::cin);

				   // process entries of the form
				   //  for (X:Y; A:B) { INST }
  while (whole_file.size() != 0)
    {
      skip_space (whole_file);
      if (whole_file.find ("for") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 3);
      skip_space (whole_file);
      if (whole_file.find ("(") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

      const std::list<std::string>
	substitutions_list
	= split_string_list (get_substring_with_delim (whole_file,
								     ")"),
					   ';');
      if (whole_file.find (")") != 0)
	{
	  std::cerr << "Invalid instantiation list" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);

				       // process the header
      std::list<std::pair<std::string, std::string> >
	substitutions;

      for (std::list<std::string>::const_iterator
	     s = substitutions_list.begin();
	   s != substitutions_list.end(); ++s)
	{
	  const std::list<std::string>
	    names_and_type = split_string_list (*s, ':');
	  if (names_and_type.size() != 2)
	    {
	      std::cerr << "Invalid instantiation header" << std::endl;
	      std::exit (1);
	    }

	  const std::list<std::string>
	    names = split_string_list (names_and_type.front(), ',');

	  for (std::list<std::string>::const_iterator
		 x = names.begin(); x != names.end(); ++x)
	    substitutions.push_back (std::make_pair (*x,
						     names_and_type.back()));
	}

				       // now read the part in {...}
      skip_space (whole_file);
      if (whole_file.find ("{") != 0)
	{
	  std::cerr << "Invalid substitution text" << std::endl;
	  std::exit (1);
	}
      whole_file.erase (0, 1);
      skip_space (whole_file);
      const std::string text_to_substitute
	= get_substring_with_delim (whole_file, "}");
      whole_file.erase (0,1);
      skip_space (whole_file);

				       // now produce the substitutions
      substitute (text_to_substitute, substitutions);
    }
}

int main (int argc, char **argv)
{
  if (argc < 2)
    {
      std::cerr << "Usage: " << std::endl
		<< "  expand_instantiations class_list_files < in_file > out_file"
		<< std::endl;
      std::exit (1);
    }

  for (int i=1; i<argc; ++i)
    read_expansion_lists (argv[i]);

  process_instantiations ();
}
<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "base/desktop/screen_capturer_wrapper.h"

#include "base/logging.h"
#include "base/desktop/desktop_environment.h"
#include "base/desktop/desktop_resizer.h"
#include "base/desktop/mouse_cursor.h"
#include "base/desktop/power_save_blocker.h"
#include "base/ipc/shared_memory_factory.h"

#if defined(OS_WIN)
#include "base/desktop/screen_capturer_dxgi.h"
#include "base/desktop/screen_capturer_gdi.h"
#include "base/desktop/screen_capturer_mirror.h"
#include "base/win/windows_version.h"
#elif defined(OS_LINUX)
// TODO
#elif defined(OS_MAC)
// TODO
#else
#error Platform support not implemented
#endif

namespace base {

ScreenCapturerWrapper::ScreenCapturerWrapper(ScreenCapturer::Type preferred_type,
                                             Delegate* delegate)
    : preferred_type_(preferred_type),
      delegate_(delegate),
      power_save_blocker_(std::make_unique<PowerSaveBlocker>()),
      environment_(std::make_unique<DesktopEnvironment>())
{
    LOG(LS_INFO) << "Ctor";

#if defined(OS_WIN)
    // If the monitor is turned off, this call will turn it on.
    SetThreadExecutionState(ES_DISPLAY_REQUIRED);
#endif // defined(OS_WIN)

    switchToInputDesktop();
    selectCapturer();
}

ScreenCapturerWrapper::~ScreenCapturerWrapper()
{
    LOG(LS_INFO) << "Dtor";
}

void ScreenCapturerWrapper::selectScreen(ScreenCapturer::ScreenId screen_id, const Size& resolution)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (screen_id == screen_capturer_->currentScreen())
    {
        if (resolution.isEmpty())
        {
            LOG(LS_WARNING) << "Empty resolution";
        }
        else
        {
            if (!resizer_)
            {
                LOG(LS_WARNING) << "No desktop resizer";
            }
            else
            {
                LOG(LS_INFO) << "Change resolution for screen " << screen_id << " to: " << resolution;
                resizer_->setResolution(screen_id, resolution);
            }
        }
    }
    else
    {
        LOG(LS_INFO) << "Try to select screen: " << screen_id;

        if (!screen_capturer_->selectScreen(screen_id))
        {
            LOG(LS_ERROR) << "ScreenCapturer::selectScreen failed";
        }
        else
        {
            LOG(LS_INFO) << "Screen " << screen_id << " selected";
            last_screen_id_ = screen_id;
        }
    }

    ScreenCapturer::ScreenList screen_list;
    if (screen_capturer_->screenList(&screen_list))
    {
        LOG(LS_INFO) << "Received an updated list of screens";

        if (resizer_)
        {
            screen_list.resolutions = resizer_->supportedResolutions(screen_id);
            if (screen_list.resolutions.empty())
            {
                LOG(LS_INFO) << "No supported resolutions";
            }

            for (const auto& resolition : screen_list.resolutions)
            {
                LOG(LS_INFO) << "Supported resolution: " << resolition;
            }
        }
        else
        {
            LOG(LS_INFO) << "No desktop resizer";
        }

        for (const auto& screen : screen_list.screens)
        {
            LOG(LS_INFO) << "Screen #" << screen.id << " (position: " << screen.position
                         << " resolution: " << screen.resolution << " DPI: " << screen.dpi << ")";
        }

        delegate_->onScreenListChanged(screen_list, screen_id);
    }
    else
    {
        LOG(LS_ERROR) << "ScreenCapturer::screenList failed";
    }
}

void ScreenCapturerWrapper::captureFrame()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!screen_capturer_)
    {
        LOG(LS_ERROR) << "Screen capturer NOT initialized";
        return;
    }

    switchToInputDesktop();

    int count = screen_capturer_->screenCount();
    if (screen_count_ != count)
    {
        LOG(LS_INFO) << "Screen count changed: " << count << " (old: " << screen_count_ << ")";

        resizer_.reset();
        resizer_ = DesktopResizer::create();

        screen_count_ = count;
        selectScreen(defaultScreen(), Size());
    }

    ScreenCapturer::Error error;
    const Frame* frame = screen_capturer_->captureFrame(&error);
    if (!frame)
    {
        switch (error)
        {
            case ScreenCapturer::Error::TEMPORARY:
                break;

            case ScreenCapturer::Error::PERMANENT:
            {
                ++permanent_error_count_;
                selectCapturer();
            }
            break;

            default:
                NOTREACHED();
                break;
        }
    }

    delegate_->onScreenCaptured(frame, screen_capturer_->captureCursor());

    if (enable_cursor_position_)
    {
        Point cursor_pos = screen_capturer_->cursorPosition();

        int32_t delta_x = std::abs(cursor_pos.x() - last_cursor_pos_.x());
        int32_t delta_y = std::abs(cursor_pos.y() - last_cursor_pos_.y());

        if (delta_x > 1 || delta_y > 1)
        {
            delegate_->onCursorPositionChanged(cursor_pos);
            last_cursor_pos_ = cursor_pos;
        }
    }
}

void ScreenCapturerWrapper::setSharedMemoryFactory(SharedMemoryFactory* shared_memory_factory)
{
    shared_memory_factory_ = shared_memory_factory;

    if (screen_capturer_)
        screen_capturer_->setSharedMemoryFactory(shared_memory_factory);
}

void ScreenCapturerWrapper::enableWallpaper(bool enable)
{
    environment_->setWallpaper(enable);
}

void ScreenCapturerWrapper::enableEffects(bool enable)
{
    environment_->setEffects(enable);
}

void ScreenCapturerWrapper::enableFontSmoothing(bool enable)
{
    environment_->setFontSmoothing(enable);
}

void ScreenCapturerWrapper::enableCursorPosition(bool enable)
{
    enable_cursor_position_ = enable;
}

ScreenCapturer::ScreenId ScreenCapturerWrapper::defaultScreen()
{
    ScreenCapturer::ScreenList screen_list;
    if (screen_capturer_->screenList(&screen_list))
    {
        for (const auto& screen : screen_list.screens)
        {
            if (screen.is_primary)
            {
                LOG(LS_INFO) << "Primary screen found: " << screen.id;
                return screen.id;
            }
        }
    }

    LOG(LS_INFO) << "Primary screen NOT found";
    return ScreenCapturer::kFullDesktopScreenId;
}

void ScreenCapturerWrapper::selectCapturer()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

#if defined(OS_WIN)
    auto try_mirror_capturer = [this]()
    {
        // Mirror screen capture is available only in Windows 7/2008 R2.
        if (win::windowsVersion() == base::win::VERSION_WIN7)
        {
            std::unique_ptr<ScreenCapturerMirror> capturer_mirror =
                std::make_unique<ScreenCapturerMirror>();

            if (capturer_mirror->isSupported())
            {
                LOG(LS_INFO) << "Using MIRROR capturer";
                screen_capturer_ = std::move(capturer_mirror);
            }
        }
    };

    static const int kMaxPermanentErrorCount = 3;

    if (permanent_error_count_ >= kMaxPermanentErrorCount)
    {
        // Skip other capturer types and using GDI capturer.
        permanent_error_count_ = 0;
    }
    else if (preferred_type_ == ScreenCapturer::Type::WIN_DXGI ||
             preferred_type_ == ScreenCapturer::Type::DEFAULT)
    {
        if (win::windowsVersion() >= win::VERSION_WIN8)
        {
            // Desktop Duplication API is available in Windows 8+.
            std::unique_ptr<ScreenCapturerDxgi> capturer_dxgi =
                std::make_unique<ScreenCapturerDxgi>();
            if (capturer_dxgi->isSupported())
            {
                LOG(LS_INFO) << "Using DXGI capturer";
                screen_capturer_ = std::move(capturer_dxgi);
            }
        }
        else
        {
            try_mirror_capturer();
        }
    }
    else if (preferred_type_ == ScreenCapturer::Type::WIN_MIRROR)
    {
        try_mirror_capturer();
    }

    if (!screen_capturer_)
    {
        LOG(LS_INFO) << "Using GDI capturer";
        screen_capturer_ = std::make_unique<ScreenCapturerGdi>();
    }

#elif defined(OS_LINUX)
    NOTIMPLEMENTED();
#elif defined(OS_MAC)
    NOTIMPLEMENTED();
#else
    NOTIMPLEMENTED();
#endif

    screen_capturer_->setSharedMemoryFactory(shared_memory_factory_);
    if (last_screen_id_ != ScreenCapturer::kInvalidScreenId)
    {
        LOG(LS_INFO) << "Restore selected screen: " << last_screen_id_;
        selectScreen(last_screen_id_, Size());
    }
}

void ScreenCapturerWrapper::switchToInputDesktop()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
#if defined(OS_WIN)
    // Switch to the desktop receiving user input if different from the current one.
    Desktop input_desktop(Desktop::inputDesktop());

    if (input_desktop.isValid() && !desktop_.isSame(input_desktop))
    {
        wchar_t desktop_name[128] = { 0 };
        input_desktop.name(desktop_name, sizeof(desktop_name));

        LOG(LS_INFO) << "Input desktop changed to " << desktop_name;

        if (screen_capturer_)
            screen_capturer_->reset();

        // If setThreadDesktop() fails, the thread is still assigned a desktop.
        // So we can continue capture screen bits, just from the wrong desktop.
        desktop_.setThreadDesktop(std::move(input_desktop));
    }
#endif // defined(OS_WIN)
}

} // namespace base
<commit_msg>Add debug messages.<commit_after>//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "base/desktop/screen_capturer_wrapper.h"

#include "base/logging.h"
#include "base/desktop/desktop_environment.h"
#include "base/desktop/desktop_resizer.h"
#include "base/desktop/mouse_cursor.h"
#include "base/desktop/power_save_blocker.h"
#include "base/ipc/shared_memory_factory.h"

#if defined(OS_WIN)
#include "base/desktop/screen_capturer_dxgi.h"
#include "base/desktop/screen_capturer_gdi.h"
#include "base/desktop/screen_capturer_mirror.h"
#include "base/win/windows_version.h"
#elif defined(OS_LINUX)
// TODO
#elif defined(OS_MAC)
// TODO
#else
#error Platform support not implemented
#endif

namespace base {

ScreenCapturerWrapper::ScreenCapturerWrapper(ScreenCapturer::Type preferred_type,
                                             Delegate* delegate)
    : preferred_type_(preferred_type),
      delegate_(delegate),
      power_save_blocker_(std::make_unique<PowerSaveBlocker>()),
      environment_(std::make_unique<DesktopEnvironment>())
{
    LOG(LS_INFO) << "Ctor";

#if defined(OS_WIN)
    // If the monitor is turned off, this call will turn it on.
    if (!SetThreadExecutionState(ES_DISPLAY_REQUIRED))
    {
        PLOG(LS_WARNING) << "SetThreadExecutionState failed";
    }
#endif // defined(OS_WIN)

    switchToInputDesktop();
    selectCapturer();
}

ScreenCapturerWrapper::~ScreenCapturerWrapper()
{
    LOG(LS_INFO) << "Dtor";
}

void ScreenCapturerWrapper::selectScreen(ScreenCapturer::ScreenId screen_id, const Size& resolution)
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (screen_id == screen_capturer_->currentScreen())
    {
        if (resolution.isEmpty())
        {
            LOG(LS_WARNING) << "Empty resolution";
        }
        else
        {
            if (!resizer_)
            {
                LOG(LS_WARNING) << "No desktop resizer";
            }
            else
            {
                LOG(LS_INFO) << "Change resolution for screen " << screen_id << " to: " << resolution;
                resizer_->setResolution(screen_id, resolution);
            }
        }
    }
    else
    {
        LOG(LS_INFO) << "Try to select screen: " << screen_id;

        if (!screen_capturer_->selectScreen(screen_id))
        {
            LOG(LS_ERROR) << "ScreenCapturer::selectScreen failed";
        }
        else
        {
            LOG(LS_INFO) << "Screen " << screen_id << " selected";
            last_screen_id_ = screen_id;
        }
    }

    ScreenCapturer::ScreenList screen_list;
    if (screen_capturer_->screenList(&screen_list))
    {
        LOG(LS_INFO) << "Received an updated list of screens";

        if (resizer_)
        {
            screen_list.resolutions = resizer_->supportedResolutions(screen_id);
            if (screen_list.resolutions.empty())
            {
                LOG(LS_INFO) << "No supported resolutions";
            }

            for (const auto& resolition : screen_list.resolutions)
            {
                LOG(LS_INFO) << "Supported resolution: " << resolition;
            }
        }
        else
        {
            LOG(LS_INFO) << "No desktop resizer";
        }

        for (const auto& screen : screen_list.screens)
        {
            LOG(LS_INFO) << "Screen #" << screen.id << " (position: " << screen.position
                         << " resolution: " << screen.resolution << " DPI: " << screen.dpi << ")";
        }

        delegate_->onScreenListChanged(screen_list, screen_id);
    }
    else
    {
        LOG(LS_ERROR) << "ScreenCapturer::screenList failed";
    }
}

void ScreenCapturerWrapper::captureFrame()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    if (!screen_capturer_)
    {
        LOG(LS_ERROR) << "Screen capturer NOT initialized";
        return;
    }

    switchToInputDesktop();

    int count = screen_capturer_->screenCount();
    if (screen_count_ != count)
    {
        LOG(LS_INFO) << "Screen count changed: " << count << " (old: " << screen_count_ << ")";

        resizer_.reset();
        resizer_ = DesktopResizer::create();

        screen_count_ = count;
        selectScreen(defaultScreen(), Size());
    }

    ScreenCapturer::Error error;
    const Frame* frame = screen_capturer_->captureFrame(&error);
    if (!frame)
    {
        switch (error)
        {
            case ScreenCapturer::Error::TEMPORARY:
                break;

            case ScreenCapturer::Error::PERMANENT:
            {
                ++permanent_error_count_;

                LOG(LS_WARNING) << "Permanent error detected (" << permanent_error_count_ << ")";
                selectCapturer();
            }
            break;

            default:
                NOTREACHED();
                break;
        }
    }
    else
    {
        permanent_error_count_ = 0;
    }

    delegate_->onScreenCaptured(frame, screen_capturer_->captureCursor());

    if (enable_cursor_position_)
    {
        Point cursor_pos = screen_capturer_->cursorPosition();

        int32_t delta_x = std::abs(cursor_pos.x() - last_cursor_pos_.x());
        int32_t delta_y = std::abs(cursor_pos.y() - last_cursor_pos_.y());

        if (delta_x > 1 || delta_y > 1)
        {
            delegate_->onCursorPositionChanged(cursor_pos);
            last_cursor_pos_ = cursor_pos;
        }
    }
}

void ScreenCapturerWrapper::setSharedMemoryFactory(SharedMemoryFactory* shared_memory_factory)
{
    shared_memory_factory_ = shared_memory_factory;

    if (screen_capturer_)
        screen_capturer_->setSharedMemoryFactory(shared_memory_factory);
}

void ScreenCapturerWrapper::enableWallpaper(bool enable)
{
    environment_->setWallpaper(enable);
}

void ScreenCapturerWrapper::enableEffects(bool enable)
{
    environment_->setEffects(enable);
}

void ScreenCapturerWrapper::enableFontSmoothing(bool enable)
{
    environment_->setFontSmoothing(enable);
}

void ScreenCapturerWrapper::enableCursorPosition(bool enable)
{
    enable_cursor_position_ = enable;
}

ScreenCapturer::ScreenId ScreenCapturerWrapper::defaultScreen()
{
    ScreenCapturer::ScreenList screen_list;
    if (screen_capturer_->screenList(&screen_list))
    {
        for (const auto& screen : screen_list.screens)
        {
            if (screen.is_primary)
            {
                LOG(LS_INFO) << "Primary screen found: " << screen.id;
                return screen.id;
            }
        }
    }
    else
    {
        LOG(LS_WARNING) << "ScreenCapturer::screenList failed";
    }

    LOG(LS_INFO) << "Primary screen NOT found";
    return ScreenCapturer::kFullDesktopScreenId;
}

void ScreenCapturerWrapper::selectCapturer()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

    LOG(LS_INFO) << "Selecting screen capturer. Preferred capturer: "
                 << static_cast<int>(preferred_type_);

#if defined(OS_WIN)
    auto try_mirror_capturer = [this]()
    {
        // Mirror screen capture is available only in Windows 7/2008 R2.
        if (win::windowsVersion() == base::win::VERSION_WIN7)
        {
            LOG(LS_INFO) << "Windows 7/2008R2 detected. Try to initialize MIRROR capturer";

            std::unique_ptr<ScreenCapturerMirror> capturer_mirror =
                std::make_unique<ScreenCapturerMirror>();

            if (capturer_mirror->isSupported())
            {
                LOG(LS_INFO) << "Using MIRROR capturer";
                screen_capturer_ = std::move(capturer_mirror);
            }
            else
            {
                LOG(LS_INFO) << "MIRROR capturer unavailable";
            }
        }
        else
        {
            LOG(LS_INFO) << "Windows version is not equal to 7/2008R2. MIRROR capturer unavailable";
        }
    };

    static const int kMaxPermanentErrorCount = 3;

    if (permanent_error_count_ >= kMaxPermanentErrorCount)
    {
        // Skip other capturer types and using GDI capturer.
        LOG(LS_INFO) << "Number of permanent errors has been exceeded. Reset to GDI capturer";
        permanent_error_count_ = 0;
    }
    else if (preferred_type_ == ScreenCapturer::Type::WIN_DXGI ||
             preferred_type_ == ScreenCapturer::Type::DEFAULT)
    {
        if (win::windowsVersion() >= win::VERSION_WIN8)
        {
            // Desktop Duplication API is available in Windows 8+.
            std::unique_ptr<ScreenCapturerDxgi> capturer_dxgi =
                std::make_unique<ScreenCapturerDxgi>();
            if (capturer_dxgi->isSupported())
            {
                LOG(LS_INFO) << "Using DXGI capturer";
                screen_capturer_ = std::move(capturer_dxgi);
            }
        }
        else
        {
            try_mirror_capturer();
        }
    }
    else if (preferred_type_ == ScreenCapturer::Type::WIN_MIRROR)
    {
        try_mirror_capturer();
    }

    if (!screen_capturer_)
    {
        LOG(LS_INFO) << "Using GDI capturer";
        screen_capturer_ = std::make_unique<ScreenCapturerGdi>();
    }

#elif defined(OS_LINUX)
    NOTIMPLEMENTED();
#elif defined(OS_MAC)
    NOTIMPLEMENTED();
#else
    NOTIMPLEMENTED();
#endif

    screen_capturer_->setSharedMemoryFactory(shared_memory_factory_);
    if (last_screen_id_ != ScreenCapturer::kInvalidScreenId)
    {
        LOG(LS_INFO) << "Restore selected screen: " << last_screen_id_;
        selectScreen(last_screen_id_, Size());
    }
}

void ScreenCapturerWrapper::switchToInputDesktop()
{
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
#if defined(OS_WIN)
    // Switch to the desktop receiving user input if different from the current one.
    Desktop input_desktop(Desktop::inputDesktop());

    if (input_desktop.isValid() && !desktop_.isSame(input_desktop))
    {
        wchar_t desktop_name[128] = { 0 };
        input_desktop.name(desktop_name, sizeof(desktop_name));

        LOG(LS_INFO) << "Input desktop changed to " << desktop_name;

        if (screen_capturer_)
            screen_capturer_->reset();

        // If setThreadDesktop() fails, the thread is still assigned a desktop.
        // So we can continue capture screen bits, just from the wrong desktop.
        desktop_.setThreadDesktop(std::move(input_desktop));
    }
#endif // defined(OS_WIN)
}

} // namespace base
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

//#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
//# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
//#endif
#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#if HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE

#include "OS2014_nonparametric_convergence_study.hh"

TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {
  nonparametric_convergence_study(/*"nonparametric_convergence_study"*/);
}
TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {
  nonparametric_convergence_study_alternative_summation();
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {
  nonparametric_block_convergence_study("[1 1 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {
  nonparametric_block_convergence_study("[2 2 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {
  nonparametric_block_convergence_study("[4 4 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {
  nonparametric_block_convergence_study("[8 8 1]");
}

#else // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE

TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {}

#endif // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE
<commit_msg>[test...] remove dead code<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#if HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE

#include "OS2014_nonparametric_convergence_study.hh"

TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {
  nonparametric_convergence_study(/*"nonparametric_convergence_study"*/);
}
TEST(OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {
  nonparametric_convergence_study_alternative_summation();
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {
  nonparametric_block_convergence_study("[1 1 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {
  nonparametric_block_convergence_study("[2 2 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {
  nonparametric_block_convergence_study("[4 4 1]");
}
TEST(OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {
  nonparametric_block_convergence_study("[8 8 1]");
}

#else // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE

TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, SWIPDG_fine_triangulation_alternative_summation) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_01_subdomain) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_04_subdomains) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_16_subdomains) {}
TEST(DISABLED_OS2014_nonparametric_convergence_study, Block_SWIPDG_64_subdomains) {}

#endif // HAVE_ALUGRID && HAVE_DUNE_FEM && HAVE_DUNE_GRID_MULTISCALE
<|endoftext|>


<commit_before>#ifndef CONTROL_H
#define CONTROL_H

#include "SPECTYPES.H"

// guessed, some may be wrong on PSX
enum input_buttons
{
	IN_NONE = 0,								// 0x00000000
	IN_FORWARD = (1 << 0),						// 0x00000001
	IN_BACK = (1 << 1),							// 0x00000002
	IN_LEFT = (1 << 2),							// 0x00000004
	IN_RIGHT = (1 << 3),						// 0x00000008
	IN_JUMP = (1 << 4),							// 0x00000010
	IN_DRAW = (1 << 5), // Space / Triangle		// 0x00000020
	IN_ACTION = (1 << 6), // Ctrl / X			// 0x00000040
	IN_WALK = (1 << 7), // Shift / R1			// 0x00000080
	IN_OPTION = (1 << 8),						// 0x00000100
	IN_LOOK = (1 << 9),							// 0x00000200
	IN_LSTEP = (1 << 10),						// 0x00000400
	IN_RSTEP = (1 << 11),						// 0x00000800
	IN_ROLL = (1 << 12), // End / O				// 0x00001000
	IN_PAUSE = (1 << 13),						// 0x00002000
	IN_FLARE = (1 << 19),						// 0x00080000
	IN_SELECT = (1 << 20),						// 0x00100000
	IN_DESELECT = (1 << 21),					// 0x00200000
	IN_SAVE = (1 << 22), // F5					// 0x00400000
	IN_LOAD = (1 << 23),  // F6					// 0x00800000
	IN_DUCK = (1 << 29),						// 0x20000000
	IN_SPRINT = (1 << 30),						// 0x40000000

	IN_ALL = ~0,								// 0xFFFFFFFF (-1)
};

enum flipeffects
{
	FE_ROTATE_180 = 0,
	FE_FLOOR_SHAKE = 1,
	FE_FLOOD_FX = 2,
	FE_LARA_BUBBLES = 3,
	FE_FINISH_LEVEL = 4,

	FE_ACTIVATE_CAMERA = 5,
	FE_ACTIVATE_KEY = 6,

	FE_RUBBLE_FX = 7,
	FE_SWAP_CROWBAR = 8,

	FE_TIMER_FIELD_FX = 10,
	FE_EXPLOSION_FX = 11,
	FE_LARA_HANDSFREE = 12,

	FE_SHOOT_RIGHTGUN = 16,
	FE_SHOOT_LEFTGUN = 17,

	FE_INV_ON = 21,
	FE_INV_OFF = 22,

	FE_RESET_HAIR = 26,
	FE_SETFOG = 28,
	FE_LARALOCATION = 30,
	FE_RESET_TEST = 31,
	FE_FOOTPRINT_FX = 32,
	FE_CLEAR_SPIDERS_PATCH = 33,
	FE_LARALOCATIONPAD = 45,
	FE_KILLACTIVEBADDIES = 46,

	FE_TUT_HINT_1 = 47,
	FE_TUT_HINT_2 = 48,
	FE_TUT_HINT_3 = 49,
	FE_TUT_HINT_4 = 50,
	FE_TUT_HINT_5 = 51,
	FE_TUT_HINT_6 = 52,
	FE_TUT_HINT_7 = 53,
	FE_TUT_HINT_8 = 54,
	FE_TUT_HINT_9 = 55,
	FE_TUT_HINT_10 = 56,
	FE_TUT_HINT_11 = 57,
	FE_TUT_HINT_12 = 58,

	NUM_FLIPEFFECTS
};

extern int flipeffect;
extern int fliptimer;
extern unsigned char ShatterSounds[18][10];
extern unsigned char WeaponDelay;
extern unsigned char KeyTriggerActive;
extern unsigned short GlobalCounter;
extern char TriggerTimer;
extern int reset_flag;
extern short SlowMotion;
extern short SlowMoFrameCount;
extern unsigned char InItemControlLoop;
extern short ItemNewRoomNo;
extern short SmashedMeshCount;
extern char richcutfrigflag;
extern int nRope;
extern char GetLaraOnLOS;
extern int NoInput;
extern int number_los_rooms;
extern long rand_1;
extern int framecount;
extern long rand_2;
extern struct ITEM_INFO* items;
extern int flip_status;
#if PC_VERSION
extern int flipmap[255];
extern int flip_stats[255];
#else
extern int flipmap[10];
extern int flip_stats[10];
#endif
extern int height_type;
extern int tiltxoff;
extern int tiltyoff;
extern unsigned long _CutSceneTriggered1;
extern unsigned long _CutSceneTriggered2;
extern unsigned long FmvSceneTriggered;
extern unsigned char CurrentAtmosphere;
extern unsigned char IsAtmospherePlaying;
extern char* OutsideRoomTable;
extern short* OutsideRoomOffsets;
extern short IsRoomOutsideNo;
extern short FXType;
extern int OnObject;
extern short* trigger_index;
extern char cd_flags[136];
extern unsigned char InGameCnt;
extern struct RAT_STRUCT* Rats;
extern struct BAT_STRUCT* Bats;
extern struct SPIDER_STRUCT* Spiders;
extern struct TWOGUN_INFO twogun[4];
extern int SetDebounce;
extern short WB_room;
extern struct ITEM_INFO* WB_item;
extern unsigned char HeavyTriggered;
extern struct MESH_INFO* SmashedMesh[16];
extern short SmashedMeshRoom[16];
extern struct PENDULUM CurrentPendulum;
extern char LaraDrawType;
extern char WeatherType;
extern char RoomDrawType;
extern struct PHD_VECTOR ClosestCoord;
extern int ClosestItem;
extern int ClosestDist;
extern short XSoff1;
extern short YSoff1;
extern short ZSoff1;
extern short XSoff2;
extern short YSoff2;
extern short ZSoff2;
extern short los_rooms[20];
extern char globoncuttrig;
extern short ItemNewRooms[256][2];
extern struct CHARDEF CharDef[106];
extern struct ROPE_STRUCT Ropes[12];

extern long ControlPhase(long nframes, int demo_mode);
extern long GetRandomControl();
extern void SeedRandomControl(long seed);
extern long GetRandomDraw();
extern void SeedRandomDraw(long seed);
extern void AddRoomFlipItems(struct room_info* r);
extern void KillMoveItems();
extern void KillMoveEffects();
extern void TestTriggers(short* data, int heavy, int HeavyFlags);
extern void ClearFires();
extern void ClearDynamics();
extern int is_object_in_room(int roomnumber, int objnumber);
extern void NeatAndTidyTriggerCutscene(int value, int timer);
extern int CheckCutPlayed(int num);
extern void SetCutNotPlayed(int num);
extern void SetCutPlayed(int num);
extern void InitCutPlayed();
extern void ResetGuards();
extern void InterpolateAngle(short dest, short* src, short* diff, short speed);
extern int CheckGuardOnTrigger();
extern int ExplodeItemNode(struct ITEM_INFO* item, int Node, int NoXZVel, long bits);
extern int GetTargetOnLOS(struct GAME_VECTOR* src, struct GAME_VECTOR* dest, int DrawTarget, int firing);
extern void FireCrossBowFromLaserSight(struct GAME_VECTOR* src, struct GAME_VECTOR* target);
extern void TriggerNormalCDTrack(short value, short flags, short type);
extern void TriggerCDTrack(short value, short flags, short type);
extern void RemoveRoomFlipItems(struct room_info* r);
extern void FlipMap(int FlipNumber);
extern void _TestTriggers(short* data, int heavy, int HeavyFlags);
extern void RefreshCamera(short type, short* data);
extern long GetWaterHeight(long x, long y, long z, short room_number);
extern void AlterFloorHeight(struct ITEM_INFO* item, int height);
extern short GetHeight(struct FLOOR_INFO* floor, int x, int y, int z);
extern struct FLOOR_INFO* GetFloor(int x, int y, int z, short* room_number);
extern short GetCeiling(struct FLOOR_INFO* floor, int x, int y, int z);
extern int TriggerActive(struct ITEM_INFO* item);
extern void AddRoomFlipItems(struct room_info* r);
extern int IsRoomOutside(long x, long y, long z);
extern short GetDoor(struct FLOOR_INFO* floor);
extern int LOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int CheckNoColCeilingTriangle(struct FLOOR_INFO* floor, int x, int z);
extern int CheckNoColFloorTriangle(struct FLOOR_INFO* floor, int x, int z);
extern int ClipTarget(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct FLOOR_INFO* floor);
#ifndef PSX_VERSION || PSXPC_VERSION///@FIXME @pc
extern void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint);
#endif
extern void AddFire(int x, int y, int z, char size, short room_num, short on);
extern int ObjectOnLOS2(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct PHD_VECTOR* a3, struct MESH_INFO** a4);
extern int check_xray_machine_trigger();
extern void AnimateItem(struct ITEM_INFO* item);
extern void UpdateSpiders();

#endif<commit_msg>add additional IN_ constants for debug, step shift, directional look (PSX) and unknown 31<commit_after>#ifndef CONTROL_H
#define CONTROL_H

#include "SPECTYPES.H"

// guessed, some may be wrong on PSX
enum input_buttons
{
	IN_NONE = 0,								// 0x00000000
	IN_FORWARD = (1 << 0),						// 0x00000001
	IN_BACK = (1 << 1),							// 0x00000002
	IN_LEFT = (1 << 2),							// 0x00000004
	IN_RIGHT = (1 << 3),						// 0x00000008
	IN_JUMP = (1 << 4),							// 0x00000010
	IN_DRAW = (1 << 5), // Space / Triangle		// 0x00000020
	IN_ACTION = (1 << 6), // Ctrl / X			// 0x00000040
	IN_WALK = (1 << 7), // Shift / R1			// 0x00000080
	IN_OPTION = (1 << 8),						// 0x00000100
	IN_LOOK = (1 << 9),							// 0x00000200
	IN_LSTEP = (1 << 10),						// 0x00000400
	IN_RSTEP = (1 << 11),						// 0x00000800
	IN_ROLL = (1 << 12), // End / O				// 0x00001000
	IN_PAUSE = (1 << 13),						// 0x00002000
	IN_A = (1 << 14),							// 0x00004000
	IN_B = (1 << 15),							// 0x00008000
	IN_CHEAT = (1 << 16),						// 0x00010000
	IN_D = (1 << 17),							// 0x00020000
	IN_E = (1 << 18),							// 0x00040000
	IN_FLARE = (1 << 19),						// 0x00080000
	IN_SELECT = (1 << 20),						// 0x00100000
	IN_DESELECT = (1 << 21),					// 0x00200000
	IN_SAVE = (1 << 22), // F5					// 0x00400000
	IN_LOAD = (1 << 23),  // F6					// 0x00800000
	IN_STEPSHIFT = (1 << 24),					// 0x01000000
	IN_LOOKLEFT = (1 << 25),					// 0x02000000
	IN_LOOKRIGHT = (1 << 26),					// 0x04000000
	IN_LOOKFORWARD = (1 << 27),					// 0x08000000
	IN_LOOKBACK = (1 << 28),					// 0x10000000
	IN_DUCK = (1 << 29),						// 0x20000000
	IN_SPRINT = (1 << 30),						// 0x40000000
	IN_UNK31 = (1 << 31),						// 0x80000000

	IN_ALL = ~0,								// 0xFFFFFFFF (-1)
};

enum flipeffects
{
	FE_ROTATE_180 = 0,
	FE_FLOOR_SHAKE = 1,
	FE_FLOOD_FX = 2,
	FE_LARA_BUBBLES = 3,
	FE_FINISH_LEVEL = 4,

	FE_ACTIVATE_CAMERA = 5,
	FE_ACTIVATE_KEY = 6,

	FE_RUBBLE_FX = 7,
	FE_SWAP_CROWBAR = 8,

	FE_TIMER_FIELD_FX = 10,
	FE_EXPLOSION_FX = 11,
	FE_LARA_HANDSFREE = 12,

	FE_SHOOT_RIGHTGUN = 16,
	FE_SHOOT_LEFTGUN = 17,

	FE_INV_ON = 21,
	FE_INV_OFF = 22,

	FE_RESET_HAIR = 26,
	FE_SETFOG = 28,
	FE_LARALOCATION = 30,
	FE_RESET_TEST = 31,
	FE_FOOTPRINT_FX = 32,
	FE_CLEAR_SPIDERS_PATCH = 33,
	FE_LARALOCATIONPAD = 45,
	FE_KILLACTIVEBADDIES = 46,

	FE_TUT_HINT_1 = 47,
	FE_TUT_HINT_2 = 48,
	FE_TUT_HINT_3 = 49,
	FE_TUT_HINT_4 = 50,
	FE_TUT_HINT_5 = 51,
	FE_TUT_HINT_6 = 52,
	FE_TUT_HINT_7 = 53,
	FE_TUT_HINT_8 = 54,
	FE_TUT_HINT_9 = 55,
	FE_TUT_HINT_10 = 56,
	FE_TUT_HINT_11 = 57,
	FE_TUT_HINT_12 = 58,

	NUM_FLIPEFFECTS
};

extern int flipeffect;
extern int fliptimer;
extern unsigned char ShatterSounds[18][10];
extern unsigned char WeaponDelay;
extern unsigned char KeyTriggerActive;
extern unsigned short GlobalCounter;
extern char TriggerTimer;
extern int reset_flag;
extern short SlowMotion;
extern short SlowMoFrameCount;
extern unsigned char InItemControlLoop;
extern short ItemNewRoomNo;
extern short SmashedMeshCount;
extern char richcutfrigflag;
extern int nRope;
extern char GetLaraOnLOS;
extern int NoInput;
extern int number_los_rooms;
extern long rand_1;
extern int framecount;
extern long rand_2;
extern struct ITEM_INFO* items;
extern int flip_status;
#if PC_VERSION
extern int flipmap[255];
extern int flip_stats[255];
#else
extern int flipmap[10];
extern int flip_stats[10];
#endif
extern int height_type;
extern int tiltxoff;
extern int tiltyoff;
extern unsigned long _CutSceneTriggered1;
extern unsigned long _CutSceneTriggered2;
extern unsigned long FmvSceneTriggered;
extern unsigned char CurrentAtmosphere;
extern unsigned char IsAtmospherePlaying;
extern char* OutsideRoomTable;
extern short* OutsideRoomOffsets;
extern short IsRoomOutsideNo;
extern short FXType;
extern int OnObject;
extern short* trigger_index;
extern char cd_flags[136];
extern unsigned char InGameCnt;
extern struct RAT_STRUCT* Rats;
extern struct BAT_STRUCT* Bats;
extern struct SPIDER_STRUCT* Spiders;
extern struct TWOGUN_INFO twogun[4];
extern int SetDebounce;
extern short WB_room;
extern struct ITEM_INFO* WB_item;
extern unsigned char HeavyTriggered;
extern struct MESH_INFO* SmashedMesh[16];
extern short SmashedMeshRoom[16];
extern struct PENDULUM CurrentPendulum;
extern char LaraDrawType;
extern char WeatherType;
extern char RoomDrawType;
extern struct PHD_VECTOR ClosestCoord;
extern int ClosestItem;
extern int ClosestDist;
extern short XSoff1;
extern short YSoff1;
extern short ZSoff1;
extern short XSoff2;
extern short YSoff2;
extern short ZSoff2;
extern short los_rooms[20];
extern char globoncuttrig;
extern short ItemNewRooms[256][2];
extern struct CHARDEF CharDef[106];
extern struct ROPE_STRUCT Ropes[12];

extern long ControlPhase(long nframes, int demo_mode);
extern long GetRandomControl();
extern void SeedRandomControl(long seed);
extern long GetRandomDraw();
extern void SeedRandomDraw(long seed);
extern void AddRoomFlipItems(struct room_info* r);
extern void KillMoveItems();
extern void KillMoveEffects();
extern void TestTriggers(short* data, int heavy, int HeavyFlags);
extern void ClearFires();
extern void ClearDynamics();
extern int is_object_in_room(int roomnumber, int objnumber);
extern void NeatAndTidyTriggerCutscene(int value, int timer);
extern int CheckCutPlayed(int num);
extern void SetCutNotPlayed(int num);
extern void SetCutPlayed(int num);
extern void InitCutPlayed();
extern void ResetGuards();
extern void InterpolateAngle(short dest, short* src, short* diff, short speed);
extern int CheckGuardOnTrigger();
extern int ExplodeItemNode(struct ITEM_INFO* item, int Node, int NoXZVel, long bits);
extern int GetTargetOnLOS(struct GAME_VECTOR* src, struct GAME_VECTOR* dest, int DrawTarget, int firing);
extern void FireCrossBowFromLaserSight(struct GAME_VECTOR* src, struct GAME_VECTOR* target);
extern void TriggerNormalCDTrack(short value, short flags, short type);
extern void TriggerCDTrack(short value, short flags, short type);
extern void RemoveRoomFlipItems(struct room_info* r);
extern void FlipMap(int FlipNumber);
extern void _TestTriggers(short* data, int heavy, int HeavyFlags);
extern void RefreshCamera(short type, short* data);
extern long GetWaterHeight(long x, long y, long z, short room_number);
extern void AlterFloorHeight(struct ITEM_INFO* item, int height);
extern short GetHeight(struct FLOOR_INFO* floor, int x, int y, int z);
extern struct FLOOR_INFO* GetFloor(int x, int y, int z, short* room_number);
extern short GetCeiling(struct FLOOR_INFO* floor, int x, int y, int z);
extern int TriggerActive(struct ITEM_INFO* item);
extern void AddRoomFlipItems(struct room_info* r);
extern int IsRoomOutside(long x, long y, long z);
extern short GetDoor(struct FLOOR_INFO* floor);
extern int LOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int xLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int zLOS(struct GAME_VECTOR* start, struct GAME_VECTOR* target);
extern int CheckNoColCeilingTriangle(struct FLOOR_INFO* floor, int x, int z);
extern int CheckNoColFloorTriangle(struct FLOOR_INFO* floor, int x, int z);
extern int ClipTarget(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct FLOOR_INFO* floor);
#ifndef PSX_VERSION || PSXPC_VERSION///@FIXME @pc
extern void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint);
#endif
extern void AddFire(int x, int y, int z, char size, short room_num, short on);
extern int ObjectOnLOS2(struct GAME_VECTOR* start, struct GAME_VECTOR* target, struct PHD_VECTOR* a3, struct MESH_INFO** a4);
extern int check_xray_machine_trigger();
extern void AnimateItem(struct ITEM_INFO* item);
extern void UpdateSpiders();

#endif<|endoftext|>


<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in

M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013

In a publication based on this software pleace cite the above reference.

Copyright (C) 2014  Manuel Wuthrich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/

#ifndef MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP
#define MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP

#include <vector>
#include <state_filtering/distributions/distribution.hpp>

namespace distributions
{
template<typename ScalarType_, typename StateType_, typename ObservationType_, typename IndexType_ = size_t>
class RaoBlackwellObserver: public Distribution<ScalarType_, StateType_>
{
public:
    typedef typename Distribution<ScalarType_, StateType_>::ScalarType     ScalarType;
    typedef typename Distribution<ScalarType_, StateType_>::VectorType     StateType;
    typedef ObservationType_                                                ObservationType;
    typedef IndexType_                                                      IndexType;
 public:
    virtual ~RaoBlackwellObserver() {}

    // since we can not implicitly cast a vector globally we do it here locally
    template<typename Type>
    std::vector<ScalarType> Loglikes(const std::vector<Type>&  states,
                                     std::vector<IndexType>&   indices,
                                     const bool&               update = false)
    {
        std::vector<const StateType*>  state_pointers(states.size());
        for(IndexType i = 0; i < states.size(); i++)
        {
            state_pointers[i] = &(states[i]);
        }

        return Loglikes(state_pointers, indices, update);
    }
    virtual std::vector<ScalarType> Loglikes(const std::vector<const StateType*>&  states,
                                             std::vector<IndexType>&   indices,
                                             const bool&               update = false) = 0;

    virtual void Observation(const ObservationType& image, const ScalarType& delta_time) = 0;

    // reset the latent variables
    virtual void Reset() = 0;
};

}
#endif
<commit_msg>- Uses ::sf namespace & removed distribution namespace. - Removed ScalarType_ template parameter since it's encoded in the STate type - Omitted suffix "Type" since it does not provide any further meaning.<commit_after>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in

M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013

In a publication based on this software pleace cite the above reference.

Copyright (C) 2014  Manuel Wuthrich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/

#ifndef MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP
#define MODELS_OBSERVERS_FEATURES_RAO_BLACKWELL_observer_HPP

#include <vector>
#include <state_filtering/utils/traits.hpp>

namespace sf
{
template<typename State, typename Observation_, typename Index_ = size_t>
class RaoBlackwellObserver
{
public:
    typedef typename internal::VectorTraits<State>::Scalar Scalar;
    typedef Index_        Index;
    typedef Observation_  Observation;

public:
    virtual ~RaoBlackwellObserver() {}

    // since we can not implicitly cast a vector globally we do it here locally
    virtual std::vector<Scalar> Loglikes(const std::vector<State>&  states,
                                     std::vector<Index>&   indices,
                                     const bool&               update = false)
    {
        std::vector<const State*>  state_pointers(states.size());
        for(Index i = 0; i < states.size(); i++)
        {
            state_pointers[i] = &(states[i]);
        }

        return Loglikes_(state_pointers, indices, update);
    }

    /* TODO fix this overloading hack */
    virtual std::vector<Scalar> Loglikes_(const std::vector<const State*>&  states,
                                             std::vector<Index>&   indices,
                                             const bool&               update = false) = 0;

    virtual void SetObservation(const Observation& image, const Scalar& delta_time) = 0;

    // reset the latent variables
    virtual void Reset() = 0;
};

}
#endif
<|endoftext|>


<commit_before>#include "SequentialEventDispatcher.hpp"

#include <memory>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>

#include "Event.hpp"
#include "EventStatistics.hpp"
#include "SimulationObject.hpp"
#include "STLLTSFQueue.hpp"

namespace warped {

SequentialEventDispatcher::SequentialEventDispatcher(unsigned int max_sim_time,
                                                     std::unique_ptr<EventStatistics> stats)
    : EventDispatcher(max_sim_time), stats_(std::move(stats)) {}

void SequentialEventDispatcher::startSimulation(
    const std::vector<std::vector<SimulationObject*>>& objects) {
    if (objects.size() != 1) {
        throw std::runtime_error(std::string("Sequential simualtion only supports 1 partition."));
    }

    std::unordered_map<std::string, SimulationObject*> objects_by_name;
    STLLTSFQueue events;
    unsigned int current_sim_time = 0;

    for (auto& ob : objects[0]) {
        auto new_events = ob->createInitialEvents();
        stats_->record(ob->name_, current_sim_time, new_events);
        events.push(std::move(new_events));
        objects_by_name[ob->name_] = ob;
    }

    while (current_sim_time < max_sim_time_ && !events.empty()) {
        auto event = events.pop();
        current_sim_time = event->timestamp();
        auto receiver = objects_by_name[event->receiverName()];
        auto new_events = receiver->receiveEvent(*event.get());
        stats_->record(event->receiverName(), current_sim_time, new_events);
        events.push(std::move(new_events));
    }

    stats_->writeToFile();
}

} // namespace warped<commit_msg>Fixed typo<commit_after>#include "SequentialEventDispatcher.hpp"

#include <memory>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>

#include "Event.hpp"
#include "EventStatistics.hpp"
#include "SimulationObject.hpp"
#include "STLLTSFQueue.hpp"

namespace warped {

SequentialEventDispatcher::SequentialEventDispatcher(unsigned int max_sim_time,
                                                     std::unique_ptr<EventStatistics> stats)
    : EventDispatcher(max_sim_time), stats_(std::move(stats)) {}

void SequentialEventDispatcher::startSimulation(
    const std::vector<std::vector<SimulationObject*>>& objects) {
    if (objects.size() != 1) {
        throw std::runtime_error(std::string("Sequential simulation only supports 1 partition."));
    }

    std::unordered_map<std::string, SimulationObject*> objects_by_name;
    STLLTSFQueue events;
    unsigned int current_sim_time = 0;

    for (auto& ob : objects[0]) {
        auto new_events = ob->createInitialEvents();
        stats_->record(ob->name_, current_sim_time, new_events);
        events.push(std::move(new_events));
        objects_by_name[ob->name_] = ob;
    }

    while (current_sim_time < max_sim_time_ && !events.empty()) {
        auto event = events.pop();
        current_sim_time = event->timestamp();
        auto receiver = objects_by_name[event->receiverName()];
        auto new_events = receiver->receiveEvent(*event.get());
        stats_->record(event->receiverName(), current_sim_time, new_events);
        events.push(std::move(new_events));
    }

    stats_->writeToFile();
}

} // namespace warped<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVersorTransformOptimizer.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#ifndef _itkVersorTransformOptimizer_txx
#define _itkVersorTransformOptimizer_txx

#include "itkVersorTransformOptimizer.h"
#include "vnl/vnl_quaternion.h"
#include "itkEventObject.h"

namespace itk
{

/**
 * Advance one Step following the gradient direction
 * This method will be overrided in non-vector spaces
 */
void
VersorTransformOptimizer
::StepAlongGradient( double factor,
                     const DerivativeType & transformedGradient )
{

  const ParametersType & currentPosition = GetCurrentPosition();

  // The parameters are assumed to be the right part of the versor
  //
  VectorType rightPart;
  for(unsigned int i=0; i<SpaceDimension; i++)
    {
    rightPart[i] = currentPosition[i];
    }

  VersorType currentRotation;
  currentRotation.Set( rightPart );

  // The gradient indicate the contribution of each one
  // of the axis to the direction of highest change in
  // the function
  VectorType   axis;
  axis[0] = transformedGradient[0];
  axis[1] = transformedGradient[1];
  axis[2] = transformedGradient[2];

  // gradientRotation is a rotation along the
  // versor direction which maximize the
  // variation of the cost function in question.
  // An additional Exponentiation produce a jump
  // of a particular length along the versor gradient
  // direction.

  VersorType gradientRotation;
  gradientRotation.Set( axis, factor * axis.GetNorm() );

  //
  // Composing the currentRotation with the gradientRotation
  // produces the new Rotation versor
  //
  VersorType newRotation = currentRotation * gradientRotation;

  ParametersType newParameters(SpaceDimension);

  newParameters[0] = newRotation.GetX();
  newParameters[1] = newRotation.GetY();
  newParameters[2] = newRotation.GetZ();

  this->SetCurrentPosition( newParameters );

}

} // end namespace itk

#endif
<commit_msg>STY: use of "this->" for invoking member functions.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVersorTransformOptimizer.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#ifndef _itkVersorTransformOptimizer_txx
#define _itkVersorTransformOptimizer_txx

#include "itkVersorTransformOptimizer.h"
#include "vnl/vnl_quaternion.h"
#include "itkEventObject.h"

namespace itk
{

/**
 * Advance one Step following the gradient direction
 * This method will be overrided in non-vector spaces
 */
void
VersorTransformOptimizer
::StepAlongGradient( double factor,
                     const DerivativeType & transformedGradient )
{

  const ParametersType & currentPosition = this->GetCurrentPosition();

  // The parameters are assumed to be the right part of the versor
  //
  VectorType rightPart;
  for(unsigned int i=0; i<SpaceDimension; i++)
    {
    rightPart[i] = currentPosition[i];
    }

  VersorType currentRotation;
  currentRotation.Set( rightPart );

  // The gradient indicate the contribution of each one
  // of the axis to the direction of highest change in
  // the function
  VectorType   axis;
  axis[0] = transformedGradient[0];
  axis[1] = transformedGradient[1];
  axis[2] = transformedGradient[2];

  // gradientRotation is a rotation along the
  // versor direction which maximize the
  // variation of the cost function in question.
  // An additional Exponentiation produce a jump
  // of a particular length along the versor gradient
  // direction.

  VersorType gradientRotation;
  gradientRotation.Set( axis, factor * axis.GetNorm() );

  //
  // Composing the currentRotation with the gradientRotation
  // produces the new Rotation versor
  //
  VersorType newRotation = currentRotation * gradientRotation;

  ParametersType newParameters(SpaceDimension);

  newParameters[0] = newRotation.GetX();
  newParameters[1] = newRotation.GetY();
  newParameters[2] = newRotation.GetZ();

  this->SetCurrentPosition( newParameters );

}

} // end namespace itk

#endif
<|endoftext|>