<commit_before>#ifndef VIENNAGRID_ALGORITHM_DISTANCE_HPP
#define VIENNAGRID_ALGORITHM_DISTANCE_HPP

/* =======================================================================
   Copyright (c) 2011-2014, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <limits>

#include "viennagrid/forwards.hpp"
#include "viennagrid/topology/all.hpp"
#include "viennagrid/algorithm/norm.hpp"
#include "viennagrid/algorithm/inner_prod.hpp"
#include "viennagrid/algorithm/closest_points.hpp"

/** @file viennagrid/algorithm/distance.hpp
    @brief Computes the (Cartesian) distance between different elements.
*/

namespace viennagrid
{
  namespace detail
  {

    //
    // Distance between points
    //

    // Distance between two points:
    template <typename PointT1, typename PointT2>
    typename viennagrid::result_of::coord<PointT1>::type
    distance_impl(PointT1 const & p1,
                  PointT2 const & p2)
    {
      return norm_2(p1 - p2);
    }

    template <typename PointT1, typename PointT2>
    typename viennagrid::result_of::coord<PointT1>::type
    distance_impl( std::pair<PointT1,PointT2> const & pts)
    {
      return distance_impl(pts.first, pts.second);
    }

    template <typename PointAccessorT, typename CoordT1, typename CoordinateSystemT1, typename CoordT2, typename CoordinateSystemT2>
    CoordT1
    distance_impl(PointAccessorT const,
                  spatial_point<CoordT1, CoordinateSystemT1> const & p1,
                  spatial_point<CoordT2, CoordinateSystemT2> const & p2)
    {
      return distance_impl(p1, p2);
    }

    template <typename PointAccessorT, typename PointT, typename WrappedConfigT>
    typename viennagrid::result_of::coord<PointT>::type
    distance_impl(PointAccessorT const accessor,
                  PointT const & p1,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT> const & v2)
    {
      return distance_impl(p1, accessor(v2));
    }

    template <typename PointAccessorT, typename PointT, typename WrappedConfigT>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    distance_impl(PointAccessorT const accessor,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT> const & v1,
                  PointT const & p2)
    {
      return distance_impl(accessor(v1), p2);
    }

    // Distance between vertices: Use point distance
    template <typename PointAccessorT, typename PointT, typename WrappedConfigT1, typename WrappedConfigT2>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    distance_impl(PointAccessorT const accessor,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT1> const & v1,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT2> const & v2)
    {
      return distance_impl(accessor(v1), accessor(v2));
    }

    //
    // Generic distance computation: Reuse closest_points()
    //
    template <typename PointAccessorT, typename SomethingT1, typename SomethingT2>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    distance_impl(PointAccessorT const accessor,
                  SomethingT1 const & el1,
                  SomethingT2 const & el2)
    {
      //typedef typename result_of::point<ElementType1>::type   PointT;
      typedef typename PointAccessorT::value_type PointT;

      std::pair<PointT, PointT> points = closest_points(accessor, el1, el2);

      return distance_impl( points );
    }

    ////////////////////////////////// boundary distance //////////////////////////////////////

    template <typename PointT1, typename PointT2>
    typename viennagrid::result_of::coord<PointT1>::type
    boundary_distance_impl(PointT1 const & p1,
                  PointT2 const & p2)
    {
      return norm_2(p1 - p2);
    }

    template <typename PointT1, typename PointT2>
    typename viennagrid::result_of::coord<PointT1>::type
    boundary_distance_impl( std::pair<PointT1,PointT2> const & pts)
    {
      return boundary_distance_impl(pts.first, pts.second);
    }

    template <typename PointAccessorT, typename CoordT1, typename CoordinateSystemT1, typename CoordT2, typename CoordinateSystemT2>
    CoordT1
    boundary_distance_impl(PointAccessorT const,
                  spatial_point<CoordT1, CoordinateSystemT1> const & p1,
                  spatial_point<CoordT2, CoordinateSystemT2> const & p2)
    {
      return boundary_distance_impl(p1, p2);
    }

    template <typename PointAccessorT, typename PointT, typename WrappedConfigT>
    typename viennagrid::result_of::coord<PointT>::type
    boundary_distance_impl(PointAccessorT const accessor,
                  PointT const & p1,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT> const & v2)
    {
      return boundary_distance_impl(p1, accessor(v2));
    }

    template <typename PointAccessorT, typename PointT, typename WrappedConfigT>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    boundary_distance_impl(PointAccessorT const accessor,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT> const & v1,
                  PointT const & p2)
    {
      return boundary_distance_impl(accessor(v1), p2);
    }

    // Distance between vertices: Use point distance
    template <typename PointAccessorT, typename PointT, typename WrappedConfigT1, typename WrappedConfigT2>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    boundary_distance_impl(PointAccessorT const accessor,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT1> const & v1,
                  viennagrid::element<viennagrid::vertex_tag, WrappedConfigT2> const & v2)
    {
      return boundary_distance_impl(accessor(v1), accessor(v2));
    }

    //
    // Generic distance computation: Reuse closest_points()
    //
    template <typename PointAccessorT, typename SomethingT1, typename SomethingT2>
    typename viennagrid::result_of::coord<typename PointAccessorT::value_type>::type
    boundary_distance_impl(PointAccessorT const accessor,
                           SomethingT1 const & el1,
                           SomethingT2 const & el2)
    {
      //typedef typename result_of::point<ElementType1>::type      PointT;
      typedef typename PointAccessorT::value_type PointT;

      std::pair<PointT, PointT> points = closest_points_on_boundary(accessor, el1, el2);

      return boundary_distance_impl(points);
    }

  } //namespace detail

  //
  // The public interface functions
  //
  /** @brief Returns the distance between elements, segments and/or meshs using the point accessor provided */
  template <typename PointAccessorT, typename SomethingT1, typename SomethingT2>
  typename viennagrid::result_of::coord<SomethingT1>::type
  distance(PointAccessorT const accessor,
           SomethingT1 const & el1,
           SomethingT2 const & el2)
  {
    return detail::distance_impl(accessor, el1, el2);
  }

  /** @brief Returns the distance between elements, segments and/or meshs using the default point accessor*/
  template <typename SomethingT1, typename SomethingT2>
  typename viennagrid::result_of::coord<SomethingT1>::type
  distance(SomethingT1 const & el1,
           SomethingT2 const & el2)
  {
    return detail::distance_impl( default_point_accessor(el1), el1, el2 );
  }

  /** @brief Returns the distance between a point and an element/segment/meshs using the default point accessor*/
  template <typename SomethingT, typename CoordT, typename CoordinateSystemT>
  typename viennagrid::result_of::coord<SomethingT>::type
  distance(SomethingT const & el1,
           spatial_point<CoordT, CoordinateSystemT> const & el2)
  {
    return detail::distance_impl( default_point_accessor(el1), el1, el2 );
  }

  /** @brief Returns the distance between a point and an element/segment/meshs using the default point accessor*/
  template <typename CoordT, typename CoordinateSystemT, typename SomethingT>
  typename viennagrid::result_of::coord<SomethingT>::type
  distance(spatial_point<CoordT, CoordinateSystemT> const & el1,
           SomethingT const & el2)
  {
    return detail::distance_impl( default_point_accessor(el2), el1, el2 );
  }

  /** @brief Returns the Euclidian distance between two points */
  template <typename CoordT1, typename CoordinateSystemT1, typename CoordT2, typename CoordinateSystemT2>
  typename viennagrid::result_of::coord< spatial_point<CoordT1, CoordinateSystemT1> >::type
  distance(spatial_point<CoordT1, CoordinateSystemT1> const & el1,
           spatial_point<CoordT2, CoordinateSystemT2> const & el2)
  {
    return detail::distance_impl( el1, el2 );
  }

  /** @brief Returns the Euclidian distance between the boundary of a segment and a line */
  template<typename WrappedMeshConfigT, typename SegmentationT>
  typename result_of::coord< segment_handle<SegmentationT> >::type distance( element<line_tag, WrappedMeshConfigT> const & line, segment_handle<SegmentationT> const & segment_handle )
  {
    typedef viennagrid::segment_handle<SegmentationT> SegmentHandleType;
    typedef typename result_of::const_line_range<SegmentHandleType>::type ConstLineRangeType;
    typedef typename result_of::iterator<ConstLineRangeType>::type ConstLineIteratorType;

    typedef typename result_of::coord<SegmentHandleType>::type CoordType;

    ConstLineRangeType lines(segment_handle);
    if (lines.empty())
      return -1;

    ConstLineIteratorType lit = lines.begin();
    CoordType min_distance = distance(line, *(lit++));

    for (; lit != lines.end(); ++lit)
    {
      CoordType current_distance = distance(line, *lit);
      if (current_distance < min_distance)
        min_distance = current_distance;
    }

    return min_distance;
  }

  template<typename SegmentationT, typename WrappedMeshConfigT>
  typename result_of::coord< segment_handle<SegmentationT> >::type distance( segment_handle<SegmentationT> const & segment_handle, element<line_tag, WrappedMeshConfigT> const & line )
  {
    return distance( line, segment_handle );
  }

  /** @brief Returns the distance between elements, segments and/or meshs
    *
    * @param accessor     Accessor functor for obtaining a point from a vertex
    * @param el1          The first element/mesh/vertex
    * @param el2          The second element/mesh/vertex
    */
  template <typename PointAccessorT, typename SomethingT1, typename SomethingT2>
  typename viennagrid::result_of::coord<SomethingT1>::type
  boundary_distance(PointAccessorT const accessor,
                    SomethingT1 const & el1,
                    SomethingT2 const & el2)
  {
    return detail::boundary_distance_impl(accessor, el1, el2);
  }

  /** @brief Returns the distance between elements, segments and/or meshs */
  template <typename SomethingT1, typename SomethingT2>
  typename viennagrid::result_of::coord<SomethingT1>::type
  boundary_distance(SomethingT1 const & el1,
                    SomethingT2 const & el2)
  {
    return detail::boundary_distance_impl( default_point_accessor(el1), el1, el2 );
  }

  /** @brief Returns the distance between a point and an element, segment and/or mesh */
  template <typename SomethingT, typename CoordT, typename CoordinateSystemT>
  typename viennagrid::result_of::coord<SomethingT>::type
  boundary_distance(SomethingT const & el1,
                    spatial_point<CoordT, CoordinateSystemT> const & el2)
  {
    return detail::boundary_distance_impl( default_point_accessor(el1), el1, el2 );
  }

  /** @brief Returns the distance between a point and an element, segment and/or mesh */
  template <typename CoordT, typename CoordinateSystemT, typename SomethingT>
  typename viennagrid::result_of::coord<SomethingT>::type
  boundary_distance(spatial_point<CoordT, CoordinateSystemT> const & el1,
                    SomethingT const & el2)
  {
    return detail::boundary_distance_impl( default_point_accessor(el2), el1, el2 );
  }

} //namespace viennagrid
#endif
<commit_msg>Delete distance.hpp<commit_after><|endoftext|>


<commit_before>// Copyright (C) 2014 Oliver Schulz <oschulz@mpp.mpg.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software 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.

#include "Bric.h"

#include <iostream>
#include <algorithm>

#include "TypeReflection.h"

#include "format.h"

using namespace std;

namespace dbrx {

PropPath BricComponent::absolutePath() const {
	return hasParent() ? parent().absolutePath() % name() : name();
}

void Bric::Terminal::connectInputToInner(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (!sourcePath.empty()) throw runtime_error("Couldn't resolve source path %s during input lookup, terminal \"%s\" has no inner components"_format(sourcePath, absolutePath()));
	else bric.connectOwnInputTo(inputName, *this);
}

const Name Bric::s_defaultInputName("input");
const Name Bric::s_defaultOutputName("output");
const Name Bric::s_bricTypeKey("type");

void Bric::registerComponent(BricComponent* component) {
	if (component->name() == s_bricTypeKey) throw invalid_argument("Can't add component with reserved name \"%s\" to bric \"%s\""_format(component->name(), absolutePath()));
	if (component->name().empty()) throw invalid_argument("Can't register BricComponent with empty name in bric \"%s\""_format(absolutePath()));

	auto r = m_components.find(component->name());
	if (r != m_components.end()) throw invalid_argument("Can't add duplicate component with name \"%s\" to bric \"%s\""_format(component->name(), absolutePath()));
	m_components[component->name()] = component;
}

void Bric::registerBric(Bric* bric)
	{ registerComponent(bric); m_brics[bric->name()] = bric; }

void Bric::registerTerminal(Terminal* terminal)
	{ registerComponent(terminal); m_terminals[terminal->name()] = terminal; }

void Bric::registerParam(ParamTerminal* param)
	{ registerTerminal(param); m_params[param->name()] = param; }

void Bric::registerOutput(OutputTerminal* output) {
	if (!canHaveOutputs()) throw invalid_argument("Bric \"%s\" cannot have outputs"_format(absolutePath()));
	registerTerminal(output);
	m_outputs[output->name()] = output;
}

void Bric::registerInput(InputTerminal* input) {
	if (!canHaveInputs()) throw invalid_argument("Bric \"%s\" cannot have inputs"_format(absolutePath()));
	registerTerminal(input);
	m_inputs[input->name()] = input;
}

void Bric::addDynBric(Name bricName, const std::string& className) {
	unique_ptr<Bric> dynBric(TypeReflection(className).newInstance<Bric>());
	registerBric(dynBric.get());
	m_dynBrics[dynBric->name()] = std::move(dynBric);
}

void Bric::connectInputToInner(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (sourcePath.empty()) {
		auto found = m_components.find(s_defaultOutputName);
		if (found != m_components.end()) found->second->connectInputToInner(bric, inputName, sourcePath);
	} else {
		auto found = m_components.find(sourcePath.front().asName());
		if (found != m_components.end()) found->second->connectInputToInner(bric, inputName, sourcePath.tail());
		else throw runtime_error("Couldn't resolve source path \"%s\" during input lookup, no such component in bric \"%s\""_format(sourcePath, absolutePath()));
	}
}

void Bric::connectInputToSiblingOrUp(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (sourcePath.empty()) throw runtime_error("Empty source path during input lookup in bric \"%s\""_format(absolutePath()));
	Name siblingName = sourcePath.front().asName();
	if (siblingName == name()) connectInputToInner(bric, inputName, sourcePath.tail());
	else {
		if (hasParent()) {
			auto found = parent().m_brics.find(siblingName);
			if (found != parent().m_brics.end()) {
				Bric* sibling = found->second;
				sibling->connectInputToInner(bric, inputName, sourcePath.tail());
				addDependency(sibling);
			}
		} else throw runtime_error("Reached top-level Bric \"%s\" during input lookup"_format(absolutePath()));
	}
}

void Bric::connectOwnInputTo(Name inputName, const Terminal& terminal) {
	auto found = m_inputs.find(inputName);
	if (found != m_inputs.end()) found->second->connectTo(terminal);
	else throw invalid_argument("Can't connect non-existing input \"%s\" to terminal \"%s\""_format(inputName, terminal.absolutePath()));
}

void Bric::applyConfig(const PropVal& config) {
	for (const auto& entry: config.asProps()) {
		Name componentName = entry.first.asName();
		const PropVal& componentConfig = entry.second;
		if (componentName != s_bricTypeKey) {
			const auto& found = m_components.find(componentName);
			if (found != m_components.end())
				m_components[entry.first.asName()]->applyConfig(componentConfig);
			else if (subBricsFromConfig()) {
				if (!componentConfig.isProps()) throw invalid_argument("Invalid configuration format for dynamic sub-bric \"%s\" in bric \"%s\""_format(componentName, absolutePath()));
				Props subBricProps = entry.second.asProps();
				const std::string className = entry.second[s_bricTypeKey].asString();
				addDynBric(componentName, className);
			}
			else throw runtime_error("Invalid configuration, bric \"%s\" doesn't have a component named \"%s\""_format(absolutePath(), componentName));
		}
	}
}

PropVal Bric::getConfig() const  {
	Props props;
	for (const auto& entry: m_components) {
		PropVal componentConfig = entry.second->getConfig();
		if (! componentConfig.isNone())	props[entry.second->name()] = std::move(componentConfig);
	}
	props[s_bricTypeKey] = TypeReflection(typeid(this)).name();
	return PropVal(std::move(props));
}

const Bric::Terminal& Bric::getTerminal(Name terminalName) const {
	auto r = m_terminals.find(terminalName);
	if (r == m_terminals.end()) throw invalid_argument("No terminal \"%s\" found in bric \"%s\""_format(terminalName, absolutePath()));
	else return *r->second;
}

Bric::Terminal& Bric::getTerminal(Name terminalName) {
	auto r = m_terminals.find(terminalName);
	if (r == m_terminals.end()) throw invalid_argument("No terminal \"%s\" found in bric \"%s\""_format(terminalName, absolutePath()));
	else return *r->second;
}

const Bric::Terminal& Bric::getTerminal(Name terminalName, const std::type_info& typeInfo) const {
	const Bric::Terminal& terminal = getTerminal(terminalName);
	if (terminal.value().typeInfo() != typeInfo)
		throw runtime_error("Type of terminal \"%s\" doesn't match requested type \"%s\""_format(terminal.absolutePath(), terminal.typeInfo().name()));
	return terminal;
}

Bric::Terminal& Bric::getTerminal(Name terminalName, const std::type_info& typeInfo) {
	Bric::Terminal& terminal = getTerminal(terminalName);
	if (terminal.value().typeInfo() != typeInfo)
		throw runtime_error("Type of terminal \"%s\" doesn't match requested type \"%s\""_format(terminal.absolutePath(), terminal.typeInfo().name()));
	return terminal;
}

const Bric::OutputTerminal& Bric::getOutput(Name outputName) const
	{ return dynamic_cast<const Bric::OutputTerminal&>(getTerminal(outputName)); }

Bric::OutputTerminal& Bric::getOutput(Name outputName)
	{ return dynamic_cast<Bric::OutputTerminal&>(getTerminal(outputName)); }

const Bric::OutputTerminal& Bric::getOutput(Name outputName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::OutputTerminal&>(getTerminal(outputName, typeInfo)); }

Bric::OutputTerminal& Bric::getOutput(Name outputName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::OutputTerminal&>(getTerminal(outputName, typeInfo)); }

const Bric::InputTerminal& Bric::getInput(Name inputName) const
	{ return dynamic_cast<const Bric::InputTerminal&>(getTerminal(inputName)); }

Bric::InputTerminal& Bric::getInput(Name inputName)
	{ return dynamic_cast<Bric::InputTerminal&>(getTerminal(inputName)); }

const Bric::InputTerminal& Bric::getInput(Name inputName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::InputTerminal&>(getTerminal(inputName, typeInfo)); }

Bric::InputTerminal& Bric::getInput(Name inputName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::InputTerminal&>(getTerminal(inputName, typeInfo)); }

const Bric::ParamTerminal& Bric::getParam(Name paramName) const
	{ return dynamic_cast<const Bric::ParamTerminal&>(getTerminal(paramName)); }

Bric::ParamTerminal& Bric::getParam(Name paramName)
	{ return dynamic_cast<Bric::ParamTerminal&>(getTerminal(paramName)); }

const Bric::ParamTerminal& Bric::getParam(Name paramName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::ParamTerminal&>(getTerminal(paramName, typeInfo)); }

Bric::ParamTerminal& Bric::getParam(Name paramName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::ParamTerminal&>(getTerminal(paramName, typeInfo)); }

void Bric::connectInputs() {
	m_deps.clear();
	for (const auto& input: m_inputs)
		connectInputToSiblingOrUp(*this, input.second->name(), input.second->source());
	for (const auto& brics: m_brics)
		brics.second->connectInputs();
}

std::ostream & Bric::printInfo(std::ostream &os) const {
	os << "Bric " << name() << ":" << endl;

	if (! m_inputs.empty()) {
		os << "  Inputs: ";
		for (auto const &x: m_inputs) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	if (! m_outputs.empty()) {
		os << "  Outputs: ";
		for (auto const &x: m_outputs) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	if (! m_params.empty()) {
		os << "  Params: ";
		for (auto const &x: m_params) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	return os;
}

} // namespace dbrx
<commit_msg>Fixed Bric implementation, using at() instead of operator[] for map reads<commit_after>// Copyright (C) 2014 Oliver Schulz <oschulz@mpp.mpg.de>

// This is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This software 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.

#include "Bric.h"

#include <iostream>
#include <algorithm>

#include "TypeReflection.h"

#include "format.h"

using namespace std;

namespace dbrx {

PropPath BricComponent::absolutePath() const {
	return hasParent() ? parent().absolutePath() % name() : name();
}

void Bric::Terminal::connectInputToInner(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (!sourcePath.empty()) throw runtime_error("Couldn't resolve source path %s during input lookup, terminal \"%s\" has no inner components"_format(sourcePath, absolutePath()));
	else bric.connectOwnInputTo(inputName, *this);
}

const Name Bric::s_defaultInputName("input");
const Name Bric::s_defaultOutputName("output");
const Name Bric::s_bricTypeKey("type");

void Bric::registerComponent(BricComponent* component) {
	if (component->name() == s_bricTypeKey) throw invalid_argument("Can't add component with reserved name \"%s\" to bric \"%s\""_format(component->name(), absolutePath()));
	if (component->name().empty()) throw invalid_argument("Can't register BricComponent with empty name in bric \"%s\""_format(absolutePath()));

	auto r = m_components.find(component->name());
	if (r != m_components.end()) throw invalid_argument("Can't add duplicate component with name \"%s\" to bric \"%s\""_format(component->name(), absolutePath()));
	m_components[component->name()] = component;
}

void Bric::registerBric(Bric* bric)
	{ registerComponent(bric); m_brics[bric->name()] = bric; }

void Bric::registerTerminal(Terminal* terminal)
	{ registerComponent(terminal); m_terminals[terminal->name()] = terminal; }

void Bric::registerParam(ParamTerminal* param)
	{ registerTerminal(param); m_params[param->name()] = param; }

void Bric::registerOutput(OutputTerminal* output) {
	if (!canHaveOutputs()) throw invalid_argument("Bric \"%s\" cannot have outputs"_format(absolutePath()));
	registerTerminal(output);
	m_outputs[output->name()] = output;
}

void Bric::registerInput(InputTerminal* input) {
	if (!canHaveInputs()) throw invalid_argument("Bric \"%s\" cannot have inputs"_format(absolutePath()));
	registerTerminal(input);
	m_inputs[input->name()] = input;
}

void Bric::addDynBric(Name bricName, const std::string& className) {
	unique_ptr<Bric> dynBric(TypeReflection(className).newInstance<Bric>());
	registerBric(dynBric.get());
	m_dynBrics[dynBric->name()] = std::move(dynBric);
}

void Bric::connectInputToInner(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (sourcePath.empty()) {
		auto found = m_components.find(s_defaultOutputName);
		if (found != m_components.end()) found->second->connectInputToInner(bric, inputName, sourcePath);
	} else {
		auto found = m_components.find(sourcePath.front().asName());
		if (found != m_components.end()) found->second->connectInputToInner(bric, inputName, sourcePath.tail());
		else throw runtime_error("Couldn't resolve source path \"%s\" during input lookup, no such component in bric \"%s\""_format(sourcePath, absolutePath()));
	}
}

void Bric::connectInputToSiblingOrUp(Bric &bric, Name inputName, PropPath::Fragment sourcePath) {
	if (sourcePath.empty()) throw runtime_error("Empty source path during input lookup in bric \"%s\""_format(absolutePath()));
	Name siblingName = sourcePath.front().asName();
	if (siblingName == name()) connectInputToInner(bric, inputName, sourcePath.tail());
	else {
		if (hasParent()) {
			auto found = parent().m_brics.find(siblingName);
			if (found != parent().m_brics.end()) {
				Bric* sibling = found->second;
				sibling->connectInputToInner(bric, inputName, sourcePath.tail());
				addDependency(sibling);
			}
		} else throw runtime_error("Reached top-level Bric \"%s\" during input lookup"_format(absolutePath()));
	}
}

void Bric::connectOwnInputTo(Name inputName, const Terminal& terminal) {
	auto found = m_inputs.find(inputName);
	if (found != m_inputs.end()) found->second->connectTo(terminal);
	else throw invalid_argument("Can't connect non-existing input \"%s\" to terminal \"%s\""_format(inputName, terminal.absolutePath()));
}

void Bric::applyConfig(const PropVal& config) {
	for (const auto& entry: config.asProps()) {
		Name componentName = entry.first.asName();
		const PropVal& componentConfig = entry.second;
		if (componentName != s_bricTypeKey) {
			const auto& found = m_components.find(componentName);
			if (found != m_components.end())
				m_components.at(entry.first.asName())->applyConfig(componentConfig);
			else if (subBricsFromConfig()) {
				if (!componentConfig.isProps()) throw invalid_argument("Invalid configuration format for dynamic sub-bric \"%s\" in bric \"%s\""_format(componentName, absolutePath()));
				Props subBricProps = entry.second.asProps();
				const std::string className = entry.second.at(s_bricTypeKey).asString();
				addDynBric(componentName, className);
			}
			else throw runtime_error("Invalid configuration, bric \"%s\" doesn't have a component named \"%s\""_format(absolutePath(), componentName));
		}
	}
}

PropVal Bric::getConfig() const  {
	Props props;
	for (const auto& entry: m_components) {
		PropVal componentConfig = entry.second->getConfig();
		if (! componentConfig.isNone())	props[entry.second->name()] = std::move(componentConfig);
	}
	props[s_bricTypeKey] = TypeReflection(typeid(this)).name();
	return PropVal(std::move(props));
}

const Bric::Terminal& Bric::getTerminal(Name terminalName) const {
	auto r = m_terminals.find(terminalName);
	if (r == m_terminals.end()) throw invalid_argument("No terminal \"%s\" found in bric \"%s\""_format(terminalName, absolutePath()));
	else return *r->second;
}

Bric::Terminal& Bric::getTerminal(Name terminalName) {
	auto r = m_terminals.find(terminalName);
	if (r == m_terminals.end()) throw invalid_argument("No terminal \"%s\" found in bric \"%s\""_format(terminalName, absolutePath()));
	else return *r->second;
}

const Bric::Terminal& Bric::getTerminal(Name terminalName, const std::type_info& typeInfo) const {
	const Bric::Terminal& terminal = getTerminal(terminalName);
	if (terminal.value().typeInfo() != typeInfo)
		throw runtime_error("Type of terminal \"%s\" doesn't match requested type \"%s\""_format(terminal.absolutePath(), terminal.typeInfo().name()));
	return terminal;
}

Bric::Terminal& Bric::getTerminal(Name terminalName, const std::type_info& typeInfo) {
	Bric::Terminal& terminal = getTerminal(terminalName);
	if (terminal.value().typeInfo() != typeInfo)
		throw runtime_error("Type of terminal \"%s\" doesn't match requested type \"%s\""_format(terminal.absolutePath(), terminal.typeInfo().name()));
	return terminal;
}

const Bric::OutputTerminal& Bric::getOutput(Name outputName) const
	{ return dynamic_cast<const Bric::OutputTerminal&>(getTerminal(outputName)); }

Bric::OutputTerminal& Bric::getOutput(Name outputName)
	{ return dynamic_cast<Bric::OutputTerminal&>(getTerminal(outputName)); }

const Bric::OutputTerminal& Bric::getOutput(Name outputName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::OutputTerminal&>(getTerminal(outputName, typeInfo)); }

Bric::OutputTerminal& Bric::getOutput(Name outputName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::OutputTerminal&>(getTerminal(outputName, typeInfo)); }

const Bric::InputTerminal& Bric::getInput(Name inputName) const
	{ return dynamic_cast<const Bric::InputTerminal&>(getTerminal(inputName)); }

Bric::InputTerminal& Bric::getInput(Name inputName)
	{ return dynamic_cast<Bric::InputTerminal&>(getTerminal(inputName)); }

const Bric::InputTerminal& Bric::getInput(Name inputName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::InputTerminal&>(getTerminal(inputName, typeInfo)); }

Bric::InputTerminal& Bric::getInput(Name inputName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::InputTerminal&>(getTerminal(inputName, typeInfo)); }

const Bric::ParamTerminal& Bric::getParam(Name paramName) const
	{ return dynamic_cast<const Bric::ParamTerminal&>(getTerminal(paramName)); }

Bric::ParamTerminal& Bric::getParam(Name paramName)
	{ return dynamic_cast<Bric::ParamTerminal&>(getTerminal(paramName)); }

const Bric::ParamTerminal& Bric::getParam(Name paramName, const std::type_info& typeInfo) const
	{ return dynamic_cast<const Bric::ParamTerminal&>(getTerminal(paramName, typeInfo)); }

Bric::ParamTerminal& Bric::getParam(Name paramName, const std::type_info& typeInfo)
	{ return dynamic_cast<Bric::ParamTerminal&>(getTerminal(paramName, typeInfo)); }

void Bric::connectInputs() {
	m_deps.clear();
	for (const auto& input: m_inputs)
		connectInputToSiblingOrUp(*this, input.second->name(), input.second->source());
	for (const auto& brics: m_brics)
		brics.second->connectInputs();
}

std::ostream & Bric::printInfo(std::ostream &os) const {
	os << "Bric " << name() << ":" << endl;

	if (! m_inputs.empty()) {
		os << "  Inputs: ";
		for (auto const &x: m_inputs) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	if (! m_outputs.empty()) {
		os << "  Outputs: ";
		for (auto const &x: m_outputs) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	if (! m_params.empty()) {
		os << "  Params: ";
		for (auto const &x: m_params) os << " " << x.second->name() << "(" << x.second->value().typeInfo().name() << ")";
		os << endl;
	}

	return os;
}

} // namespace dbrx
<|endoftext|>


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

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<commit_msg>Make WebDevToolsAgentClient::sendMessageToFrontendOnIOThread virtual.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebDevToolsMessageTransport;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

namespace {

class WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {
 public:
  void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {
    DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));
  }
};

}  // namespace

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  WebDevToolsMessageTransportImpl transport;
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      &transport,
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<|endoftext|>


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

#include "chrome/renderer/notification_provider.h"

#include "base/string_util.h"
#include "base/task.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"

using WebKit::WebDocument;
using WebKit::WebNotification;
using WebKit::WebNotificationPresenter;
using WebKit::WebNotificationPermissionCallback;
using WebKit::WebString;
using WebKit::WebURL;

NotificationProvider::NotificationProvider(RenderView* view)
    : view_(view) {
}

bool NotificationProvider::show(const WebNotification& notification) {
  int notification_id = manager_.RegisterNotification(notification);
  if (notification.isHTML())
    return ShowHTML(notification, notification_id);
  else
    return ShowText(notification, notification_id);
}

void NotificationProvider::cancel(const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id));
}

void NotificationProvider::objectDestroyed(
    const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    manager_.UnregisterNotification(id);
}

WebNotificationPresenter::Permission NotificationProvider::checkPermission(
    const WebURL& url, WebDocument* document) {
  int permission;
  Send(new ViewHostMsg_CheckNotificationPermission(
          view_->routing_id(),
          url,
          document ? UTF16ToASCII(document->applicationID()) : "",
          &permission));
  return static_cast<WebNotificationPresenter::Permission>(permission);
}

void NotificationProvider::requestPermission(
    const WebString& origin, WebNotificationPermissionCallback* callback) {
  // We only request permission in response to a user gesture.
  if (!view_->webview()->mainFrame()->isProcessingUserGesture())
    return;

  int id = manager_.RegisterPermissionRequest(callback);

  Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(),
                                                     GURL(origin), id));
}

bool NotificationProvider::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message)
    IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay);
    IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError);
    IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose);
    IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone,
                        OnPermissionRequestComplete);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void NotificationProvider::OnNavigate() {
  //  manager_.Clear();
}

bool NotificationProvider::ShowHTML(const WebNotification& notification,
                                    int id) {
  // Disallow HTML notifications from non-HTTP schemes.
  GURL url = notification.url();
  if (!url.SchemeIs(chrome::kHttpScheme) &&
      !url.SchemeIs(chrome::kHttpsScheme) &&
      !url.SchemeIs(chrome::kExtensionScheme))
    return false;

  DCHECK(notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              notification.url(), id));
}

bool NotificationProvider::ShowText(const WebNotification& notification,
                                    int id) {
  DCHECK(!notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              GURL(notification.icon()),
              notification.title(), notification.body(), id));
}

void NotificationProvider::OnDisplay(int id) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before it was actually displayed to the user.
  if (found)
    notification.dispatchDisplayEvent();
}

void NotificationProvider::OnError(int id, const WebString& message) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the error occurred.
  if (found)
    notification.dispatchErrorEvent(message);
}

void NotificationProvider::OnClose(int id, bool by_user) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the associated toast was closed by the user.
  if (found) {
    notification.dispatchCloseEvent(by_user);
    manager_.UnregisterNotification(id);
  }
}

void NotificationProvider::OnPermissionRequestComplete(int id) {
  WebNotificationPermissionCallback* callback = manager_.GetCallback(id);
  DCHECK(callback);
  callback->permissionRequestComplete();
  manager_.OnPermissionRequestComplete(id);
}

bool NotificationProvider::Send(IPC::Message* message) {
  return RenderThread::current()->Send(message);
}
<commit_msg>Correct a mistake I made on a previous submission by commenting out an important line!<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/notification_provider.h"

#include "base/string_util.h"
#include "base/task.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebNotificationPermissionCallback.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"

using WebKit::WebDocument;
using WebKit::WebNotification;
using WebKit::WebNotificationPresenter;
using WebKit::WebNotificationPermissionCallback;
using WebKit::WebString;
using WebKit::WebURL;

NotificationProvider::NotificationProvider(RenderView* view)
    : view_(view) {
}

bool NotificationProvider::show(const WebNotification& notification) {
  int notification_id = manager_.RegisterNotification(notification);
  if (notification.isHTML())
    return ShowHTML(notification, notification_id);
  else
    return ShowText(notification, notification_id);
}

void NotificationProvider::cancel(const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    Send(new ViewHostMsg_CancelDesktopNotification(view_->routing_id(), id));
}

void NotificationProvider::objectDestroyed(
    const WebNotification& notification) {
  int id;
  bool id_found = manager_.GetId(notification, id);
  // Won't be found if the notification has already been closed by the user.
  if (id_found)
    manager_.UnregisterNotification(id);
}

WebNotificationPresenter::Permission NotificationProvider::checkPermission(
    const WebURL& url, WebDocument* document) {
  int permission;
  Send(new ViewHostMsg_CheckNotificationPermission(
          view_->routing_id(),
          url,
          document ? UTF16ToASCII(document->applicationID()) : "",
          &permission));
  return static_cast<WebNotificationPresenter::Permission>(permission);
}

void NotificationProvider::requestPermission(
    const WebString& origin, WebNotificationPermissionCallback* callback) {
  // We only request permission in response to a user gesture.
  if (!view_->webview()->mainFrame()->isProcessingUserGesture())
    return;

  int id = manager_.RegisterPermissionRequest(callback);

  Send(new ViewHostMsg_RequestNotificationPermission(view_->routing_id(),
                                                     GURL(origin), id));
}

bool NotificationProvider::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NotificationProvider, message)
    IPC_MESSAGE_HANDLER(ViewMsg_PostDisplayToNotificationObject, OnDisplay);
    IPC_MESSAGE_HANDLER(ViewMsg_PostErrorToNotificationObject, OnError);
    IPC_MESSAGE_HANDLER(ViewMsg_PostCloseToNotificationObject, OnClose);
    IPC_MESSAGE_HANDLER(ViewMsg_PermissionRequestDone,
                        OnPermissionRequestComplete);
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void NotificationProvider::OnNavigate() {
  manager_.Clear();
}

bool NotificationProvider::ShowHTML(const WebNotification& notification,
                                    int id) {
  // Disallow HTML notifications from non-HTTP schemes.
  GURL url = notification.url();
  if (!url.SchemeIs(chrome::kHttpScheme) &&
      !url.SchemeIs(chrome::kHttpsScheme) &&
      !url.SchemeIs(chrome::kExtensionScheme))
    return false;

  DCHECK(notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotification(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              notification.url(), id));
}

bool NotificationProvider::ShowText(const WebNotification& notification,
                                    int id) {
  DCHECK(!notification.isHTML());
  return Send(new ViewHostMsg_ShowDesktopNotificationText(view_->routing_id(),
              GURL(view_->webview()->mainFrame()->url()).GetOrigin(),
              GURL(notification.icon()),
              notification.title(), notification.body(), id));
}

void NotificationProvider::OnDisplay(int id) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before it was actually displayed to the user.
  if (found)
    notification.dispatchDisplayEvent();
}

void NotificationProvider::OnError(int id, const WebString& message) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the error occurred.
  if (found)
    notification.dispatchErrorEvent(message);
}

void NotificationProvider::OnClose(int id, bool by_user) {
  WebNotification notification;
  bool found = manager_.GetNotification(id, &notification);
  // |found| may be false if the WebNotification went out of scope in
  // the page before the associated toast was closed by the user.
  if (found) {
    notification.dispatchCloseEvent(by_user);
    manager_.UnregisterNotification(id);
  }
}

void NotificationProvider::OnPermissionRequestComplete(int id) {
  WebNotificationPermissionCallback* callback = manager_.GetCallback(id);
  DCHECK(callback);
  callback->permissionRequestComplete();
  manager_.OnPermissionRequestComplete(id);
}

bool NotificationProvider::Send(IPC::Message* message) {
  return RenderThread::current()->Send(message);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2014, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#define __STDC_LIMIT_MACROS

// Google Log
#include <glog/logging.h>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/hostname.h>

// e
#include <e/popt.h>

// BusyBee
#include <busybee_utils.h>

// HyperDex
#include "daemon/daemon.h"

int
main(int argc, const char* argv[])
{
    bool daemonize = true;
    const char* data = ".";
    const char* log = NULL;
    const char* pidfile = "";
    bool has_pidfile = false;
    bool listen = false;
    const char* listen_host = "auto";
    long listen_port = 2012;
    bool coordinator = false;
    const char* coordinator_host = "127.0.0.1";
    long coordinator_port = 1982;
    long threads = 0;
    bool log_immediate = false;

    e::argparser ap;
    ap.autohelp();
    ap.arg().name('d', "daemon")
            .description("run in the background")
            .set_true(&daemonize);
    ap.arg().name('f', "foreground")
            .description("run in the foreground")
            .set_false(&daemonize);
    ap.arg().name('D', "data")
            .description("store persistent state in this directory (default: .)")
            .metavar("dir").as_string(&data);
    ap.arg().name('L', "log")
            .description("store logs in this directory (default: --data)")
            .metavar("dir").as_string(&log);
    ap.arg().long_name("pidfile")
            .description("write the PID to a file (default: don't)")
            .metavar("file").as_string(&pidfile).set_true(&has_pidfile);
    ap.arg().name('l', "listen")
            .description("listen on a specific IP address (default: auto)")
            .metavar("IP").as_string(&listen_host).set_true(&listen);
    ap.arg().name('p', "listen-port")
            .description("listen on an alternative port (default: 1982)")
            .metavar("port").as_long(&listen_port).set_true(&listen);
    ap.arg().name('c', "coordinator")
            .description("join an existing HyperDex cluster through IP address or hostname")
            .metavar("addr").as_string(&coordinator_host).set_true(&coordinator);
    ap.arg().name('P', "coordinator-port")
            .description("connect to an alternative port on the coordinator (default: 1982)")
            .metavar("port").as_long(&coordinator_port).set_true(&coordinator);
    ap.arg().name('t', "threads")
            .description("the number of threads which will handle network traffic")
            .metavar("N").as_long(&threads);
    ap.arg().long_name("log-immediate")
            .description("immediately flush all log output")
            .set_true(&log_immediate).hidden();

    if (!ap.parse(argc, argv))
    {
        return EXIT_FAILURE;
    }

    if (ap.args_sz() != 0)
    {
        std::cerr << "command takes no positional arguments\n" << std::endl;
        ap.usage();
        return EXIT_FAILURE;
    }

    if (listen_port >= (1 << 16))
    {
        std::cerr << "listen-port is out of range" << std::endl;
        return EXIT_FAILURE;
    }

    if (coordinator_port >= (1 << 16))
    {
        std::cerr << "coordinator-port is out of range" << std::endl;
        return EXIT_FAILURE;
    }

    po6::net::ipaddr listen_ip;
    po6::net::location bind_to;

    if (strcmp(listen_host, "auto") == 0)
    {
        if (!busybee_discover(&listen_ip))
        {
            std::cerr << "cannot automatically discover local address; specify one manually" << std::endl;
            return EXIT_FAILURE;
        }

        bind_to = po6::net::location(listen_ip, listen_port);
    }
    else
    {
        try
        {
            listen_ip = po6::net::ipaddr(listen_host);
            bind_to = po6::net::location(listen_ip, listen_port);
        }
        catch (std::invalid_argument& e)
        {
            // fallthrough
        }

        if (bind_to == po6::net::location())
        {
            bind_to = po6::net::hostname(listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP);
            bind_to.port = listen_port;
        }
    }

    if (bind_to == po6::net::location())
    {
        std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl;
        return EXIT_FAILURE;
    }

    if (bind_to.address == po6::net::ipaddr("0.0.0.0"))
    {
        std::cerr << "cannot bind to " << bind_to << " because it is not routable" << std::endl;
        return EXIT_FAILURE;
    }

    google::InitGoogleLogging(argv[0]);
    google::InstallFailureSignalHandler();

    if (log_immediate)
    {
        FLAGS_logbufsecs = 0;
    }

    try
    {
        hyperdex::daemon d;

        if (threads <= 0)
        {
            threads += sysconf(_SC_NPROCESSORS_ONLN);

            if (threads <= 0)
            {
                std::cerr << "cannot create a non-positive number of threads" << std::endl;
                return EXIT_FAILURE;
            }
        }
        else if (threads > 512)
        {
            std::cerr << "refusing to create more than 512 threads" << std::endl;
            return EXIT_FAILURE;
        }

        return d.run(daemonize,
                     std::string(data),
                     std::string(log ? log : data),
                     std::string(pidfile), has_pidfile,
                     listen, bind_to,
                     coordinator, po6::net::hostname(coordinator_host, coordinator_port),
                     threads);
    }
    catch (std::exception& e)
    {
        std::cerr << "error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
}
<commit_msg>Add missing stdexcept header<commit_after>// Copyright (c) 2011-2014, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#define __STDC_LIMIT_MACROS

// STL
#include <stdexcept>

// Google Log
#include <glog/logging.h>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/hostname.h>

// e
#include <e/popt.h>

// BusyBee
#include <busybee_utils.h>

// HyperDex
#include "daemon/daemon.h"

int
main(int argc, const char* argv[])
{
    bool daemonize = true;
    const char* data = ".";
    const char* log = NULL;
    const char* pidfile = "";
    bool has_pidfile = false;
    bool listen = false;
    const char* listen_host = "auto";
    long listen_port = 2012;
    bool coordinator = false;
    const char* coordinator_host = "127.0.0.1";
    long coordinator_port = 1982;
    long threads = 0;
    bool log_immediate = false;

    e::argparser ap;
    ap.autohelp();
    ap.arg().name('d', "daemon")
            .description("run in the background")
            .set_true(&daemonize);
    ap.arg().name('f', "foreground")
            .description("run in the foreground")
            .set_false(&daemonize);
    ap.arg().name('D', "data")
            .description("store persistent state in this directory (default: .)")
            .metavar("dir").as_string(&data);
    ap.arg().name('L', "log")
            .description("store logs in this directory (default: --data)")
            .metavar("dir").as_string(&log);
    ap.arg().long_name("pidfile")
            .description("write the PID to a file (default: don't)")
            .metavar("file").as_string(&pidfile).set_true(&has_pidfile);
    ap.arg().name('l', "listen")
            .description("listen on a specific IP address (default: auto)")
            .metavar("IP").as_string(&listen_host).set_true(&listen);
    ap.arg().name('p', "listen-port")
            .description("listen on an alternative port (default: 1982)")
            .metavar("port").as_long(&listen_port).set_true(&listen);
    ap.arg().name('c', "coordinator")
            .description("join an existing HyperDex cluster through IP address or hostname")
            .metavar("addr").as_string(&coordinator_host).set_true(&coordinator);
    ap.arg().name('P', "coordinator-port")
            .description("connect to an alternative port on the coordinator (default: 1982)")
            .metavar("port").as_long(&coordinator_port).set_true(&coordinator);
    ap.arg().name('t', "threads")
            .description("the number of threads which will handle network traffic")
            .metavar("N").as_long(&threads);
    ap.arg().long_name("log-immediate")
            .description("immediately flush all log output")
            .set_true(&log_immediate).hidden();

    if (!ap.parse(argc, argv))
    {
        return EXIT_FAILURE;
    }

    if (ap.args_sz() != 0)
    {
        std::cerr << "command takes no positional arguments\n" << std::endl;
        ap.usage();
        return EXIT_FAILURE;
    }

    if (listen_port >= (1 << 16))
    {
        std::cerr << "listen-port is out of range" << std::endl;
        return EXIT_FAILURE;
    }

    if (coordinator_port >= (1 << 16))
    {
        std::cerr << "coordinator-port is out of range" << std::endl;
        return EXIT_FAILURE;
    }

    po6::net::ipaddr listen_ip;
    po6::net::location bind_to;

    if (strcmp(listen_host, "auto") == 0)
    {
        if (!busybee_discover(&listen_ip))
        {
            std::cerr << "cannot automatically discover local address; specify one manually" << std::endl;
            return EXIT_FAILURE;
        }

        bind_to = po6::net::location(listen_ip, listen_port);
    }
    else
    {
        try
        {
            listen_ip = po6::net::ipaddr(listen_host);
            bind_to = po6::net::location(listen_ip, listen_port);
        }
        catch (std::invalid_argument& e)
        {
            // fallthrough
        }

        if (bind_to == po6::net::location())
        {
            bind_to = po6::net::hostname(listen_host, 0).lookup(AF_UNSPEC, IPPROTO_TCP);
            bind_to.port = listen_port;
        }
    }

    if (bind_to == po6::net::location())
    {
        std::cerr << "cannot interpret listen address as hostname or IP address" << std::endl;
        return EXIT_FAILURE;
    }

    if (bind_to.address == po6::net::ipaddr("0.0.0.0"))
    {
        std::cerr << "cannot bind to " << bind_to << " because it is not routable" << std::endl;
        return EXIT_FAILURE;
    }

    google::InitGoogleLogging(argv[0]);
    google::InstallFailureSignalHandler();

    if (log_immediate)
    {
        FLAGS_logbufsecs = 0;
    }

    try
    {
        hyperdex::daemon d;

        if (threads <= 0)
        {
            threads += sysconf(_SC_NPROCESSORS_ONLN);

            if (threads <= 0)
            {
                std::cerr << "cannot create a non-positive number of threads" << std::endl;
                return EXIT_FAILURE;
            }
        }
        else if (threads > 512)
        {
            std::cerr << "refusing to create more than 512 threads" << std::endl;
            return EXIT_FAILURE;
        }

        return d.run(daemonize,
                     std::string(data),
                     std::string(log ? log : data),
                     std::string(pidfile), has_pidfile,
                     listen, bind_to,
                     coordinator, po6::net::hostname(coordinator_host, coordinator_port),
                     threads);
    }
    catch (std::exception& e)
    {
        std::cerr << "error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>// RUN: %clang -c -g %s -o /dev/null
// Radar 8730409

class foo {
public:
#define x(a) virtual void v ## a (void)
x(1);
x(2);
x(3);
x(4);
x(5);
x(6);
x(7);
x(8);
x(9);
x(10);
x(11);
x(12);
x(13);
x(14);
x(15);
x(16);
x(17);
x(18);
x(19);
x(20);
x(21);
x(22);
x(23);
x(24);
x(25);
x(26);
x(27);
x(28);
x(29);
x(30);
x(31);
x(32);
x(33);
x(34);
x(35);
x(36);
x(37);
x(38);
x(39);
x(40);
x(41);
x(42);
x(43);
x(44);
x(45);
x(46);
x(47);
x(48);
x(49);
x(50);
x(51);
x(52);
x(53);
x(54);
x(55);
x(56);
x(57);
x(58);
x(59);
x(60);
x(61);
x(62);
x(63);
x(64);
x(65);
x(66);
x(67);
x(68);
x(69);
x(70);
x(71);
x(72);
x(73);
x(74);
x(75);
x(76);
x(77);
x(78);
x(79);
x(80);
x(81);
x(82);
x(83);
x(84);
x(85);
x(86);
x(87);
x(88);
x(89);
x(90);
x(91);
x(92);
x(93);
x(94);
x(95);
x(96);
x(97);
x(98);
x(99);
x(100);
x(101);
x(102);
x(103);
x(104);
x(105);
x(106);
x(107);
x(108);
x(109);
x(110);
x(111);
x(112);
x(113);
x(114);
x(115);
x(116);
x(117);
x(118);
x(119);
x(120);
x(121);
x(122);
x(123);
x(124);
x(125);
x(126);
x(127);
x(128);
x(129);
x(130);
x(131);
x(132);
x(133);
x(134);
x(135);
x(136);
x(137);
x(138);
x(139);
x(140);
x(141);
x(142);
x(143);
x(144);
x(145);
x(146);
x(147);
x(148);
x(149);
x(150);
x(151);
x(152);
x(153);
x(154);
x(155);
x(156);
x(157);
x(158);
x(159);
x(160);
x(161);
x(162);
x(163);
x(164);
x(165);
x(166);
x(167);
x(168);
x(169);
x(170);
x(171);
x(172);
x(173);
x(174);
x(175);
x(176);
x(177);
x(178);
x(179);
x(180);
x(181);
x(182);
x(183);
x(184);
x(185);
x(186);
x(187);
x(188);
x(189);
x(190);
x(191);
x(192);
x(193);
x(194);
x(195);
x(196);
x(197);
x(198);
x(199);
x(200);
x(201);
x(202);
x(203);
x(204);
x(205);
x(206);
x(207);
x(208);
x(209);
x(210);
x(211);
x(212);
x(213);
x(214);
x(215);
x(216);
x(217);
x(218);
x(219);
x(220);
x(221);
x(222);
x(223);
x(224);
x(225);
x(226);
x(227);
x(228);
x(229);
x(230);
x(231);
x(232);
x(233);
x(234);
x(235);
x(236);
x(237);
x(238);
x(239);
x(240);
x(241);
x(242);
x(243);
x(244);
x(245);
x(246);
x(247);
x(248);
x(249);
x(250);
x(251);
x(252);
x(253);
x(254);
x(255);
x(256);
x(257);
x(258);
x(259);
x(260);
x(261);
x(262);
x(263);
x(264);
x(265);
x(266);
x(267);
x(268);
x(269);
x(270);
x(271);
x(272);
x(273);
x(274);
x(275);
x(276);
x(277);
x(278);
x(279);
x(280);
x(281);
x(282);
x(283);
x(284);
x(285);
x(286);
x(287);
x(288);
x(289);
x(290);
x(291);
x(292);
x(293);
x(294);
x(295);
x(296);
x(297);
x(298);
x(299);
x(300);
};

foo b;
<commit_msg>Disable this test on Windows; it crashes and popup an dialog on each lit test run. I have no idea how to fix it.<commit_after>// RUN: %clang -c -g %s -o /dev/null
// Radar 8730409

// FIXME: This test crashes on Windows.
#ifndef _WIN32

class foo {
public:
#define x(a) virtual void v ## a (void)
x(1);
x(2);
x(3);
x(4);
x(5);
x(6);
x(7);
x(8);
x(9);
x(10);
x(11);
x(12);
x(13);
x(14);
x(15);
x(16);
x(17);
x(18);
x(19);
x(20);
x(21);
x(22);
x(23);
x(24);
x(25);
x(26);
x(27);
x(28);
x(29);
x(30);
x(31);
x(32);
x(33);
x(34);
x(35);
x(36);
x(37);
x(38);
x(39);
x(40);
x(41);
x(42);
x(43);
x(44);
x(45);
x(46);
x(47);
x(48);
x(49);
x(50);
x(51);
x(52);
x(53);
x(54);
x(55);
x(56);
x(57);
x(58);
x(59);
x(60);
x(61);
x(62);
x(63);
x(64);
x(65);
x(66);
x(67);
x(68);
x(69);
x(70);
x(71);
x(72);
x(73);
x(74);
x(75);
x(76);
x(77);
x(78);
x(79);
x(80);
x(81);
x(82);
x(83);
x(84);
x(85);
x(86);
x(87);
x(88);
x(89);
x(90);
x(91);
x(92);
x(93);
x(94);
x(95);
x(96);
x(97);
x(98);
x(99);
x(100);
x(101);
x(102);
x(103);
x(104);
x(105);
x(106);
x(107);
x(108);
x(109);
x(110);
x(111);
x(112);
x(113);
x(114);
x(115);
x(116);
x(117);
x(118);
x(119);
x(120);
x(121);
x(122);
x(123);
x(124);
x(125);
x(126);
x(127);
x(128);
x(129);
x(130);
x(131);
x(132);
x(133);
x(134);
x(135);
x(136);
x(137);
x(138);
x(139);
x(140);
x(141);
x(142);
x(143);
x(144);
x(145);
x(146);
x(147);
x(148);
x(149);
x(150);
x(151);
x(152);
x(153);
x(154);
x(155);
x(156);
x(157);
x(158);
x(159);
x(160);
x(161);
x(162);
x(163);
x(164);
x(165);
x(166);
x(167);
x(168);
x(169);
x(170);
x(171);
x(172);
x(173);
x(174);
x(175);
x(176);
x(177);
x(178);
x(179);
x(180);
x(181);
x(182);
x(183);
x(184);
x(185);
x(186);
x(187);
x(188);
x(189);
x(190);
x(191);
x(192);
x(193);
x(194);
x(195);
x(196);
x(197);
x(198);
x(199);
x(200);
x(201);
x(202);
x(203);
x(204);
x(205);
x(206);
x(207);
x(208);
x(209);
x(210);
x(211);
x(212);
x(213);
x(214);
x(215);
x(216);
x(217);
x(218);
x(219);
x(220);
x(221);
x(222);
x(223);
x(224);
x(225);
x(226);
x(227);
x(228);
x(229);
x(230);
x(231);
x(232);
x(233);
x(234);
x(235);
x(236);
x(237);
x(238);
x(239);
x(240);
x(241);
x(242);
x(243);
x(244);
x(245);
x(246);
x(247);
x(248);
x(249);
x(250);
x(251);
x(252);
x(253);
x(254);
x(255);
x(256);
x(257);
x(258);
x(259);
x(260);
x(261);
x(262);
x(263);
x(264);
x(265);
x(266);
x(267);
x(268);
x(269);
x(270);
x(271);
x(272);
x(273);
x(274);
x(275);
x(276);
x(277);
x(278);
x(279);
x(280);
x(281);
x(282);
x(283);
x(284);
x(285);
x(286);
x(287);
x(288);
x(289);
x(290);
x(291);
x(292);
x(293);
x(294);
x(295);
x(296);
x(297);
x(298);
x(299);
x(300);
};

foo b;

#endif
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"

#include "ui/Suite.h"
#include "mason/Hud.h"
#include "mason/Common.h"
#include "mason/Config.h"
#include "mason/Assets.h"
#include "mason/Profiling.h"

#include "HudTest.h"
#include "MiscTest.h"
//#include "BlendingTest.h"

#define USE_SECONDARY_SCREEN 1
#define MSAA 4

using namespace ci;
using namespace ci::app;
using namespace std;

class MasonTestsApp : public App {
  public:
	void setup() override;
	void resize() override;
	void keyDown( app::KeyEvent event ) override;
	void update() override;
	void draw() override;

	void reload();

	ui::SuiteRef	mSuite;
	bool			mDrawHud = true;
	bool			mDrawProfiling = false;
};

void MasonTestsApp::setup()
{
	ma::initialize( ma::getRepoRootPath() );

	mSuite = make_shared<ui::Suite>();

	mSuite->registerSuiteView<HudTest>( "hud" );
	mSuite->registerSuiteView<MiscTest>( "misc" );
	//mSuite->registerSuiteView<MotionTest>( "motion" );

	reload();
}

void MasonTestsApp::reload()
{
	ma::assets()->getFile( app::getAssetPath( "config.json" ), [this]( DataSourceRef dataSource ) {
		CI_LOG_I( "config.json reloaded" );

		ma::config()->read( dataSource );

		size_t testIndex = (size_t)ma::config()->get<int>( "app", "test" );
		mSuite->select( testIndex );
	} );
}

void MasonTestsApp::keyDown( app::KeyEvent event )
{
	if( event.isControlDown() ) {
		if( tolower( event.getChar() ) == 'r' ) {
			CI_LOG_I( "reloading suite" );
			if( event.isShiftDown() ) {
				CI_LOG_I( "- clearing variables" );
				ma::hud()->clear();
			}
			mSuite->reload();
		}
		else if( event.getChar() == 'f' ) {
			CI_LOG_I( "toggling fullscreen" );
			setFullScreen( ! isFullScreen() );
		}
		else if( event.getChar() == 'h' ) {
			CI_LOG_I( "toggling Hud" );
			mDrawHud = ! mDrawHud;
			mSuite->setDrawUiEnabled( mDrawHud );
		}
		else if( event.getChar() == 'l' )
			mDrawProfiling = ! mDrawProfiling;
	}
}

void MasonTestsApp::resize()
{
	CI_LOG_I( "window size: " << getWindowSize() );
}

void MasonTestsApp::update()
{
	{
		CI_PROFILE_CPU( "Suite update" );
		CI_PROFILE_GPU( "Suite update" );
		mSuite->update();
	}

#if CI_PROFILING
	if( mDrawProfiling )
		perf::printProfiling();
#endif
}

void MasonTestsApp::draw()
{
	CI_PROFILE_CPU( "main draw" );
	CI_PROFILE_GPU( "main draw" );

	gl::clear();

	{
		CI_PROFILE_CPU( "Suite draw" );
		CI_PROFILE_GPU( "Suite draw" );
		mSuite->draw();
	}

	if( mDrawHud ) {
		CI_PROFILE_CPU( "Hud draw" );
		CI_PROFILE_GPU( "Hud draw" );
		ma::hud()->draw();
	}

	CI_CHECK_GL();
}

void prepareSettings( App::Settings *settings )
{
	bool useSecondaryScreen = ( USE_SECONDARY_SCREEN && Display::getDisplays().size() > 1 );

	if( useSecondaryScreen ) {
		for( const auto &display : Display::getDisplays() ) {
			//CI_LOG_I( "display name: " << display->getName() );
			if( display->getName() == "Color LCD" ) {
				// macbook
				settings->setDisplay( display );
				settings->setWindowSize( 1280, 720 );
			}
			else if( display->getName() == "Generic PnP Monitor" ) {
				// gechic 1303i 13"touch display
				settings->setDisplay( display );
				settings->setFullScreen( true );
			}
		}
	}
	else {
#if defined( CINDER_MAC )
		ivec2 windowPos = { 0, 0 };
#else
		ivec2 windowPos = { 0, 24 };
#endif
		settings->setWindowPos( windowPos.x, windowPos.y );
		settings->setWindowSize( 960, 565 );
	}
}

CINDER_APP( MasonTestsApp, RendererGl( RendererGl::Options().msaa( MSAA ) ), prepareSettings )
<commit_msg>using new Cinder-Profiler macro<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"

#include "ui/Suite.h"
#include "mason/Hud.h"
#include "mason/Common.h"
#include "mason/Config.h"
#include "mason/Assets.h"
#include "mason/Profiling.h"

#include "HudTest.h"
#include "MiscTest.h"
//#include "BlendingTest.h"

#define USE_SECONDARY_SCREEN 1
#define MSAA 4

using namespace ci;
using namespace ci::app;
using namespace std;

class MasonTestsApp : public App {
  public:
	void setup() override;
	void resize() override;
	void keyDown( app::KeyEvent event ) override;
	void update() override;
	void draw() override;

	void reload();

	ui::SuiteRef	mSuite;
	bool			mDrawHud = true;
	bool			mDrawProfiling = false;
};

void MasonTestsApp::setup()
{
	ma::initialize( ma::getRepoRootPath() );

	mSuite = make_shared<ui::Suite>();

	mSuite->registerSuiteView<HudTest>( "hud" );
	mSuite->registerSuiteView<MiscTest>( "misc" );
	//mSuite->registerSuiteView<MotionTest>( "motion" );

	reload();
}

void MasonTestsApp::reload()
{
	ma::assets()->getFile( app::getAssetPath( "config.json" ), [this]( DataSourceRef dataSource ) {
		CI_LOG_I( "config.json reloaded" );

		ma::config()->read( dataSource );

		size_t testIndex = (size_t)ma::config()->get<int>( "app", "test" );
		mSuite->select( testIndex );
	} );
}

void MasonTestsApp::keyDown( app::KeyEvent event )
{
	if( event.isControlDown() ) {
		if( tolower( event.getChar() ) == 'r' ) {
			CI_LOG_I( "reloading suite" );
			if( event.isShiftDown() ) {
				CI_LOG_I( "- clearing variables" );
				ma::hud()->clear();
			}
			mSuite->reload();
		}
		else if( event.getChar() == 'f' ) {
			CI_LOG_I( "toggling fullscreen" );
			setFullScreen( ! isFullScreen() );
		}
		else if( event.getChar() == 'h' ) {
			CI_LOG_I( "toggling Hud" );
			mDrawHud = ! mDrawHud;
			mSuite->setDrawUiEnabled( mDrawHud );
		}
		else if( event.getChar() == 'l' )
			mDrawProfiling = ! mDrawProfiling;
	}
}

void MasonTestsApp::resize()
{
	CI_LOG_I( "window size: " << getWindowSize() );
}

void MasonTestsApp::update()
{
	{
		CI_PROFILE( "Suite update" );
		mSuite->update();
	}

#if CI_PROFILING
	if( mDrawProfiling )
		perf::printProfiling();
#endif
}

void MasonTestsApp::draw()
{
	CI_PROFILE( "main draw" );

	gl::clear();

	{
		CI_PROFILE( "Suite draw" );
		mSuite->draw();
	}

	if( mDrawHud ) {
		CI_PROFILE( "Hud draw" );
		ma::hud()->draw();
	}

	CI_CHECK_GL();
}

void prepareSettings( App::Settings *settings )
{
	bool useSecondaryScreen = ( USE_SECONDARY_SCREEN && Display::getDisplays().size() > 1 );

	if( useSecondaryScreen ) {
		for( const auto &display : Display::getDisplays() ) {
			//CI_LOG_I( "display name: " << display->getName() );
			if( display->getName() == "Color LCD" ) {
				// macbook
				settings->setDisplay( display );
				settings->setWindowSize( 1280, 720 );
			}
			else if( display->getName() == "Generic PnP Monitor" ) {
				// gechic 1303i 13"touch display
				settings->setDisplay( display );
				settings->setFullScreen( true );
			}
		}
	}
	else {
#if defined( CINDER_MAC )
		ivec2 windowPos = { 0, 0 };
#else
		ivec2 windowPos = { 0, 24 };
#endif
		settings->setWindowPos( windowPos.x, windowPos.y );
		settings->setWindowSize( 960, 565 );
	}
}

CINDER_APP( MasonTestsApp, RendererGl( RendererGl::Options().msaa( MSAA ) ), prepareSettings )
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

//RUN: cat %s | %cling -Xclang -verify 2>&1
// Test unknownTypeTest

 #include <x86intrin.h>

 __m128 testVar;
testVar // expected-error@2 {{__attribute__((__vector_size__(4 * sizeof(float)))) float has unknown type, which is not supported for this kind of declaration}}

.q
<commit_msg>Fix x86 dependency in test/UnknownType.C<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

//RUN: cat %s | %cling -Xclang -verify 2>&1
// Test unknownTypeTest

typedef float vec4f __attribute__((ext_vector_type(4)));

vec4f testVar;
testVar // expected-error {{float __attribute__((ext_vector_type(4))) has unknown type, which is not supported for this kind of declaration}}

.q
<|endoftext|>