<commit_before>#include "Get.hh"

#include <fstream>
#include "Config.hh"

ss::methods::Get::Get(const http::Request& request, http::Response* response) : request(request)
{
	create_correct_location();
	auto file = read_file(correct_location);
	if (file.empty())
	{
		response->headers["code"] = "404";
		response->headers["code_message"] = "Not Found";
		response->headers["Content-Length:"] = 15;
		response->message = "404 - Not Found";
	}
	else
	{
		response->headers["Content-Type"] = mime_type(correct_location);
		response->headers["code"] = "200";
		response->headers["code_message"] = "OK";
		response->headers["Content-Length:"] = file.size();
		response->message = file;
	}
}

std::string ss::methods::Get::mime_type(const std::string& location)
{
	auto split_pos = location.find_last_of('.');
	if (split_pos == std::string::npos)
	{
		return "text/plain";
	}
	else
	{
		auto extention = location.substr(split_pos + 1);

		// For testing purposes
		if (extention == "cc")
		{
			return "text/html";
		}
		else
		{
			return "text/plain";
		}
	}
}

std::string ss::methods::Get::read_file(const std::string& location)
{
	std::ifstream file(location);
	if (!file.is_open())
	{
		return "";
	}

	file.seekg(0, std::ios::end);
	auto size = file.tellg();
	std::string contents(static_cast<unsigned int>(size), ' ');
	file.seekg(0, std::ios::beg);
	file.read(&contents[0], size);

	return contents;
}

void ss::methods::Get::create_correct_location()
{
	const auto host = request.headers.at("Host");
	// Check if Host header contains a port.
	const auto port_pos = host.find_last_of(":");
	if (port_pos == std::string::npos)
	{
		correct_location = (Config::get_sites()[host] + request.headers.at("location").substr(1));
	}
	else
	{
		correct_location = (Config::get_sites()[host.substr(0, port_pos)] + request.headers.at("location").substr(1));
	}
}
<commit_msg>Add default index file for Get requests<commit_after>#include "Get.hh"

#include <fstream>
#include "Config.hh"

ss::methods::Get::Get(const http::Request& request, http::Response* response) : request(request)
{
	create_correct_location();
	auto file = read_file(correct_location);
	if (file.empty())
	{
		response->headers["code"] = "404";
		response->headers["code_message"] = "Not Found";
		response->headers["Content-Length:"] = 15;
		response->message = "404 - Not Found";
	}
	else
	{
		response->headers["Content-Type"] = mime_type(correct_location);
		response->headers["code"] = "200";
		response->headers["code_message"] = "OK";
		response->headers["Content-Length:"] = file.size();
		response->message = file;
	}
}

std::string ss::methods::Get::mime_type(const std::string& location)
{
	auto split_pos = location.find_last_of('.');
	if (split_pos == std::string::npos)
	{
		return "text/plain";
	}
	else
	{
		auto extention = location.substr(split_pos + 1);

		// For testing purposes
		if (extention == "cc")
		{
			return "text/html";
		}
		else
		{
			return "text/plain";
		}
	}
}

std::string ss::methods::Get::read_file(const std::string& location)
{
	std::ifstream file(location);
	if (!file.is_open())
	{
		return "";
	}

	file.seekg(0, std::ios::end);
	auto size = file.tellg();
	std::string contents(static_cast<unsigned int>(size), ' ');
	file.seekg(0, std::ios::beg);
	file.read(&contents[0], size);

	return contents;
}

void ss::methods::Get::create_correct_location()
{
	const auto host = request.headers.at("Host");

	std::string req_location;
	if (request.headers.at("location").back() == '/')
	{
		// Using Makefile just for testing purposes
		req_location = request.headers.at("location").substr(1) + "Makefile";
	}
	else
	{
		req_location = request.headers.at("location").substr(1);
	}

	// Check if Host header contains a port.
	const auto port_pos = host.find_last_of(":");
	if (port_pos == std::string::npos)
	{
		correct_location = (Config::get_sites()[host] + req_location);
	}
	else
	{
		correct_location = (Config::get_sites()[host.substr(0, port_pos)] + req_location);
	}
}
<|endoftext|>


<commit_before>
#include "config.h"

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-grid-multiscale
#include <dune/grid/multiscale/provider/cube.hh>

// dune-fem
#include <dune/fem/misc/mpimanager.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.ms.semicg.ddd";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[grid.multiscale.provider.cube]" << std::endl;
    file << "level = 4" << std::endl;
    file << "boundaryId = 7" << std::endl;                  // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
    file << "partitions.0 = 2" << std::endl;
    file << "partitions.1 = 2" << std::endl;
    file << "partitions.2 = 2" << std::endl;
    file << "filename = " << id << ".msGrid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0" << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression.0 = 1.0"  << std::endl;
    file << "diffusion.expression.1 = 1.0"  << std::endl;
    file << "diffusion.expression.2 = 1.0"  << std::endl;
    file << "force.order = 0" << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
    file << "discretization.penaltyFactor = 10.0" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id, id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
    typedef GridProviderType::MsGridType MsGridType;
    const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr();
    info << "  took " << timer.elapsed()
         << " sec (has " << gridProvider.grid().size(0) << " elements, "
         << msGrid->size() << " subdomains)" << std::endl;
    debug.resume();
    info << "visualizing grid... " << std::flush;
    timer.reset();
    debug.suspend();
    msGrid->visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_msGrid"));
    info << "done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    debug.suspend();
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id())));
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    // solver
    info << "initializing solver";
    info << ":" << std::endl;
//    info << "... " << std::flush;
//    debug.suspend();
//    timer.reset();
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations<
        ModelType,
        MsGridType,
        BoundaryInfoType,
        polOrder > SolverType;
    paramTree.assertSub(SolverType::id, id);
    SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id));
    solver.init("  ", debug);
//    debug.resume();
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "solving";
    info << ":" << std::endl;
//    info << "... " << std::flush;
//    debug.suspend();
//    timer.reset();
    typedef SolverType::VectorBackendType VectorType;
    Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), "  ", debug);
//    debug.resume();
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "postprocessing";
    info << ":" << std::endl;
//    info << "... " << std::flush;
//    debug.suspend();
//    timer.reset();
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution"),
                     paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);
//    debug.resume();
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples...elliptic.multiscale...] added first draft on some error computation<commit_after>#include "config.h"

// system
#include <vector>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-grid-multiscale
#include <dune/grid/multiscale/provider/cube.hh>

// dune-fem
#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/misc/gridwidth.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/discretefunction/norm.hh>
#include <dune/stuff/function/expression.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.ms.semicg.ddd";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "exact_solution.order = 2" << std::endl;
    file << "exact_solution.variable = x" << std::endl;
    file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl;
    file << "[grid.multiscale.provider.cube]" << std::endl;
    file << "level = 4" << std::endl;
    file << "boundaryId = 7" << std::endl;                  // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
    file << "partitions.0 = 2" << std::endl;
    file << "partitions.1 = 2" << std::endl;
    file << "partitions.2 = 2" << std::endl;
    file << "filename = " << id << ".msGrid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0" << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression.0 = 1.0"  << std::endl;
    file << "diffusion.expression.1 = 1.0"  << std::endl;
    file << "diffusion.expression.2 = 1.0"  << std::endl;
    file << "force.order = 0" << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
    file << "discretization.penaltyFactor = 10.0" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class MultiscaleDiscreteFunctionType,
          class OutStreamType >
void compute_errors(Dune::ParameterTree& paramTree,
                    const MultiscaleDiscreteFunctionType& discreteFunction,
                    OutStreamType& out,
                    std::string prefix = "")
{
  // exact solution
  typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType;
  typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType;
  typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType;
  typedef Dune::Stuff::Function::Expression<
      DomainFieldType,
      DiscreteFunctionType::dimDomain,
      RangeFieldType,
      DiscreteFunctionType::dimRange >
    FunctionType;
  const FunctionType function(paramTree);
  const unsigned int functionOrder = paramTree.get("order", 100);
  // compute norms
  out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
  const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()),
                                                                               function,
                                                                               functionOrder);
  out.precision(2);
  out << prefix << "   L2 | " << std::setw(14) << std::scientific << L2_reference_norm
                                      << " | " << std::flush;
  const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction);
  out << std::setw(17) << std::scientific << L2_discrete_norm
                                                          << " | " << std::flush;
  const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction);
  out << std::setw(11) << std::scientific << L2_difference
                                                                        << " | " << std::flush;
  out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
//  const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution);
//  out.precision(2);
//  out << prefix << "   h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush;
//  const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution);
//  out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush;
//  const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution);
//  out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush;
//  out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl;
//  out << prefix << "------+-----------+------------+-------------+-------------" << std::endl;
} // void compute_norms(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
//    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    std::ostream& info = std::cout;
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id, id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
    typedef GridProviderType::MsGridType MsGridType;
    const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr();
    info << "  took " << timer.elapsed()
         << " sec (has " << gridProvider.grid().size(0) << " elements, "
         << msGrid->size() << " subdomain";
    if (msGrid->size() > 1)
      info << "s";
    info << " and a width of "
         << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl;
    debug.resume();
    info << "visualizing grid... " << std::flush;
    timer.reset();
    debug.suspend();
    msGrid->visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_msGrid"));
    info << "done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    info << "setting up model... " << std::flush;
    debug.suspend();
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id())));
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    // solver
    info << "initializing solver";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations<
        ModelType,
        MsGridType,
        BoundaryInfoType,
        polOrder > SolverType;
    paramTree.assertSub(SolverType::id, id);
    SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id));
    solver.init("  ", debug);
    debug.resume();
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "solving";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef SolverType::VectorBackendType VectorType;
    Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector();
    solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), "  ", debug);
    debug.resume();
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

//    info << "computing detailed reference solution... " << std::flush;
//    debug.suspend();
//    timer.reset();
//    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations<
//        ModelType,
//        typename MsGridType::GlobalGridPartType,
//        BoundaryInfoType,
//        polOrder >
//      ReferenceSolverType;
//    ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo);
//    referenceSolver.init();
//    Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector();
//    referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), "  ", debug);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
//    debug.resume();

    info << "postprocessing";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    solver.visualize(*solution,
                     paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution"),
                     paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);
//    referenceSolver.visualize(*referenceSolution,
//                              paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference",
//                              paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference",
//                              "  ",
//                              debug);
    debug.resume();
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    info << "computing norms:" << std::endl;
    Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution");
    compute_errors(paramTree.sub(id).sub("exact_solution"),
                   *discreteSolution,
                   info, "  ");
    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


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

#ifndef _LINGU2_HYPHENIMP_HXX_
#define _LINGU2_HYPHENIMP_HXX_

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase6.hxx> // helper for implementations

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_
#include <com/sun/star/lang/XServiceDisplayName.hpp>
#endif
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XHyphenator.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>

#ifndef _TOOLS_TABLE_HXX
#include <tools/table.hxx>
#endif

#include <linguistic/misc.hxx>
#include "hprophelp.hxx"
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

#define A2OU(x) ::rtl::OUString::createFromAscii( x )

#define OU2A(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()

#define OU2UTF8(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()

#define OU2ISO_1(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()

#define OU2ENC(rtlOUString, rtlEncoding)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()

///////////////////////////////////////////////////////////////////////////

struct HDInfo {
  HyphenDict *     aPtr;
  OUString         aName;
  Locale           aLoc;
  rtl_TextEncoding aEnc;
};

class Hyphenator :
    public cppu::WeakImplHelper6
    <
        XHyphenator,
        XLinguServiceEventBroadcaster,
        XInitialization,
        XComponent,
        XServiceInfo,
        XServiceDisplayName
    >
{
    Sequence< Locale >                      aSuppLocales;
        HDInfo * aDicts;
        sal_Int32 numdict;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    Reference< XPropertyChangeListener >    xPropHelper;
    Reference< XMultiServiceFactory > rSMgr;
    PropertyHelper_Hyphen *                 pPropHelper;
    BOOL                                    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    Hyphenator(const Hyphenator &);
    Hyphenator & operator = (const Hyphenator &);

    PropertyHelper_Hyphen & GetPropHelper_Impl();
    PropertyHelper_Hyphen & GetPropHelper()
    {
        return pPropHelper ? *pPropHelper : GetPropHelper_Impl();
    }

public:
    Hyphenator();

    virtual ~Hyphenator();

    // XSupportedLocales (for XHyphenator)
    virtual Sequence< Locale > SAL_CALL getLocales()
        throw(RuntimeException);
    virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )
        throw(RuntimeException);

    // XHyphenator
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    hyphenate( const ::rtl::OUString& aWord,
           const ::com::sun::star::lang::Locale& aLocale,
           sal_Int16 nMaxLeading,
           const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    queryAlternativeSpelling( const ::rtl::OUString& aWord,
                  const ::com::sun::star::lang::Locale& aLocale,
                  sal_Int16 nIndex,
                  const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL
    createPossibleHyphens( const ::rtl::OUString& aWord,
                   const ::com::sun::star::lang::Locale& aLocale,
                   const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    // XLinguServiceEventBroadcaster
    virtual sal_Bool SAL_CALL
        addLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        removeLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);

    // XServiceDisplayName
    virtual OUString SAL_CALL
        getServiceDisplayName( const Locale& rLocale )
            throw(RuntimeException);

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

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(RuntimeException);
    virtual void SAL_CALL
        addEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

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

    static inline OUString
        getImplementationName_Static() throw();
    static Sequence< OUString >
        getSupportedServiceNames_Static() throw();
};

inline OUString Hyphenator::getImplementationName_Static() throw()
{
    return A2OU( "org.openoffice.lingu.LibHnjHyphenator" );
}

///////////////////////////////////////////////////////////////////////////

#endif

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

#ifndef _LINGU2_HYPHENIMP_HXX_
#define _LINGU2_HYPHENIMP_HXX_

#include <uno/lbnames.h>            // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase1.hxx> // helper for implementations
#include <cppuhelper/implbase6.hxx> // helper for implementations

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_
#include <com/sun/star/lang/XServiceDisplayName.hpp>
#endif
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/PropertyValues.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/linguistic2/XHyphenator.hpp>
#include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp>
#include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp>

#ifndef _TOOLS_TABLE_HXX
#include <tools/table.hxx>
#endif

#include <unotools/charclass.hxx>

#include <linguistic/misc.hxx>
#include "hprophelp.hxx"
#include <stdio.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

#define A2OU(x) ::rtl::OUString::createFromAscii( x )

#define OU2A(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()

#define OU2UTF8(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()

#define OU2ISO_1(rtlOUString)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()

#define OU2ENC(rtlOUString, rtlEncoding)     ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()

///////////////////////////////////////////////////////////////////////////

struct HDInfo {
  HyphenDict *     aPtr;
  OUString         aName;
  Locale           aLoc;
  rtl_TextEncoding aEnc;
  CharClass *      apCC;
};

class Hyphenator :
    public cppu::WeakImplHelper6
    <
        XHyphenator,
        XLinguServiceEventBroadcaster,
        XInitialization,
        XComponent,
        XServiceInfo,
        XServiceDisplayName
    >
{
    Sequence< Locale >                      aSuppLocales;
        HDInfo * aDicts;
        sal_Int32 numdict;

    ::cppu::OInterfaceContainerHelper       aEvtListeners;
    Reference< XPropertyChangeListener >    xPropHelper;
    Reference< XMultiServiceFactory > rSMgr;
    PropertyHelper_Hyphen *                 pPropHelper;
    BOOL                                    bDisposing;

    // disallow copy-constructor and assignment-operator for now
    Hyphenator(const Hyphenator &);
    Hyphenator & operator = (const Hyphenator &);

    PropertyHelper_Hyphen & GetPropHelper_Impl();
    PropertyHelper_Hyphen & GetPropHelper()
    {
        return pPropHelper ? *pPropHelper : GetPropHelper_Impl();
    }

public:
    Hyphenator();

    virtual ~Hyphenator();

    // XSupportedLocales (for XHyphenator)
    virtual Sequence< Locale > SAL_CALL getLocales()
        throw(RuntimeException);
    virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )
        throw(RuntimeException);

    // XHyphenator
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    hyphenate( const ::rtl::OUString& aWord,
           const ::com::sun::star::lang::Locale& aLocale,
           sal_Int16 nMaxLeading,
           const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL
    queryAlternativeSpelling( const ::rtl::OUString& aWord,
                  const ::com::sun::star::lang::Locale& aLocale,
                  sal_Int16 nIndex,
                  const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL
    createPossibleHyphens( const ::rtl::OUString& aWord,
                   const ::com::sun::star::lang::Locale& aLocale,
                   const ::com::sun::star::beans::PropertyValues& aProperties )
        throw(::com::sun::star::lang::IllegalArgumentException,
              ::com::sun::star::uno::RuntimeException);

    // XLinguServiceEventBroadcaster
    virtual sal_Bool SAL_CALL
        addLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);
    virtual sal_Bool SAL_CALL
        removeLinguServiceEventListener(
            const Reference< XLinguServiceEventListener >& rxLstnr )
            throw(RuntimeException);

    // XServiceDisplayName
    virtual OUString SAL_CALL
        getServiceDisplayName( const Locale& rLocale )
            throw(RuntimeException);

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

    // XComponent
    virtual void SAL_CALL
        dispose()
            throw(RuntimeException);
    virtual void SAL_CALL
        addEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);
    virtual void SAL_CALL
        removeEventListener( const Reference< XEventListener >& rxListener )
            throw(RuntimeException);

    ////////////////////////////////////////////////////////////
    // Service specific part
    //

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

    static inline OUString
        getImplementationName_Static() throw();
    static Sequence< OUString >
        getSupportedServiceNames_Static() throw();

private:
        OUString SAL_CALL makeLowerCase(const OUString&, CharClass *);

};

inline OUString Hyphenator::getImplementationName_Static() throw()
{
    return A2OU( "org.openoffice.lingu.LibHnjHyphenator" );
}

///////////////////////////////////////////////////////////////////////////

#endif

<|endoftext|>


<commit_before>#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#include <sys/utsname.h>
#include <unistd.h>

namespace {
  int
  os_major_version(void)
  {
    struct utsname un;
    if (uname(&un) != 0) {
      return -1;
    }

    std::string release(un.release);
    auto pos = release.find('.');
    if (pos == std::string::npos) {
      return -1;
    }

    return boost::lexical_cast<int>(release.substr(0, pos));
  }

  void
  usage(void)
  {
    std::cout << "Usage: kextload {load|unload}" << std::endl;
    exit(1);
  }
}

int
main(int argc, const char* argv[])
{
  if (argc != 2) {
    usage();
  }

  std::string command;
  std::string argument(argv[1]);

  if (argument == "load") {
    int major = os_major_version();
    switch (major) {
      case 12: // OS X 10.8
        command = "/sbin/kextload '/Applications/PCKeyboardHack.app/Contents/Library/PCKeyboardHack.10.8.kext'";
        break;
      case 13: // OS X 10.9
        command = "/sbin/kextload '/Applications/PCKeyboardHack.app/Contents/Library/PCKeyboardHack.10.9.signed.kext'";
        break;
      case 14: // OS X 10.10 (XXX: provisional support of OS X 10.10)
        command = "/sbin/kextload '/Applications/PCKeyboardHack.app/Contents/Library/PCKeyboardHack.10.9.signed.kext'";
        break;
      default:
        std::cerr << "Unknown os major version: " << major << std::endl;
        exit(1);
    }

  } else if (argument == "unload") {
    command = "/sbin/kextunload -b org.pqrs.driver.PCKeyboardHack";
  } else {
    usage();
  }

  // We need to call setuid in order to Execute command as root.
  // (rwsr-xr-x permission changes only euid (geteuid). So, we need to change uid by hand.)
  if (setuid(0) != 0) {
    std::cerr << "Failed to setuid(0)." << std::endl;
    exit(1);
  }
  return system(command.c_str());
}
<commit_msg>rename<commit_after>#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#include <sys/utsname.h>
#include <unistd.h>

namespace {
  int
  os_major_version(void)
  {
    struct utsname un;
    if (uname(&un) != 0) {
      return -1;
    }

    std::string release(un.release);
    auto pos = release.find('.');
    if (pos == std::string::npos) {
      return -1;
    }

    return boost::lexical_cast<int>(release.substr(0, pos));
  }

  void
  usage(void)
  {
    std::cout << "Usage: kextload {load|unload}" << std::endl;
    exit(1);
  }
}

int
main(int argc, const char* argv[])
{
  if (argc != 2) {
    usage();
  }

  std::string command;
  std::string argument(argv[1]);

  if (argument == "load") {
    int major = os_major_version();
    switch (major) {
      case 12: // OS X 10.8
        command = "/sbin/kextload '/Applications/Seil.app/Contents/Library/Seil.10.8.kext'";
        break;
      case 13: // OS X 10.9
        command = "/sbin/kextload '/Applications/Seil.app/Contents/Library/Seil.10.9.signed.kext'";
        break;
      case 14: // OS X 10.10 (XXX: provisional support of OS X 10.10)
        command = "/sbin/kextload '/Applications/Seil.app/Contents/Library/Seil.10.9.signed.kext'";
        break;
      default:
        std::cerr << "Unknown os major version: " << major << std::endl;
        exit(1);
    }

  } else if (argument == "unload") {
    command = "/sbin/kextunload -b org.pqrs.driver.Seil";
  } else {
    usage();
  }

  // We need to call setuid in order to Execute command as root.
  // (rwsr-xr-x permission changes only euid (geteuid). So, we need to change uid by hand.)
  if (setuid(0) != 0) {
    std::cerr << "Failed to setuid(0)." << std::endl;
    exit(1);
  }
  return system(command.c_str());
}
<|endoftext|>


<commit_before>//
//  yas_ui_event_types.cpp
//

#include "yas_ui_event_types.h"

using namespace yas;
using namespace yas::ui;

#pragma mark - cursor_event

cursor_event::cursor_event(point pos, double const timestamp) : position(std::move(pos)), timestamp(timestamp) {
}

bool cursor_event::operator==(cursor_event const &rhs) const {
    return true;
}

bool cursor_event::operator!=(cursor_event const &rhs) const {
    return false;
}

bool cursor_event::contains_in_window() const {
    return -1.0f <= this->position.x && this->position.x <= 1.0f && -1.0f <= this->position.y &&
           this->position.y <= 1.0f;
}

#pragma mark - touch_id

bool touch_id::operator==(touch_id const &rhs) const {
    return this->kind == rhs.kind && this->identifier == rhs.identifier;
}

bool touch_id::operator!=(touch_id const &rhs) const {
    return !(*this == rhs);
}

touch_id const &touch_id::mouse_left() {
    static touch_id const _mouse_left{.kind = touch_kind::mouse, .identifier = 0};
    return _mouse_left;
}

touch_id const &touch_id::mouse_right() {
    static touch_id const _mouse_right{.kind = touch_kind::mouse, .identifier = 1};
    return _mouse_right;
}

#pragma mark - touch_event

touch_event::touch_event(ui::touch_id const identifier, point pos, double const timestamp)
    : touch_id(identifier), position(std::move(pos)), timestamp(timestamp) {
}

bool touch_event::operator==(touch_event const &rhs) const {
    return this->touch_id == rhs.touch_id;
}

bool touch_event::operator!=(touch_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - key_event

key_event::key_event(uint16_t const key_code, std::string charas, std::string charas2, double const timestamp)
    : key_code(key_code), characters(std::move(charas)), raw_characters(std::move(charas2)), timestamp(timestamp) {
}

bool key_event::operator==(key_event const &rhs) const {
    return this->key_code == rhs.key_code;
}

bool key_event::operator!=(key_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - modifier_event

modifier_event::modifier_event(modifier_flags const flag, double const timestamp) : flag(flag), timestamp(timestamp) {
}

bool modifier_event::operator==(modifier_event const &rhs) const {
    return this->flag == rhs.flag;
}

bool modifier_event::operator!=(modifier_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - pinch_event

pinch_event::pinch_event(double const magnification, double const timestamp)
    : _magnification(magnification), _timestamp(timestamp) {
}

bool pinch_event::operator==(pinch_event const &rhs) const {
    return this->_magnification == rhs._magnification;
}

bool pinch_event::operator!=(pinch_event const &rhs) const {
    return !(*this == rhs);
}

double pinch_event::magnification() const {
    return this->_magnification;
}

double pinch_event::timestamp() const {
    return this->_timestamp;
}

#pragma mark - scroll_event

scroll_event::scroll_event(double const x, double const y, double const timestamp)
    : _delta_x(x), _delta_y(y), _timestamp(timestamp) {
}

bool scroll_event::operator==(scroll_event const &rhs) const {
    return this->_delta_x == rhs._delta_x && this->_delta_y == rhs._delta_y;
}

bool scroll_event::operator!=(scroll_event const &rhs) const {
    return !(*this == rhs);
}

double scroll_event::deltaX() const {
    return this->_delta_x;
}

double scroll_event::deltaY() const {
    return this->_delta_y;
}

double scroll_event::timestamp() const {
    return this->_timestamp;
}

#pragma mark -

std::string yas::to_string(cursor_event const &event) {
    return "{position:" + to_string(event.position) + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(ui::touch_kind const &kind) {
    switch (kind) {
        case touch_kind::mouse:
            return "mouse";
        case touch_kind::touch:
            return "touch";
    }
}

std::string yas::to_string(ui::touch_id const &touch_id) {
    return "{kind:" + to_string(touch_id.kind) + ", identifier:" + std::to_string(touch_id.identifier) + "}";
}

std::string yas::to_string(touch_event const &event) {
    return "{position:" + to_string(event.position) + ", touch_id:" + to_string(event.touch_id) +
           ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(key_event const &event) {
    return "{key_code:" + std::to_string(event.key_code) + ", characters:" + event.characters +
           ", raw_characters:" + event.raw_characters + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(modifier_event const &event) {
    return "{flag:" + to_string(event.flag) + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(ui::pinch_event const &event) {
    return "{magnification:" + std::to_string(event.magnification()) +
           ", timestamp:" + std::to_string(event.timestamp()) + "}";
}

std::string yas::to_string(ui::scroll_event const &event) {
    return "{x:" + std::to_string(event.deltaX()) + ", y:" + std::to_string(event.deltaY()) + "}";
}

std::string yas::to_string(event_phase const &phase) {
    switch (phase) {
        case event_phase::began:
            return "began";
        case event_phase::stationary:
            return "stationary";
        case event_phase::changed:
            return "changed";
        case event_phase::ended:
            return "ended";
        case event_phase::canceled:
            return "canceled";
        case event_phase::may_begin:
            return "may_begin";
        case event_phase::none:
            return "none";
    }
}

std::string yas::to_string(modifier_flags const &flag) {
    switch (flag) {
        case modifier_flags::alpha_shift:
            return "alpha_shift";
        case modifier_flags::shift:
            return "shift";
        case modifier_flags::control:
            return "control";
        case modifier_flags::alternate:
            return "alternate";
        case modifier_flags::command:
            return "command";
        case modifier_flags::numeric_pad:
            return "numeric_pad";
        case modifier_flags::help:
            return "help";
        case modifier_flags::function:
            return "function";
    }

    return "unknown";
}

std::string yas::to_string(ui::event_type const &type) {
    switch (type) {
        case event_type::cursor:
            return "cursor";
        case event_type::touch:
            return "touch";
        case event_type::key:
            return "key";
        case event_type::modifier:
            return "modifier";
        case event_type::pinch:
            return "pinch";
        case event_type::scroll:
            return "scroll";
    }
}

std::ostream &operator<<(std::ostream &os, yas::ui::cursor_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::touch_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::key_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::modifier_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::pinch_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::scroll_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::event_phase const &phase) {
    os << to_string(phase);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::modifier_flags const &flags) {
    os << to_string(flags);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::event_type const &event_type) {
    os << to_string(event_type);
    return os;
}
<commit_msg>scroll_event to_string<commit_after>//
//  yas_ui_event_types.cpp
//

#include "yas_ui_event_types.h"

using namespace yas;
using namespace yas::ui;

#pragma mark - cursor_event

cursor_event::cursor_event(point pos, double const timestamp) : position(std::move(pos)), timestamp(timestamp) {
}

bool cursor_event::operator==(cursor_event const &rhs) const {
    return true;
}

bool cursor_event::operator!=(cursor_event const &rhs) const {
    return false;
}

bool cursor_event::contains_in_window() const {
    return -1.0f <= this->position.x && this->position.x <= 1.0f && -1.0f <= this->position.y &&
           this->position.y <= 1.0f;
}

#pragma mark - touch_id

bool touch_id::operator==(touch_id const &rhs) const {
    return this->kind == rhs.kind && this->identifier == rhs.identifier;
}

bool touch_id::operator!=(touch_id const &rhs) const {
    return !(*this == rhs);
}

touch_id const &touch_id::mouse_left() {
    static touch_id const _mouse_left{.kind = touch_kind::mouse, .identifier = 0};
    return _mouse_left;
}

touch_id const &touch_id::mouse_right() {
    static touch_id const _mouse_right{.kind = touch_kind::mouse, .identifier = 1};
    return _mouse_right;
}

#pragma mark - touch_event

touch_event::touch_event(ui::touch_id const identifier, point pos, double const timestamp)
    : touch_id(identifier), position(std::move(pos)), timestamp(timestamp) {
}

bool touch_event::operator==(touch_event const &rhs) const {
    return this->touch_id == rhs.touch_id;
}

bool touch_event::operator!=(touch_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - key_event

key_event::key_event(uint16_t const key_code, std::string charas, std::string charas2, double const timestamp)
    : key_code(key_code), characters(std::move(charas)), raw_characters(std::move(charas2)), timestamp(timestamp) {
}

bool key_event::operator==(key_event const &rhs) const {
    return this->key_code == rhs.key_code;
}

bool key_event::operator!=(key_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - modifier_event

modifier_event::modifier_event(modifier_flags const flag, double const timestamp) : flag(flag), timestamp(timestamp) {
}

bool modifier_event::operator==(modifier_event const &rhs) const {
    return this->flag == rhs.flag;
}

bool modifier_event::operator!=(modifier_event const &rhs) const {
    return !(*this == rhs);
}

#pragma mark - pinch_event

pinch_event::pinch_event(double const magnification, double const timestamp)
    : _magnification(magnification), _timestamp(timestamp) {
}

bool pinch_event::operator==(pinch_event const &rhs) const {
    return this->_magnification == rhs._magnification;
}

bool pinch_event::operator!=(pinch_event const &rhs) const {
    return !(*this == rhs);
}

double pinch_event::magnification() const {
    return this->_magnification;
}

double pinch_event::timestamp() const {
    return this->_timestamp;
}

#pragma mark - scroll_event

scroll_event::scroll_event(double const x, double const y, double const timestamp)
    : _delta_x(x), _delta_y(y), _timestamp(timestamp) {
}

bool scroll_event::operator==(scroll_event const &rhs) const {
    return this->_delta_x == rhs._delta_x && this->_delta_y == rhs._delta_y;
}

bool scroll_event::operator!=(scroll_event const &rhs) const {
    return !(*this == rhs);
}

double scroll_event::deltaX() const {
    return this->_delta_x;
}

double scroll_event::deltaY() const {
    return this->_delta_y;
}

double scroll_event::timestamp() const {
    return this->_timestamp;
}

#pragma mark -

std::string yas::to_string(cursor_event const &event) {
    return "{position:" + to_string(event.position) + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(ui::touch_kind const &kind) {
    switch (kind) {
        case touch_kind::mouse:
            return "mouse";
        case touch_kind::touch:
            return "touch";
    }
}

std::string yas::to_string(ui::touch_id const &touch_id) {
    return "{kind:" + to_string(touch_id.kind) + ", identifier:" + std::to_string(touch_id.identifier) + "}";
}

std::string yas::to_string(touch_event const &event) {
    return "{position:" + to_string(event.position) + ", touch_id:" + to_string(event.touch_id) +
           ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(key_event const &event) {
    return "{key_code:" + std::to_string(event.key_code) + ", characters:" + event.characters +
           ", raw_characters:" + event.raw_characters + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(modifier_event const &event) {
    return "{flag:" + to_string(event.flag) + ", timestamp:" + std::to_string(event.timestamp) + "}";
}

std::string yas::to_string(ui::pinch_event const &event) {
    return "{magnification:" + std::to_string(event.magnification()) +
           ", timestamp:" + std::to_string(event.timestamp()) + "}";
}

std::string yas::to_string(ui::scroll_event const &event) {
    return "{x:" + std::to_string(event.deltaX()) + ", y:" + std::to_string(event.deltaY()) + ", timestamp" +
           std::to_string(event.timestamp()) + "}";
}

std::string yas::to_string(event_phase const &phase) {
    switch (phase) {
        case event_phase::began:
            return "began";
        case event_phase::stationary:
            return "stationary";
        case event_phase::changed:
            return "changed";
        case event_phase::ended:
            return "ended";
        case event_phase::canceled:
            return "canceled";
        case event_phase::may_begin:
            return "may_begin";
        case event_phase::none:
            return "none";
    }
}

std::string yas::to_string(modifier_flags const &flag) {
    switch (flag) {
        case modifier_flags::alpha_shift:
            return "alpha_shift";
        case modifier_flags::shift:
            return "shift";
        case modifier_flags::control:
            return "control";
        case modifier_flags::alternate:
            return "alternate";
        case modifier_flags::command:
            return "command";
        case modifier_flags::numeric_pad:
            return "numeric_pad";
        case modifier_flags::help:
            return "help";
        case modifier_flags::function:
            return "function";
    }

    return "unknown";
}

std::string yas::to_string(ui::event_type const &type) {
    switch (type) {
        case event_type::cursor:
            return "cursor";
        case event_type::touch:
            return "touch";
        case event_type::key:
            return "key";
        case event_type::modifier:
            return "modifier";
        case event_type::pinch:
            return "pinch";
        case event_type::scroll:
            return "scroll";
    }
}

std::ostream &operator<<(std::ostream &os, yas::ui::cursor_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::touch_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::key_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::modifier_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::pinch_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::scroll_event const &value) {
    os << to_string(value);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::event_phase const &phase) {
    os << to_string(phase);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::modifier_flags const &flags) {
    os << to_string(flags);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::event_type const &event_type) {
    os << to_string(event_type);
    return os;
}
<|endoftext|>


<commit_before>// $Id: options.C,v 1.18 2000/11/30 22:57:06 amoll Exp $

#include <BALL/DATATYPE/options.h>

#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>

#include <fstream>
#include <list>
#include <algorithm>

using namespace std;
using std::ofstream;
using std::ios;

namespace BALL
{

	const Size Options::MAX_ENTRY_LENGTH = 1024;

	Options::Options()
	 throw()
		:	StringHashMap<String>(),
			name_("")
	{
	}

	Options::Options(const Options& options, bool deep)
	 throw()
		:	StringHashMap<String>(options, deep),
			name_(options.name_)
	{
	}

	Options::~Options()
	 throw()
	{
	}

	bool Options::isReal(const String& key) const
	 throw()
	{
		errno = 0;
		char*	endptr;
		String value(get(key));

		// an empty String is no real number
		if (value =="")
		{
			return false;
		}

		// try to convert it to a number
		::strtod(value.c_str(), &endptr);

		// return and tell whether it happend to work
		return (errno == 0) && (endptr != value.c_str());
	}

	bool Options::isVector(const String& key) const
	 throw()
	{
		// if the key does not exist - then the nonexistent value
		// cannot contain a vector
		if (!has(key))
		{
			return false;
		}

		// try to interpret the string as three double values
		double dummy;
		if (sscanf(get(key).c_str(), "(%lf %lf %lf)", &dummy, &dummy, &dummy) == 3)
		{
			return true;
		}

		return false;
	}

	bool Options::isBool(const String& key) const
	 throw()
	{
		String s = get(key);
		if (s == "")
		{
			return false;
		}

		s.toLower();
		return (s.compare("true") == 0 || s.compare("false") == 0);
	}

	bool Options::isSet(const String& key) const
	 throw()
	{
		return (StringHashMap<String>::find(key) != StringHashMap<String>::end());
	}

	bool Options::isInteger(const String& key) const
	 throw()
	{
		// if it cannot be read as a floating point number
		// it cannot be an integer
		if (!isReal(key))
		{
			return false;
		}

		// check wheter it is an integer
		long_value long_value = ::atol(get(key).c_str());
		double double_value   = ::atof(get(key).c_str());

		// check if it is an integer (cutoff is 1e-7)
		if (fabs(double_value - ((double)long_value)) <= 1e-7)
		{
			return true;
		}

		// it is a floating point number, but no integer
		return false;
	}

	double Options::getReal(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return 0.0;
		}
		double value;
		errno = 0;
		value = ::atof((*find(key)).second.c_str());

		if (errno == 0)
		{
			return value;
		}
		else
		{
			return 0.0;
		}
	}

	Vector3	Options::getVector(const String& key) const
	 throw()
	{
		Vector3	h(0,0,0);

		if (!has(key))
		{
			return h;
		}

		// use temporary variables of double precision
		// this avoids trouble if the definition of
		// Vector3 is changed between TVector3<float> and TVector3<double>
		double x, y, z;

		// try to interpret the option as a vector
		sscanf(get(key).c_str(), "(%lf %lf %lf)", &x, &y, &z);
		h.x = x;
		h.y = y;
		h.z = z;

		return h;
	}

	bool Options::getBool(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return false;
		}

		ConstIterator it = find(key);
		if ((it != end()) && (it->second == "true"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	long Options::getInteger(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return 0;
		}

		long value;
		errno = 0;
		ConstIterator it = find(key);
		if (it == end())
		{
			return 0;
		}
		value = atol((*it).second.c_str());

		if (errno == 0)
		{
			return value;
		}
		else
		{
			errno = 0;
			return 0;
		}
	}

	void Options::set(const String& key, const String& value)
	 throw()
	{
		(*this)[key] = value;
	}

	void Options::setInteger(const String& key, const long value)
	 throw()
	{
		static char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "%ld", value);
		set(key, &(buffer[0]));
	}

	void Options::setReal(const String& key, const double value)
	 throw()
	{
		char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "%f", value);
		set(key, buffer);
	}

	void Options::setVector(const String& key, const Vector3& value)
	 throw()
	{
		char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "(%f %f %f)", value.x, value.y, value.z);
		set(key, buffer);
	}

	void Options::setBool(const String& key, const bool value)
	 throw()
	{
		if (value)
		{
			set(key, "true");
		}
		else
		{
			set(key, "false");
		}
	}

	String Options::setDefault(const String& key, const String& value)
	 throw()
	{
		if (!has(key))
		{
			set(key, value);
			return key;
		}
		else
		{
			return get(key);
		}
	}

	double Options::setDefaultReal(const String& key, const double value)
	 throw()
	{
		if (!has(key) || !isReal(key))
		{
			setReal(key, value);
			return value;
		}
		else
		{
			return getReal(key);
		}
	}

	bool Options::setDefaultBool(const String& key, const bool value)
	 throw()
	{
		if (!has(key) || !isBool(key))
		{
			setBool(key, value);
			return value;
		}
		else
		{
			return getBool(key);
		}
	}

	long Options::setDefaultInteger(const String& key, const long value)
	 throw()
	{
		if (!has(key) || !isInteger(key))
		{
			setInteger(key, value);
			return value;
		}
		else
		{
			return getInteger(key);
		}
	}

	void Options::setName(const String& name)
	 throw()
	{
		name_ = name;
	}

	const String& Options::getName() const
	 throw()
	{
		return name_;
	}

	String Options::get(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return "";
		}
		ConstIterator it = find(key);

		if (it == end())
		{
			return "";
		}
		else
		{
			return (*it).second;
		}
	}

	bool Options::readOptionFile(const String& filename)
	 throw()
	{
		ifstream	infile;
		infile.open(filename.c_str(), ios::in);
		if (!infile)
		{
			return false;
		}

		char		buffer[MAX_ENTRY_LENGTH + 1];
		String	s, key;
		while (infile.getline(buffer, MAX_ENTRY_LENGTH))
		{
			if ((buffer[0] != '#') && (buffer[0] != '!') && (buffer[0] != ';'))
			{
				s = buffer;
				key = s.getField(0, " ");
				s = s.after(" ");
				set(key, s);
			}
		}

		infile.close();
		return true;
	}

	bool Options::writeOptionFile(const String& filename) const
	 throw()
	{
		std::list<String>		entry_list;
		String							entry;

		std::ofstream stream(filename.c_str());//, File::OUT);
		if (!stream.is_open())
		{
			return false;
		}

		stream << "![OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;

		StringHashMap<String>::ConstIterator	it(begin());
		for(; !(it == end()); ++it)
		{
			entry = (*it).first + ' ' + (*it).second;
			entry_list.push_back(entry);
		}

		entry_list.sort();

		std::list<String>::iterator	list_it = entry_list.begin();
		for (; list_it != entry_list.end(); ++list_it)
		{
	  	stream << *list_it << endl;
		}

		stream << "!-----------------------------------" << endl;

		stream.close();
		entry_list.clear();
		return true;
	}

	void Options::dump (ostream& stream, Size /* depth */) const
	 throw()
	{
		std::list<String>		entry_list;
		String							entry;

		stream << "[OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;

		StringHashMap<String>::ConstIterator	it(begin());
		for(; !(it == end()); ++it)
		{
			entry = (*it).first + ' ' + (*it).second;
			entry_list.push_back(entry);
		}

		entry_list.sort();

		std::list<String>::iterator	list_it = entry_list.begin();
		for (; list_it != entry_list.end(); ++list_it)
		{
	  	stream << *list_it << endl;
		}

		stream << "-----------------------------------" << endl;

		entry_list.clear();
	}

	const Options& Options::operator = (const Options& options)
	 throw()
	{
		*this = Options(options);
	}

	bool Options::operator == (const Options::& option) const
		throw()
	{
		if (this->name_ != option.name_)
		{
			return false;
		}

		return StringHashMap<String>::operator == (option);
	}

	bool Options::operator != (const Options::& option) const
		throw()
	{
		return !(*this == option);
	}

	void Options::clear() throw()
	{
		name_ = "";
		StringHashMap<String>::clear();
	}

} // namespace BALL
<commit_msg>fixed: operator = didnt return anything, long_value was not a type, some typos<commit_after>// $Id: options.C,v 1.19 2000/12/01 13:01:53 anker Exp $

#include <BALL/DATATYPE/options.h>

#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>

#include <fstream>
#include <list>
#include <algorithm>

using namespace std;
using std::ofstream;
using std::ios;

namespace BALL
{

	const Size Options::MAX_ENTRY_LENGTH = 1024;

	Options::Options()
	 throw()
		:	StringHashMap<String>(),
			name_("")
	{
	}

	Options::Options(const Options& options, bool deep)
	 throw()
		:	StringHashMap<String>(options, deep),
			name_(options.name_)
	{
	}

	Options::~Options()
	 throw()
	{
	}

	bool Options::isReal(const String& key) const
	 throw()
	{
		errno = 0;
		char*	endptr;
		String value(get(key));

		// an empty String is no real number
		if (value =="")
		{
			return false;
		}

		// try to convert it to a number
		::strtod(value.c_str(), &endptr);

		// return and tell whether it happend to work
		return (errno == 0) && (endptr != value.c_str());
	}

	bool Options::isVector(const String& key) const
	 throw()
	{
		// if the key does not exist - then the nonexistent value
		// cannot contain a vector
		if (!has(key))
		{
			return false;
		}

		// try to interpret the string as three double values
		double dummy;
		if (sscanf(get(key).c_str(), "(%lf %lf %lf)", &dummy, &dummy, &dummy) == 3)
		{
			return true;
		}

		return false;
	}

	bool Options::isBool(const String& key) const
	 throw()
	{
		String s = get(key);
		if (s == "")
		{
			return false;
		}

		s.toLower();
		return (s.compare("true") == 0 || s.compare("false") == 0);
	}

	bool Options::isSet(const String& key) const
	 throw()
	{
		return (StringHashMap<String>::find(key) != StringHashMap<String>::end());
	}

	bool Options::isInteger(const String& key) const
	 throw()
	{
		// if it cannot be read as a floating point number
		// it cannot be an integer
		if (!isReal(key))
		{
			return false;
		}

		// check wheter it is an integer
		long long_value = ::atol(get(key).c_str());
		double double_value   = ::atof(get(key).c_str());

		// check if it is an integer (cutoff is 1e-7)
		if (fabs(double_value - ((double)long_value)) <= 1e-7)
		{
			return true;
		}

		// it is a floating point number, but no integer
		return false;
	}

	double Options::getReal(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return 0.0;
		}
		double value;
		errno = 0;
		value = ::atof((*find(key)).second.c_str());

		if (errno == 0)
		{
			return value;
		}
		else
		{
			return 0.0;
		}
	}

	Vector3	Options::getVector(const String& key) const
	 throw()
	{
		Vector3	h(0,0,0);

		if (!has(key))
		{
			return h;
		}

		// use temporary variables of double precision
		// this avoids trouble if the definition of
		// Vector3 is changed between TVector3<float> and TVector3<double>
		double x, y, z;

		// try to interpret the option as a vector
		sscanf(get(key).c_str(), "(%lf %lf %lf)", &x, &y, &z);
		h.x = x;
		h.y = y;
		h.z = z;

		return h;
	}

	bool Options::getBool(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return false;
		}

		ConstIterator it = find(key);
		if ((it != end()) && (it->second == "true"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	long Options::getInteger(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return 0;
		}

		long value;
		errno = 0;
		ConstIterator it = find(key);
		if (it == end())
		{
			return 0;
		}
		value = atol((*it).second.c_str());

		if (errno == 0)
		{
			return value;
		}
		else
		{
			errno = 0;
			return 0;
		}
	}

	void Options::set(const String& key, const String& value)
	 throw()
	{
		(*this)[key] = value;
	}

	void Options::setInteger(const String& key, const long value)
	 throw()
	{
		static char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "%ld", value);
		set(key, &(buffer[0]));
	}

	void Options::setReal(const String& key, const double value)
	 throw()
	{
		char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "%f", value);
		set(key, buffer);
	}

	void Options::setVector(const String& key, const Vector3& value)
	 throw()
	{
		char buffer[MAX_ENTRY_LENGTH + 1];
		sprintf(buffer, "(%f %f %f)", value.x, value.y, value.z);
		set(key, buffer);
	}

	void Options::setBool(const String& key, const bool value)
	 throw()
	{
		if (value)
		{
			set(key, "true");
		}
		else
		{
			set(key, "false");
		}
	}

	String Options::setDefault(const String& key, const String& value)
	 throw()
	{
		if (!has(key))
		{
			set(key, value);
			return key;
		}
		else
		{
			return get(key);
		}
	}

	double Options::setDefaultReal(const String& key, const double value)
	 throw()
	{
		if (!has(key) || !isReal(key))
		{
			setReal(key, value);
			return value;
		}
		else
		{
			return getReal(key);
		}
	}

	bool Options::setDefaultBool(const String& key, const bool value)
	 throw()
	{
		if (!has(key) || !isBool(key))
		{
			setBool(key, value);
			return value;
		}
		else
		{
			return getBool(key);
		}
	}

	long Options::setDefaultInteger(const String& key, const long value)
	 throw()
	{
		if (!has(key) || !isInteger(key))
		{
			setInteger(key, value);
			return value;
		}
		else
		{
			return getInteger(key);
		}
	}

	void Options::setName(const String& name)
	 throw()
	{
		name_ = name;
	}

	const String& Options::getName() const
	 throw()
	{
		return name_;
	}

	String Options::get(const String& key) const
	 throw()
	{
		if (!has(key))
		{
			return "";
		}
		ConstIterator it = find(key);

		if (it == end())
		{
			return "";
		}
		else
		{
			return (*it).second;
		}
	}

	bool Options::readOptionFile(const String& filename)
	 throw()
	{
		ifstream	infile;
		infile.open(filename.c_str(), ios::in);
		if (!infile)
		{
			return false;
		}

		char		buffer[MAX_ENTRY_LENGTH + 1];
		String	s, key;
		while (infile.getline(buffer, MAX_ENTRY_LENGTH))
		{
			if ((buffer[0] != '#') && (buffer[0] != '!') && (buffer[0] != ';'))
			{
				s = buffer;
				key = s.getField(0, " ");
				s = s.after(" ");
				set(key, s);
			}
		}

		infile.close();
		return true;
	}

	bool Options::writeOptionFile(const String& filename) const
	 throw()
	{
		std::list<String>		entry_list;
		String							entry;

		std::ofstream stream(filename.c_str());//, File::OUT);
		if (!stream.is_open())
		{
			return false;
		}

		stream << "![OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;

		StringHashMap<String>::ConstIterator	it(begin());
		for(; !(it == end()); ++it)
		{
			entry = (*it).first + ' ' + (*it).second;
			entry_list.push_back(entry);
		}

		entry_list.sort();

		std::list<String>::iterator	list_it = entry_list.begin();
		for (; list_it != entry_list.end(); ++list_it)
		{
	  	stream << *list_it << endl;
		}

		stream << "!-----------------------------------" << endl;

		stream.close();
		entry_list.clear();
		return true;
	}

	void Options::dump (ostream& stream, Size /* depth */) const
	 throw()
	{
		std::list<String>		entry_list;
		String							entry;

		stream << "[OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;

		StringHashMap<String>::ConstIterator	it(begin());
		for(; !(it == end()); ++it)
		{
			entry = (*it).first + ' ' + (*it).second;
			entry_list.push_back(entry);
		}

		entry_list.sort();

		std::list<String>::iterator	list_it = entry_list.begin();
		for (; list_it != entry_list.end(); ++list_it)
		{
	  	stream << *list_it << endl;
		}

		stream << "-----------------------------------" << endl;

		entry_list.clear();
	}

	const Options& Options::operator = (const Options& options)
	 throw()
	{
		*this = Options(options);
		return *this;
	}

	bool Options::operator == (const Options& option) const
		throw()
	{
		if (this->name_ != option.name_)
		{
			return false;
		}

		return StringHashMap<String>::operator == (option);
	}

	bool Options::operator != (const Options& option) const
		throw()
	{
		return !(*this == option);
	}

	void Options::clear() throw()
	{
		name_ = "";
		StringHashMap<String>::clear();
	}

} // namespace BALL
<|endoftext|>


<commit_before>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen 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 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "raul/Path.hpp"
#include "interface/EngineInterface.hpp"
#include "client/ClientStore.hpp"
#include "client/PatchModel.hpp"
#include "App.hpp"
#include "PatchTreeWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

PatchTreeWindow::PatchTreeWindow(BaseObjectType*                        cobject,
                                 const Glib::RefPtr<Gnome::Glade::Xml>& xml)
	: Gtk::Window(cobject)
	, _enable_signal(true)
{
	xml->get_widget_derived("patches_treeview", _patches_treeview);

	_patch_treestore = Gtk::TreeStore::create(_patch_tree_columns);
	_patches_treeview->set_window(this);
	_patches_treeview->set_model(_patch_treestore);
	Gtk::TreeViewColumn* name_col = Gtk::manage(new Gtk::TreeViewColumn(
		"Patch", _patch_tree_columns.name_col));
	Gtk::TreeViewColumn* enabled_col = Gtk::manage(new Gtk::TreeViewColumn(
		"Run", _patch_tree_columns.enabled_col));
	name_col->set_resizable(true);
	name_col->set_expand(true);

	_patches_treeview->append_column(*name_col);
	_patches_treeview->append_column(*enabled_col);
	Gtk::CellRendererToggle* enabled_renderer = dynamic_cast<Gtk::CellRendererToggle*>(
		_patches_treeview->get_column_cell_renderer(1));
	enabled_renderer->property_activatable() = true;

	_patch_tree_selection = _patches_treeview->get_selection();

	//m_patch_tree_selection->signal_changed().connect(
	//	sigc::mem_fun(this, &PatchTreeWindow::event_patch_selected));
	_patches_treeview->signal_row_activated().connect(
		sigc::mem_fun(this, &PatchTreeWindow::event_patch_activated));
	enabled_renderer->signal_toggled().connect(
		sigc::mem_fun(this, &PatchTreeWindow::event_patch_enabled_toggled));

	_patches_treeview->columns_autosize();
}

void
PatchTreeWindow::init(ClientStore& store)
{
	store.signal_new_object.connect(sigc::mem_fun(this, &PatchTreeWindow::new_object));
}

void
PatchTreeWindow::new_object(SharedPtr<ObjectModel> object)
{
	SharedPtr<PatchModel> patch = PtrCast<PatchModel>(object);
	if (patch)
		add_patch(patch);
}

void
PatchTreeWindow::add_patch(SharedPtr<PatchModel> pm)
{
	if (!pm->parent()) {
		Gtk::TreeModel::iterator iter = _patch_treestore->append();
		Gtk::TreeModel::Row row = *iter;
		if (pm->path() == "/") {
			row[_patch_tree_columns.name_col] = App::instance().engine()->uri();
		} else {
			row[_patch_tree_columns.name_col] = pm->path().name();
		}
		row[_patch_tree_columns.enabled_col] = false;
		row[_patch_tree_columns.patch_model_col] = pm;
		_patches_treeview->expand_row(_patch_treestore->get_path(iter), true);
	} else {
		Gtk::TreeModel::Children children = _patch_treestore->children();
		Gtk::TreeModel::iterator c = find_patch(children, pm->parent()->path());

		if (c != children.end()) {
			Gtk::TreeModel::iterator iter = _patch_treestore->append(c->children());
			Gtk::TreeModel::Row row = *iter;
			row[_patch_tree_columns.name_col] = pm->path().name();
			row[_patch_tree_columns.enabled_col] = false;
			row[_patch_tree_columns.patch_model_col] = pm;
			_patches_treeview->expand_row(_patch_treestore->get_path(iter), true);
		}
	}

	pm->signal_property.connect(sigc::bind(sigc::mem_fun(this, &PatchTreeWindow::patch_property_changed), pm->path()));
}

void
PatchTreeWindow::remove_patch(const Path& path)
{
	Gtk::TreeModel::iterator i = find_patch(_patch_treestore->children(), path);
	if (i != _patch_treestore->children().end())
		_patch_treestore->erase(i);
}

Gtk::TreeModel::iterator
PatchTreeWindow::find_patch(Gtk::TreeModel::Children root, const Path& path)
{
	for (Gtk::TreeModel::iterator c = root.begin(); c != root.end(); ++c) {
		SharedPtr<PatchModel> pm = (*c)[_patch_tree_columns.patch_model_col];
		if (pm->path() == path) {
			return c;
		} else if ((*c)->children().size() > 0) {
			Gtk::TreeModel::iterator ret = find_patch(c->children(), path);
			if (ret != c->children().end())
				return ret;
		}
	}
	return root.end();
}

/*
void
PatchTreeWindow::event_patch_selected()
{
	Gtk::TreeModel::iterator active = _patch_tree_selection->get_selected();
	if (active) {
		Gtk::TreeModel::Row row = *active;
		SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
	}
}
*/

/** Show the context menu for the selected patch in the patches treeview.
 */
void
PatchTreeWindow::show_patch_menu(GdkEventButton* ev)
{
	Gtk::TreeModel::iterator active = _patch_tree_selection->get_selected();
	if (active) {
		Gtk::TreeModel::Row row = *active;
		SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
		if (pm)
			cerr << "FIXME: patch menu\n";
			//pm->show_menu(ev);
	}
}

void
PatchTreeWindow::event_patch_activated(const Gtk::TreeModel::Path& path, Gtk::TreeView::Column* col)
{
	Gtk::TreeModel::iterator active = _patch_treestore->get_iter(path);
	Gtk::TreeModel::Row row = *active;
	SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];

	App::instance().window_factory()->present_patch(pm);
}

void
PatchTreeWindow::event_patch_enabled_toggled(const Glib::ustring& path_str)
{
	Gtk::TreeModel::Path path(path_str);
	Gtk::TreeModel::iterator active = _patch_treestore->get_iter(path);
	Gtk::TreeModel::Row row = *active;

	SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
	Glib::ustring patch_path = pm->path();

	assert(pm);

	if (_enable_signal)
		App::instance().engine()->set_property(patch_path, "ingen:enabled", (bool)!pm->enabled());
}

void
PatchTreeWindow::patch_property_changed(const string& key, const Raul::Atom& value, const Path& path)
{
	_enable_signal = false;
	if (key == "ingen:enabled" && value.type() == Atom::BOOL) {
		Gtk::TreeModel::iterator i = find_patch(_patch_treestore->children(), path);
		if (i != _patch_treestore->children().end()) {
			Gtk::TreeModel::Row row = *i;
			row[_patch_tree_columns.enabled_col] = value.get_bool();
		} else {
			cerr << "[PatchTreeWindow] Unable to find patch " << path << endl;
		}
	}
	_enable_signal = true;
}

void
PatchTreeWindow::patch_renamed(const Path& old_path, const Path& new_path)
{
	_enable_signal = false;

	Gtk::TreeModel::iterator i
		= find_patch(_patch_treestore->children(), old_path);

	if (i != _patch_treestore->children().end()) {
		Gtk::TreeModel::Row row = *i;
		row[_patch_tree_columns.name_col] = new_path.name();
	} else {
		cerr << "[PatchTreeWindow] Unable to find patch " << old_path << endl;
	}

	_enable_signal = true;
}

} // namespace GUI
} // namespace Ingen
<commit_msg>Remove destroyed patches from patch tree window (fix ticket #311).<commit_after>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen 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 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "raul/Path.hpp"
#include "interface/EngineInterface.hpp"
#include "client/ClientStore.hpp"
#include "client/PatchModel.hpp"
#include "App.hpp"
#include "PatchTreeWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

PatchTreeWindow::PatchTreeWindow(BaseObjectType*                        cobject,
                                 const Glib::RefPtr<Gnome::Glade::Xml>& xml)
	: Gtk::Window(cobject)
	, _enable_signal(true)
{
	xml->get_widget_derived("patches_treeview", _patches_treeview);

	_patch_treestore = Gtk::TreeStore::create(_patch_tree_columns);
	_patches_treeview->set_window(this);
	_patches_treeview->set_model(_patch_treestore);
	Gtk::TreeViewColumn* name_col = Gtk::manage(new Gtk::TreeViewColumn(
		"Patch", _patch_tree_columns.name_col));
	Gtk::TreeViewColumn* enabled_col = Gtk::manage(new Gtk::TreeViewColumn(
		"Run", _patch_tree_columns.enabled_col));
	name_col->set_resizable(true);
	name_col->set_expand(true);

	_patches_treeview->append_column(*name_col);
	_patches_treeview->append_column(*enabled_col);
	Gtk::CellRendererToggle* enabled_renderer = dynamic_cast<Gtk::CellRendererToggle*>(
		_patches_treeview->get_column_cell_renderer(1));
	enabled_renderer->property_activatable() = true;

	_patch_tree_selection = _patches_treeview->get_selection();

	//m_patch_tree_selection->signal_changed().connect(
	//	sigc::mem_fun(this, &PatchTreeWindow::event_patch_selected));
	_patches_treeview->signal_row_activated().connect(
		sigc::mem_fun(this, &PatchTreeWindow::event_patch_activated));
	enabled_renderer->signal_toggled().connect(
		sigc::mem_fun(this, &PatchTreeWindow::event_patch_enabled_toggled));

	_patches_treeview->columns_autosize();
}

void
PatchTreeWindow::init(ClientStore& store)
{
	store.signal_new_object.connect(sigc::mem_fun(this, &PatchTreeWindow::new_object));
}

void
PatchTreeWindow::new_object(SharedPtr<ObjectModel> object)
{
	SharedPtr<PatchModel> patch = PtrCast<PatchModel>(object);
	if (patch)
		add_patch(patch);
}

void
PatchTreeWindow::add_patch(SharedPtr<PatchModel> pm)
{
	if (!pm->parent()) {
		Gtk::TreeModel::iterator iter = _patch_treestore->append();
		Gtk::TreeModel::Row row = *iter;
		if (pm->path() == "/") {
			row[_patch_tree_columns.name_col] = App::instance().engine()->uri();
		} else {
			row[_patch_tree_columns.name_col] = pm->path().name();
		}
		row[_patch_tree_columns.enabled_col] = false;
		row[_patch_tree_columns.patch_model_col] = pm;
		_patches_treeview->expand_row(_patch_treestore->get_path(iter), true);
	} else {
		Gtk::TreeModel::Children children = _patch_treestore->children();
		Gtk::TreeModel::iterator c = find_patch(children, pm->parent()->path());

		if (c != children.end()) {
			Gtk::TreeModel::iterator iter = _patch_treestore->append(c->children());
			Gtk::TreeModel::Row row = *iter;
			row[_patch_tree_columns.name_col] = pm->path().name();
			row[_patch_tree_columns.enabled_col] = false;
			row[_patch_tree_columns.patch_model_col] = pm;
			_patches_treeview->expand_row(_patch_treestore->get_path(iter), true);
		}
	}

	pm->signal_property.connect(sigc::bind(
			sigc::mem_fun(this, &PatchTreeWindow::patch_property_changed),
			pm->path()));

	pm->signal_destroyed.connect(sigc::bind(
		sigc::mem_fun(this, &PatchTreeWindow::remove_patch),
		pm->path()));
}

void
PatchTreeWindow::remove_patch(const Path& path)
{
	Gtk::TreeModel::iterator i = find_patch(_patch_treestore->children(), path);
	if (i != _patch_treestore->children().end())
		_patch_treestore->erase(i);
}

Gtk::TreeModel::iterator
PatchTreeWindow::find_patch(Gtk::TreeModel::Children root, const Path& path)
{
	for (Gtk::TreeModel::iterator c = root.begin(); c != root.end(); ++c) {
		SharedPtr<PatchModel> pm = (*c)[_patch_tree_columns.patch_model_col];
		if (pm->path() == path) {
			return c;
		} else if ((*c)->children().size() > 0) {
			Gtk::TreeModel::iterator ret = find_patch(c->children(), path);
			if (ret != c->children().end())
				return ret;
		}
	}
	return root.end();
}

/*
void
PatchTreeWindow::event_patch_selected()
{
	Gtk::TreeModel::iterator active = _patch_tree_selection->get_selected();
	if (active) {
		Gtk::TreeModel::Row row = *active;
		SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
	}
}
*/

/** Show the context menu for the selected patch in the patches treeview.
 */
void
PatchTreeWindow::show_patch_menu(GdkEventButton* ev)
{
	Gtk::TreeModel::iterator active = _patch_tree_selection->get_selected();
	if (active) {
		Gtk::TreeModel::Row row = *active;
		SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
		if (pm)
			cerr << "FIXME: patch menu\n";
			//pm->show_menu(ev);
	}
}

void
PatchTreeWindow::event_patch_activated(const Gtk::TreeModel::Path& path, Gtk::TreeView::Column* col)
{
	Gtk::TreeModel::iterator active = _patch_treestore->get_iter(path);
	Gtk::TreeModel::Row row = *active;
	SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];

	App::instance().window_factory()->present_patch(pm);
}

void
PatchTreeWindow::event_patch_enabled_toggled(const Glib::ustring& path_str)
{
	Gtk::TreeModel::Path path(path_str);
	Gtk::TreeModel::iterator active = _patch_treestore->get_iter(path);
	Gtk::TreeModel::Row row = *active;

	SharedPtr<PatchModel> pm = row[_patch_tree_columns.patch_model_col];
	Glib::ustring patch_path = pm->path();

	assert(pm);

	if (_enable_signal)
		App::instance().engine()->set_property(patch_path, "ingen:enabled", (bool)!pm->enabled());
}

void
PatchTreeWindow::patch_property_changed(const string& key, const Raul::Atom& value, const Path& path)
{
	_enable_signal = false;
	if (key == "ingen:enabled" && value.type() == Atom::BOOL) {
		Gtk::TreeModel::iterator i = find_patch(_patch_treestore->children(), path);
		if (i != _patch_treestore->children().end()) {
			Gtk::TreeModel::Row row = *i;
			row[_patch_tree_columns.enabled_col] = value.get_bool();
		} else {
			cerr << "[PatchTreeWindow] Unable to find patch " << path << endl;
		}
	}
	_enable_signal = true;
}

void
PatchTreeWindow::patch_renamed(const Path& old_path, const Path& new_path)
{
	_enable_signal = false;

	Gtk::TreeModel::iterator i
		= find_patch(_patch_treestore->children(), old_path);

	if (i != _patch_treestore->children().end()) {
		Gtk::TreeModel::Row row = *i;
		row[_patch_tree_columns.name_col] = new_path.name();
	} else {
		cerr << "[PatchTreeWindow] Unable to find patch " << old_path << endl;
	}

	_enable_signal = true;
}

} // namespace GUI
} // namespace Ingen
<|endoftext|>