<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <mapnik/config.hpp>

// boost
#include "boost_std_shared_shim.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-local-typedef"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"

#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/exception_translator.hpp>
#include <boost/python/manage_new_object.hpp>
#include <boost/python/iterator.hpp>
#include <boost/noncopyable.hpp>
#include <boost/version.hpp>
#pragma GCC diagnostic pop

// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_type.hpp>
#include <mapnik/geometry_envelope.hpp>
#include <mapnik/geometry_is_valid.hpp>
#include <mapnik/geometry_is_simple.hpp>
#include <mapnik/geometry_is_empty.hpp>
#include <mapnik/geometry_correct.hpp>
#include <mapnik/geometry_centroid.hpp>

#include <mapnik/wkt/wkt_factory.hpp> // from_wkt
#include <mapnik/json/geometry_parser.hpp> // from_geojson
#include <mapnik/util/geometry_to_geojson.hpp> // to_geojson
#include <mapnik/util/geometry_to_wkb.hpp> // to_wkb
#include <mapnik/util/geometry_to_wkt.hpp> // to_wkt
//#include <mapnik/util/geometry_to_svg.hpp>
#include <mapnik/wkb.hpp>

// stl
#include <stdexcept>

namespace {

std::shared_ptr<mapnik::geometry::geometry<double> > from_wkb_impl(std::string const& wkb)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    try
    {
        *geom = std::move(mapnik::geometry_utils::from_wkb(wkb.c_str(), wkb.size()));
    }
    catch (...)
    {
        throw std::runtime_error("Failed to parse WKB");
    }
    return geom;
}

std::shared_ptr<mapnik::geometry::geometry<double> > from_wkt_impl(std::string const& wkt)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    if (!mapnik::from_wkt(wkt, *geom))
        throw std::runtime_error("Failed to parse WKT geometry");
    return geom;
}

std::shared_ptr<mapnik::geometry::geometry<double> > from_geojson_impl(std::string const& json)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    if (!mapnik::json::from_geojson(json, *geom))
        throw std::runtime_error("Failed to parse geojson geometry");
    return geom;
}

}

inline std::string boost_version()
{
    std::ostringstream s;
    s << BOOST_VERSION/100000 << "." << BOOST_VERSION/100 % 1000  << "." << BOOST_VERSION % 100;
    return s.str();
}

PyObject* to_wkb_impl(mapnik::geometry::geometry<double> const& geom, mapnik::wkbByteOrder byte_order)
{
    mapnik::util::wkb_buffer_ptr wkb = mapnik::util::to_wkb(geom,byte_order);
    if (wkb)
    {
        return
#if PY_VERSION_HEX >= 0x03000000
            ::PyBytes_FromStringAndSize
#else
            ::PyString_FromStringAndSize
#endif
            ((const char*)wkb->buffer(),wkb->size());
    }
    else
    {
        Py_RETURN_NONE;
    }
}

std::string to_geojson_impl(mapnik::geometry::geometry<double> const& geom)
{
    std::string wkt;
    if (!mapnik::util::to_geojson(wkt, geom))
    {
        throw std::runtime_error("Generate JSON failed");
    }
    return wkt;
}

std::string to_wkt_impl(mapnik::geometry::geometry<double> const& geom)
{
    std::string wkt;
    if (!mapnik::util::to_wkt(wkt,geom))
    {
        throw std::runtime_error("Generate WKT failed");
    }
    return wkt;
}

mapnik::geometry::geometry_types geometry_type_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::geometry_type(geom);
}

mapnik::box2d<double> geometry_envelope_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::envelope(geom);
}

bool geometry_is_valid_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_valid(geom);
}

bool geometry_is_simple_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_simple(geom);
}

bool geometry_is_empty_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_empty(geom);
}

void geometry_correct_impl(mapnik::geometry::geometry<double> & geom)
{
    mapnik::geometry::correct(geom);
}

void polygon_set_exterior_impl(mapnik::geometry::polygon<double> & poly, mapnik::geometry::linear_ring<double> const& ring)
{
    poly.exterior_ring = ring; // copy
}

void polygon_add_hole_impl(mapnik::geometry::polygon<double> & poly, mapnik::geometry::linear_ring<double> const& ring)
{
    poly.interior_rings.push_back(ring); // copy
}

mapnik::geometry::point<double> geometry_centroid_impl(mapnik::geometry::geometry<double> const& geom)
{
    mapnik::geometry::point<double> pt;
    mapnik::geometry::centroid(geom, pt);
    return pt;
}

void export_geometry()
{
    using namespace boost::python;

    implicitly_convertible<mapnik::geometry::point<double>, mapnik::geometry::geometry<double> >();
    implicitly_convertible<mapnik::geometry::line_string<double>, mapnik::geometry::geometry<double> >();
    implicitly_convertible<mapnik::geometry::polygon<double>, mapnik::geometry::geometry<double> >();
    enum_<mapnik::geometry::geometry_types>("GeometryType")
        .value("Unknown",mapnik::geometry::geometry_types::Unknown)
        .value("Point",mapnik::geometry::geometry_types::Point)
        .value("LineString",mapnik::geometry::geometry_types::LineString)
        .value("Polygon",mapnik::geometry::geometry_types::Polygon)
        .value("MultiPoint",mapnik::geometry::geometry_types::MultiPoint)
        .value("MultiLineString",mapnik::geometry::geometry_types::MultiLineString)
        .value("MultiPolygon",mapnik::geometry::geometry_types::MultiPolygon)
        .value("GeometryCollection",mapnik::geometry::geometry_types::GeometryCollection)
        ;

    enum_<mapnik::wkbByteOrder>("wkbByteOrder")
        .value("XDR",mapnik::wkbXDR)
        .value("NDR",mapnik::wkbNDR)
        ;

    using mapnik::geometry::geometry;
    using mapnik::geometry::point;
    using mapnik::geometry::line_string;
    using mapnik::geometry::linear_ring;
    using mapnik::geometry::polygon;

    class_<point<double> >("Point", init<double, double>((arg("x"), arg("y")),
                                                "Constructs a new Point object\n"))
        .add_property("x", &point<double>::x, "X coordinate")
        .add_property("y", &point<double>::y, "Y coordinate")
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<line_string<double> >("LineString", init<>(
                      "Constructs a new LineString object\n"))
        .def("add_coord", &line_string<double>::add_coord, "Adds coord")
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<linear_ring<double> >("LinearRing", init<>(
                            "Constructs a new LinearRtring object\n"))
        .def("add_coord", &linear_ring<double>::add_coord, "Adds coord")
        ;

    class_<polygon<double> >("Polygon", init<>(
                        "Constructs a new Polygon object\n"))
        .add_property("exterior_ring", &polygon<double>::exterior_ring , "Exterior ring")
        .def("add_hole", &polygon_add_hole_impl, "Add interior ring")
        .def("num_rings", polygon_set_exterior_impl, "Number of rings (at least 1)")
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<geometry<double>, std::shared_ptr<geometry<double> >, boost::noncopyable>("Geometry",no_init)
        .def("envelope",&geometry_envelope_impl)
        .def("from_geojson", from_geojson_impl)
        .def("from_wkt", from_wkt_impl)
        .def("from_wkb", from_wkb_impl)
        .staticmethod("from_geojson")
        .staticmethod("from_wkt")
        .staticmethod("from_wkb")
        .def("__str__",&to_wkt_impl)
        .def("type",&geometry_type_impl)
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
        .def("is_empty", &geometry_is_empty_impl)
        .def("correct", &geometry_correct_impl)
        .def("centroid",&geometry_centroid_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        .def("to_geojson",&to_geojson_impl)
        //.def("to_svg",&to_svg)
        // TODO add other geometry_type methods
        ;
}
<commit_msg>fix build with boost versions prior to 1.56<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include <mapnik/config.hpp>

// boost
#include "boost_std_shared_shim.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-local-typedef"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"

#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/exception_translator.hpp>
#include <boost/python/manage_new_object.hpp>
#include <boost/python/iterator.hpp>
#include <boost/noncopyable.hpp>
#include <boost/version.hpp>
#pragma GCC diagnostic pop

// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/geometry_type.hpp>
#include <mapnik/geometry_envelope.hpp>
#include <mapnik/geometry_is_valid.hpp>
#include <mapnik/geometry_is_simple.hpp>
#include <mapnik/geometry_is_empty.hpp>
#include <mapnik/geometry_correct.hpp>
#include <mapnik/geometry_centroid.hpp>

#include <mapnik/wkt/wkt_factory.hpp> // from_wkt
#include <mapnik/json/geometry_parser.hpp> // from_geojson
#include <mapnik/util/geometry_to_geojson.hpp> // to_geojson
#include <mapnik/util/geometry_to_wkb.hpp> // to_wkb
#include <mapnik/util/geometry_to_wkt.hpp> // to_wkt
//#include <mapnik/util/geometry_to_svg.hpp>
#include <mapnik/wkb.hpp>

// stl
#include <stdexcept>

namespace {

std::shared_ptr<mapnik::geometry::geometry<double> > from_wkb_impl(std::string const& wkb)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    try
    {
        *geom = std::move(mapnik::geometry_utils::from_wkb(wkb.c_str(), wkb.size()));
    }
    catch (...)
    {
        throw std::runtime_error("Failed to parse WKB");
    }
    return geom;
}

std::shared_ptr<mapnik::geometry::geometry<double> > from_wkt_impl(std::string const& wkt)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    if (!mapnik::from_wkt(wkt, *geom))
        throw std::runtime_error("Failed to parse WKT geometry");
    return geom;
}

std::shared_ptr<mapnik::geometry::geometry<double> > from_geojson_impl(std::string const& json)
{
    std::shared_ptr<mapnik::geometry::geometry<double> > geom = std::make_shared<mapnik::geometry::geometry<double> >();
    if (!mapnik::json::from_geojson(json, *geom))
        throw std::runtime_error("Failed to parse geojson geometry");
    return geom;
}

}

inline std::string boost_version()
{
    std::ostringstream s;
    s << BOOST_VERSION/100000 << "." << BOOST_VERSION/100 % 1000  << "." << BOOST_VERSION % 100;
    return s.str();
}

PyObject* to_wkb_impl(mapnik::geometry::geometry<double> const& geom, mapnik::wkbByteOrder byte_order)
{
    mapnik::util::wkb_buffer_ptr wkb = mapnik::util::to_wkb(geom,byte_order);
    if (wkb)
    {
        return
#if PY_VERSION_HEX >= 0x03000000
            ::PyBytes_FromStringAndSize
#else
            ::PyString_FromStringAndSize
#endif
            ((const char*)wkb->buffer(),wkb->size());
    }
    else
    {
        Py_RETURN_NONE;
    }
}

std::string to_geojson_impl(mapnik::geometry::geometry<double> const& geom)
{
    std::string wkt;
    if (!mapnik::util::to_geojson(wkt, geom))
    {
        throw std::runtime_error("Generate JSON failed");
    }
    return wkt;
}

std::string to_wkt_impl(mapnik::geometry::geometry<double> const& geom)
{
    std::string wkt;
    if (!mapnik::util::to_wkt(wkt,geom))
    {
        throw std::runtime_error("Generate WKT failed");
    }
    return wkt;
}

mapnik::geometry::geometry_types geometry_type_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::geometry_type(geom);
}

mapnik::box2d<double> geometry_envelope_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::envelope(geom);
}

// only Boost >= 1.56 contains the is_valid and is_simple functions
#if BOOST_VERSION >= 105600
bool geometry_is_valid_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_valid(geom);
}

bool geometry_is_simple_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_simple(geom);
}
#endif

bool geometry_is_empty_impl(mapnik::geometry::geometry<double> const& geom)
{
    return mapnik::geometry::is_empty(geom);
}

void geometry_correct_impl(mapnik::geometry::geometry<double> & geom)
{
    mapnik::geometry::correct(geom);
}

void polygon_set_exterior_impl(mapnik::geometry::polygon<double> & poly, mapnik::geometry::linear_ring<double> const& ring)
{
    poly.exterior_ring = ring; // copy
}

void polygon_add_hole_impl(mapnik::geometry::polygon<double> & poly, mapnik::geometry::linear_ring<double> const& ring)
{
    poly.interior_rings.push_back(ring); // copy
}

mapnik::geometry::point<double> geometry_centroid_impl(mapnik::geometry::geometry<double> const& geom)
{
    mapnik::geometry::point<double> pt;
    mapnik::geometry::centroid(geom, pt);
    return pt;
}

void export_geometry()
{
    using namespace boost::python;

    implicitly_convertible<mapnik::geometry::point<double>, mapnik::geometry::geometry<double> >();
    implicitly_convertible<mapnik::geometry::line_string<double>, mapnik::geometry::geometry<double> >();
    implicitly_convertible<mapnik::geometry::polygon<double>, mapnik::geometry::geometry<double> >();
    enum_<mapnik::geometry::geometry_types>("GeometryType")
        .value("Unknown",mapnik::geometry::geometry_types::Unknown)
        .value("Point",mapnik::geometry::geometry_types::Point)
        .value("LineString",mapnik::geometry::geometry_types::LineString)
        .value("Polygon",mapnik::geometry::geometry_types::Polygon)
        .value("MultiPoint",mapnik::geometry::geometry_types::MultiPoint)
        .value("MultiLineString",mapnik::geometry::geometry_types::MultiLineString)
        .value("MultiPolygon",mapnik::geometry::geometry_types::MultiPolygon)
        .value("GeometryCollection",mapnik::geometry::geometry_types::GeometryCollection)
        ;

    enum_<mapnik::wkbByteOrder>("wkbByteOrder")
        .value("XDR",mapnik::wkbXDR)
        .value("NDR",mapnik::wkbNDR)
        ;

    using mapnik::geometry::geometry;
    using mapnik::geometry::point;
    using mapnik::geometry::line_string;
    using mapnik::geometry::linear_ring;
    using mapnik::geometry::polygon;

    class_<point<double> >("Point", init<double, double>((arg("x"), arg("y")),
                                                "Constructs a new Point object\n"))
        .add_property("x", &point<double>::x, "X coordinate")
        .add_property("y", &point<double>::y, "Y coordinate")
#if BOOST_VERSION >= 105600
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
#endif
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<line_string<double> >("LineString", init<>(
                      "Constructs a new LineString object\n"))
        .def("add_coord", &line_string<double>::add_coord, "Adds coord")
#if BOOST_VERSION >= 105600
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
#endif
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<linear_ring<double> >("LinearRing", init<>(
                            "Constructs a new LinearRtring object\n"))
        .def("add_coord", &linear_ring<double>::add_coord, "Adds coord")
        ;

    class_<polygon<double> >("Polygon", init<>(
                        "Constructs a new Polygon object\n"))
        .add_property("exterior_ring", &polygon<double>::exterior_ring , "Exterior ring")
        .def("add_hole", &polygon_add_hole_impl, "Add interior ring")
        .def("num_rings", polygon_set_exterior_impl, "Number of rings (at least 1)")
#if BOOST_VERSION >= 105600
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
#endif
        .def("to_geojson",&to_geojson_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        ;

    class_<geometry<double>, std::shared_ptr<geometry<double> >, boost::noncopyable>("Geometry",no_init)
        .def("envelope",&geometry_envelope_impl)
        .def("from_geojson", from_geojson_impl)
        .def("from_wkt", from_wkt_impl)
        .def("from_wkb", from_wkb_impl)
        .staticmethod("from_geojson")
        .staticmethod("from_wkt")
        .staticmethod("from_wkb")
        .def("__str__",&to_wkt_impl)
        .def("type",&geometry_type_impl)
#if BOOST_VERSION >= 105600
        .def("is_valid", &geometry_is_valid_impl)
        .def("is_simple", &geometry_is_simple_impl)
#endif
        .def("is_empty", &geometry_is_empty_impl)
        .def("correct", &geometry_correct_impl)
        .def("centroid",&geometry_centroid_impl)
        .def("to_wkb",&to_wkb_impl)
        .def("to_wkt",&to_wkt_impl)
        .def("to_geojson",&to_geojson_impl)
        //.def("to_svg",&to_svg)
        // TODO add other geometry_type methods
        ;
}
<|endoftext|>


<commit_before>#include "metal.h"
#include "paramset.h"
MetalMaterial* CreateMetalMaterial(const TextureParams&mp){
    std::shared_ptr<Texture<Spectrum>>eta = mp.GetSpectrumTexture("eta", Spectrum(1.0f));
    std::shared_ptr<Texture<Spectrum>> absorb = mp.GetSpectrumTexture("absorb", Spectrum(1.0f));
    std::shared_ptr<Texture<Float>> roughness = mp.GetFloatTexture("roughness", 1.0f);
	Debug("[CreateMetalMaterial]");
	return new MetalMaterial(eta,absorb,roughness);
}<commit_msg>去除冗余的金属材质的打印信息<commit_after>#include "metal.h"
#include "paramset.h"
MetalMaterial* CreateMetalMaterial(const TextureParams&mp){
    std::shared_ptr<Texture<Spectrum>>eta = mp.GetSpectrumTexture("eta", Spectrum(1.0f));
    std::shared_ptr<Texture<Spectrum>> absorb = mp.GetSpectrumTexture("absorb", Spectrum(1.0f));
    std::shared_ptr<Texture<Float>> roughness = mp.GetFloatTexture("roughness", 1.0f);
	return new MetalMaterial(eta,absorb,roughness);
}<|endoftext|>


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

#include "chrome/browser/ui/webui/options/password_manager_handler.h"

#include "base/callback.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"

PasswordManagerHandler::PasswordManagerHandler()
    : ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) {
}

PasswordManagerHandler::~PasswordManagerHandler() {
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->RemoveObserver(this);
}

void PasswordManagerHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsSiteColumn",
      IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN },
    { "passwordsUsernameColumn",
      IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN },
    { "passwordsRemoveButton",
      IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON },
    { "passwordsNoPasswordsDescription",
     IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
     IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
    { "passwordsRemoveAllButton",
      IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON },
    { "passwordsRemoveAllTitle",
      IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS },
    { "passwordsRemoveAllWarning",
      IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
      google_util::AppendGoogleLocaleParam(
          GURL(chrome::kPasswordManagerLearnMoreURL)).spec());
}

void PasswordManagerHandler::Initialize() {
  show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
                       web_ui_->GetProfile()->GetPrefs(), this);
  // We should not cache web_ui_->GetProfile(). See crosbug.com/6304.
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->AddObserver(this);
}

void PasswordManagerHandler::RegisterMessages() {
  DCHECK(web_ui_);

  web_ui_->RegisterMessageCallback("updatePasswordLists",
      NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists));
  web_ui_->RegisterMessageCallback("removeSavedPassword",
      NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword));
  web_ui_->RegisterMessageCallback("removePasswordException",
      NewCallback(this, &PasswordManagerHandler::RemovePasswordException));
  web_ui_->RegisterMessageCallback("removeAllSavedPasswords",
      NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords));
  web_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback(
      this, &PasswordManagerHandler::RemoveAllPasswordExceptions));
}

void PasswordManagerHandler::OnLoginsChanged() {
  UpdatePasswordLists(NULL);
}

PasswordStore* PasswordManagerHandler::GetPasswordStore() {
  return web_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS);
}

void PasswordManagerHandler::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  if (type.value == NotificationType::PREF_CHANGED) {
    std::string* pref_name = Details<std::string>(details).ptr();
    if (*pref_name == prefs::kPasswordManagerAllowShowPasswords) {
      UpdatePasswordLists(NULL);
    }
  }

  OptionsPageUIHandler::Observe(type, source, details);
}

void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
  // Reset the current lists.
  password_list_.reset();
  password_exception_list_.reset();

  languages_ =
      web_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
  populater_.Populate();
  exception_populater_.Populate();
}

void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  base::StringToInt(string_value, &index);
  store->RemoveLogin(*password_list_[index]);
}

void PasswordManagerHandler::RemovePasswordException(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  base::StringToInt(string_value, &index);

  store->RemoveLogin(*password_exception_list_[index]);
}

void PasswordManagerHandler::RemoveAllSavedPasswords(
    const ListValue* args) {
  // TODO(jhawkins): This will cause a list refresh for every password in the
  // list. Add PasswordStore::RemoveAllLogins().
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  for (size_t i = 0; i < password_list_.size(); ++i)
    store->RemoveLogin(*password_list_[i]);
}

void PasswordManagerHandler::RemoveAllPasswordExceptions(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  for (size_t i = 0; i < password_exception_list_.size(); ++i)
    store->RemoveLogin(*password_exception_list_[i]);
}

void PasswordManagerHandler::SetPasswordList() {
  ListValue entries;
  bool show_passwords = *show_passwords_;
  string16 empty;
  for (size_t i = 0; i < password_list_.size(); ++i) {
    ListValue* entry = new ListValue();
    entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
                                                 languages_)));
    entry->Append(new StringValue(password_list_[i]->username_value));
    entry->Append(new StringValue(
        show_passwords ? password_list_[i]->password_value : empty));
    entries.Append(entry);
  }

  web_ui_->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                  entries);
}

void PasswordManagerHandler::SetPasswordExceptionList() {
  ListValue entries;
  for (size_t i = 0; i < password_exception_list_.size(); ++i) {
    entries.Append(new StringValue(
        net::FormatUrl(password_exception_list_[i]->origin, languages_)));
  }

  web_ui_->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                  entries);
}

PasswordManagerHandler::ListPopulater::ListPopulater(
    PasswordManagerHandler* page)
    : page_(page),
      pending_login_query_(0) {
}

PasswordManagerHandler::ListPopulater::~ListPopulater() {
}

PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
    PasswordManagerHandler* page) : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetAutofillableLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display passwords.";
  }
}

void PasswordManagerHandler::PasswordListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<webkit_glue::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_list_.reset();
  page_->password_list_.insert(page_->password_list_.end(),
                               result.begin(), result.end());
  page_->SetPasswordList();
}

PasswordManagerHandler::PasswordExceptionListPopulater::
    PasswordExceptionListPopulater(PasswordManagerHandler* page)
        : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetBlacklistLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display exceptions.";
  }
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<webkit_glue::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_exception_list_.reset();
  page_->password_exception_list_.insert(page_->password_exception_list_.end(),
                                         result.begin(), result.end());
  page_->SetPasswordExceptionList();
}
<commit_msg>WebUI: check bounds of password list before use, a likely cause of bug 85009. BUG=85009<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/password_manager_handler.h"

#include "base/callback.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"

PasswordManagerHandler::PasswordManagerHandler()
    : ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) {
}

PasswordManagerHandler::~PasswordManagerHandler() {
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->RemoveObserver(this);
}

void PasswordManagerHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsSiteColumn",
      IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN },
    { "passwordsUsernameColumn",
      IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN },
    { "passwordsRemoveButton",
      IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON },
    { "passwordsNoPasswordsDescription",
     IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
     IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
    { "passwordsRemoveAllButton",
      IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON },
    { "passwordsRemoveAllTitle",
      IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS },
    { "passwordsRemoveAllWarning",
      IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
      google_util::AppendGoogleLocaleParam(
          GURL(chrome::kPasswordManagerLearnMoreURL)).spec());
}

void PasswordManagerHandler::Initialize() {
  show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
                       web_ui_->GetProfile()->GetPrefs(), this);
  // We should not cache web_ui_->GetProfile(). See crosbug.com/6304.
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->AddObserver(this);
}

void PasswordManagerHandler::RegisterMessages() {
  DCHECK(web_ui_);

  web_ui_->RegisterMessageCallback("updatePasswordLists",
      NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists));
  web_ui_->RegisterMessageCallback("removeSavedPassword",
      NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword));
  web_ui_->RegisterMessageCallback("removePasswordException",
      NewCallback(this, &PasswordManagerHandler::RemovePasswordException));
  web_ui_->RegisterMessageCallback("removeAllSavedPasswords",
      NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords));
  web_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback(
      this, &PasswordManagerHandler::RemoveAllPasswordExceptions));
}

void PasswordManagerHandler::OnLoginsChanged() {
  UpdatePasswordLists(NULL);
}

PasswordStore* PasswordManagerHandler::GetPasswordStore() {
  return web_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS);
}

void PasswordManagerHandler::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  if (type.value == NotificationType::PREF_CHANGED) {
    std::string* pref_name = Details<std::string>(details).ptr();
    if (*pref_name == prefs::kPasswordManagerAllowShowPasswords) {
      UpdatePasswordLists(NULL);
    }
  }

  OptionsPageUIHandler::Observe(type, source, details);
}

void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
  // Reset the current lists.
  password_list_.reset();
  password_exception_list_.reset();

  languages_ =
      web_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
  populater_.Populate();
  exception_populater_.Populate();
}

void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_list_.size())
    store->RemoveLogin(*password_list_[index]);
}

void PasswordManagerHandler::RemovePasswordException(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_exception_list_.size())
    store->RemoveLogin(*password_exception_list_[index]);
}

void PasswordManagerHandler::RemoveAllSavedPasswords(
    const ListValue* args) {
  // TODO(jhawkins): This will cause a list refresh for every password in the
  // list. Add PasswordStore::RemoveAllLogins().
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  for (size_t i = 0; i < password_list_.size(); ++i)
    store->RemoveLogin(*password_list_[i]);
}

void PasswordManagerHandler::RemoveAllPasswordExceptions(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  for (size_t i = 0; i < password_exception_list_.size(); ++i)
    store->RemoveLogin(*password_exception_list_[i]);
}

void PasswordManagerHandler::SetPasswordList() {
  ListValue entries;
  bool show_passwords = *show_passwords_;
  string16 empty;
  for (size_t i = 0; i < password_list_.size(); ++i) {
    ListValue* entry = new ListValue();
    entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
                                                 languages_)));
    entry->Append(new StringValue(password_list_[i]->username_value));
    entry->Append(new StringValue(
        show_passwords ? password_list_[i]->password_value : empty));
    entries.Append(entry);
  }

  web_ui_->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                  entries);
}

void PasswordManagerHandler::SetPasswordExceptionList() {
  ListValue entries;
  for (size_t i = 0; i < password_exception_list_.size(); ++i) {
    entries.Append(new StringValue(
        net::FormatUrl(password_exception_list_[i]->origin, languages_)));
  }

  web_ui_->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                  entries);
}

PasswordManagerHandler::ListPopulater::ListPopulater(
    PasswordManagerHandler* page)
    : page_(page),
      pending_login_query_(0) {
}

PasswordManagerHandler::ListPopulater::~ListPopulater() {
}

PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
    PasswordManagerHandler* page) : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetAutofillableLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display passwords.";
  }
}

void PasswordManagerHandler::PasswordListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<webkit_glue::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_list_.reset();
  page_->password_list_.insert(page_->password_list_.end(),
                               result.begin(), result.end());
  page_->SetPasswordList();
}

PasswordManagerHandler::PasswordExceptionListPopulater::
    PasswordExceptionListPopulater(PasswordManagerHandler* page)
        : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetBlacklistLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display exceptions.";
  }
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<webkit_glue::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_exception_list_.reset();
  page_->password_exception_list_.insert(page_->password_exception_list_.end(),
                                         result.begin(), result.end());
  page_->SetPasswordExceptionList();
}
<|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 "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
      bool is_uninstall)
          : delegate_(delegate), icon_(NULL), warning_(NULL),
            create_shortcut_(NULL), is_uninstall_(false) {
    if (extension->IsApp()) {
      icon_size_ = kIconSizeApp;
      right_column_width_ = kRightColumnWidthApp;
    } else {
      icon_size_ = kIconSizeExtension;
      right_column_width_ = kRightColumnWidthExtension;
    }

    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > icon_size_ || size.height() > icon_size_)
      size = gfx::Size(icon_size_, icon_size_);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(is_uninstall ?
                                  IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
                                  IDS_EXTENSION_INSTALL_PROMPT_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (!is_uninstall && extension->IsApp()) {
      create_shortcut_ = new views::Checkbox(
          l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
      create_shortcut_->SetChecked(true);
      create_shortcut_->SetMultiLine(true);
      AddChildView(create_shortcut_);
    } else {
      warning_ = new views::Label(warning_text);
      warning_->SetMultiLine(true);
      warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(warning_);
    }
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        if (is_uninstall_)
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
        else
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed(
        create_shortcut_ && create_shortcut_->checked());
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    if (is_uninstall_)
      return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
    else
      return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
    width += icon_size_;
    width += kPanelHorizMargin;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(right_column_width_);
    height += kPanelVertMargin;

    if (warning_)
      height += warning_->GetHeightForWidth(right_column_width_);
    else
      height += create_shortcut_->GetPreferredSize().height();

    height += kPanelVertMargin;

    return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    icon_->SetBounds(x, y, icon_size_, icon_size_);
    x += icon_size_;
    x += kPanelHorizMargin;

    heading_->SizeToFit(right_column_width_);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();

    y += kPanelVertMargin;

    if (create_shortcut_) {
      create_shortcut_->SetBounds(x, y, right_column_width_, 0);
      create_shortcut_->SetBounds(x, y, right_column_width_,
          create_shortcut_->GetPreferredSize().height());

      int bottom_aligned = icon_->y() + icon_->height() -
          create_shortcut_->height();
      if (bottom_aligned > y) {
        create_shortcut_->SetY(bottom_aligned);
        y = bottom_aligned;
      }
      y += create_shortcut_->height();
    } else {
      warning_->SizeToFit(right_column_width_);
      warning_->SetX(x);
      warning_->SetY(y);
      y += warning_->height();
    }

    y += kPanelVertMargin;
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* warning_;
  views::Checkbox* create_shortcut_;
  bool is_uninstall_;
  int right_column_width_;
  int icon_size_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const string16& warning_text, bool is_uninstall) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               UTF16ToWideHack(warning_text),
                               is_uninstall))->Show();
}
<commit_msg>Install/uninstall dialog had stopped showing Uninstall when you uninstall from the context menu for Browser Actions.<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 "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

class Profile;

namespace {

// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;

// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
 public:
  InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
      Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
      bool is_uninstall)
          : delegate_(delegate), icon_(NULL), warning_(NULL),
            create_shortcut_(NULL), is_uninstall_(is_uninstall) {
    if (extension->IsApp()) {
      icon_size_ = kIconSizeApp;
      right_column_width_ = kRightColumnWidthApp;
    } else {
      icon_size_ = kIconSizeExtension;
      right_column_width_ = kRightColumnWidthExtension;
    }

    // Scale down to icon size, but allow smaller icons (don't scale up).
    gfx::Size size(icon->width(), icon->height());
    if (size.width() > icon_size_ || size.height() > icon_size_)
      size = gfx::Size(icon_size_, icon_size_);
    icon_ = new views::ImageView();
    icon_->SetImageSize(size);
    icon_->SetImage(*icon);
    AddChildView(icon_);

    heading_ = new views::Label(
        l10n_util::GetStringF(is_uninstall ?
                                  IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
                                  IDS_EXTENSION_INSTALL_PROMPT_HEADING,
                              UTF8ToWide(extension->name())));
    heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
    heading_->SetMultiLine(true);
    heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    AddChildView(heading_);

    if (!is_uninstall && extension->IsApp()) {
      create_shortcut_ = new views::Checkbox(
          l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
      create_shortcut_->SetChecked(true);
      create_shortcut_->SetMultiLine(true);
      AddChildView(create_shortcut_);
    } else {
      warning_ = new views::Label(warning_text);
      warning_->SetMultiLine(true);
      warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
      AddChildView(warning_);
    }
  }

 private:
  // DialogDelegate
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const {
    switch (button) {
      case MessageBoxFlags::DIALOGBUTTON_OK:
        if (is_uninstall_)
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
        else
          return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
      case MessageBoxFlags::DIALOGBUTTON_CANCEL:
        return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
      default:
        NOTREACHED();
        return L"";
    }
  }

  virtual int GetDefaultDialogButton() const {
    return MessageBoxFlags::DIALOGBUTTON_CANCEL;
  }

  virtual bool Accept() {
    delegate_->InstallUIProceed(
        create_shortcut_ && create_shortcut_->checked());
    return true;
  }

  virtual bool Cancel() {
    delegate_->InstallUIAbort();
    return true;
  }

  // WindowDelegate
  virtual bool IsModal() const { return true; }
  virtual std::wstring GetWindowTitle() const {
    if (is_uninstall_)
      return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
    else
      return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
  }
  virtual views::View* GetContentsView() { return this; }

  // View
  virtual gfx::Size GetPreferredSize() {
    int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
    width += icon_size_;
    width += kPanelHorizMargin;

    int height = kPanelVertMargin * 2;
    height += heading_->GetHeightForWidth(right_column_width_);
    height += kPanelVertMargin;

    if (warning_)
      height += warning_->GetHeightForWidth(right_column_width_);
    else
      height += create_shortcut_->GetPreferredSize().height();

    height += kPanelVertMargin;

    return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
  }

  virtual void Layout() {
    int x = kPanelHorizMargin;
    int y = kPanelVertMargin;

    icon_->SetBounds(x, y, icon_size_, icon_size_);
    x += icon_size_;
    x += kPanelHorizMargin;

    heading_->SizeToFit(right_column_width_);
    heading_->SetX(x);
    heading_->SetY(y);
    y += heading_->height();

    y += kPanelVertMargin;

    if (create_shortcut_) {
      create_shortcut_->SetBounds(x, y, right_column_width_, 0);
      create_shortcut_->SetBounds(x, y, right_column_width_,
          create_shortcut_->GetPreferredSize().height());

      int bottom_aligned = icon_->y() + icon_->height() -
          create_shortcut_->height();
      if (bottom_aligned > y) {
        create_shortcut_->SetY(bottom_aligned);
        y = bottom_aligned;
      }
      y += create_shortcut_->height();
    } else {
      warning_->SizeToFit(right_column_width_);
      warning_->SetX(x);
      warning_->SetY(y);
      y += warning_->height();
    }

    y += kPanelVertMargin;
  }

  ExtensionInstallUI::Delegate* delegate_;
  views::ImageView* icon_;
  views::Label* heading_;
  views::Label* warning_;
  views::Checkbox* create_shortcut_;
  bool is_uninstall_;
  int right_column_width_;
  int icon_size_;

  DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};

}  // namespace

// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
    Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
    const string16& warning_text, bool is_uninstall) {
  Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
  if (!browser) {
    delegate->InstallUIAbort();
    return;
  }

  BrowserWindow* window = browser->window();
  if (!window) {
    delegate->InstallUIAbort();
    return;
  }

  views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
      new InstallDialogContent(delegate, extension, icon,
                               UTF16ToWideHack(warning_text),
                               is_uninstall))->Show();
}
<|endoftext|>


<commit_before>/*!
*	@file	MinimumWeightTriangulation.cpp
*	@brief	Functions for minimum weight triangulation
*/

#include "MinimumWeightTriangulation.h"

namespace psalm
{

/*!
*	Sets default attributes for the minimum-weight triangulation algorithm:
*	The objective function is set to be a minimum-area function.
*/

MinimumWeightTriangulation::MinimumWeightTriangulation()
{
	objective_function = minimum_area_and_normal_angle;
}

/*!
*	Applies triangulation algorithm to the input mesh. The function
*	requires the input mesh to consist solely of unconnected points. If
*	this is not the case, the function will abort.
*
*	@param input_mesh Mesh that will be triangulated.
*
*	@return true if the mesh could be triangulated, else false. Errors may
*	occur when the topology of the mesh is already defined.
*/

bool MinimumWeightTriangulation::apply_to(mesh& input_mesh)
{
	if(	input_mesh.num_faces() > 0 ||
		input_mesh.num_edges() > 0)
		return(false);

	size_t n = input_mesh.num_vertices();
	if(n < 3)
		return(false);

	indices = new size_t*[n];		// store minimum indices (private member)
	ktuple** weights = new ktuple*[n];	// store weights of triangulation (only required locally)

	for(size_t i = 0; i < n-1; i++)
	{
		indices[i] = new size_t[n];
		weights[i] = new ktuple[n];

		// Initialize weights array correctly
		if(i < n-1)
			weights[i][i+1] = 0;
		if(i < n-2)
			weights[i][i+2] = objective_function(	input_mesh.get_vertex(i),
								input_mesh.get_vertex(i+1),
								input_mesh.get_vertex(i+2));
	}

	size_t j = 2;
	while(j++ < n-1)	// this is correct -- the loop is supposed to start
				// with j == 3
	{
		for(size_t i = 0; i < n-j; i++)
		{
			size_t k = i+j;

			// Find minimum
			ktuple min_weight = boost::tuple<double, double>(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
			size_t min_index = std::numeric_limits<size_t>::max();
			for(size_t m = i+1; m < k; m++)
			{
				ktuple cur_weight = objective_function(	input_mesh.get_vertex(i),
									input_mesh.get_vertex(m),
									input_mesh.get_vertex(k));

				// The first component of the tuples can be
				// added; for the second component, only the
				// maximum of _all_ tuples is used

				double area	= weights[i][m].get<0>()+weights[m][k].get<0>()+cur_weight.get<0>();
				double angle	= std::max(	cur_weight.get<1>(),
								std::max(	weights[i][m].get<1>(),
										weights[m][k].get<1>()));

				ktuple res = boost::tuple<double, double>(area, angle);
				if(res < min_weight)
				{
					min_weight = res;
					min_index = m;
				}
			}

			weights[i][k] = min_weight;
			indices[i][k] = min_index;
		}
	}

	// Now weights[0][n-1] contains the weight of the minimal
	// triangulation. Construct triangulation using the stored indices.
	bool result = construct_triangulation(input_mesh, 0, n-1);

	for(size_t i = 0; i < n-1; i++)
	{
		delete[] weights[i];
		delete[] indices[i];
	}

	delete[] weights;
	delete[] indices;

	/*
		Mark _all_ vertices as boundary vertices. Upon subdivision, the
		boundary vertices will not be changed and we need to identify
		them when storing the subdivided mesh.
	*/

	for(size_t i = 0; i < input_mesh.num_vertices(); i++)
		input_mesh.get_vertex(i)->set_on_boundary();

	return(result);
}

/*!
*	Using the array of indices that achieve the minimum of the
*	minimum-weight triangulation, this function constructs the actual
*	triangulation of the mesh.
*
*	This function calls itself recursively.
*
*	@param input_mesh Mesh for which the triangles are constructed
*	@param i Smallest index for constructing a triangle
*	@param k Largest index for constructing a triangle
*
*	@return true if the triangulation could be constructed, else false.
*/

bool MinimumWeightTriangulation::construct_triangulation(mesh& input_mesh, size_t i, size_t k)
{
	// abort
	if(i+2 == k)
	{
		if(input_mesh.add_face(	input_mesh.get_vertex(i),
					input_mesh.get_vertex(i+1),
					input_mesh.get_vertex(k)) == NULL)
		{
			std::cerr << "psalm: Error: MinimumWeightTriangulation: Unable to construct triangulation\n";
			return(false);
		}
	}

	// use minimum index to branch off
	else
	{
		size_t j = indices[i][k];
		if(j != i+1)
		{
			if(!construct_triangulation(input_mesh, i, j))
				return(false);
		}

		if(input_mesh.add_face(	input_mesh.get_vertex(i),
					input_mesh.get_vertex(j),
					input_mesh.get_vertex(k)) == NULL)
		{
			std::cerr << "psalm: Error: MinimumWeightTriangulation: Unable to construct triangulation\n";
			return(false);
		}

		if(j != k-1)
		{
			if(!construct_triangulation(input_mesh, j, k))
				return(false);
		}
	}

	return(true);
}

} // end of namespace "psalm"
<commit_msg>Added error message to `MinimumWeightTriangulation` class<commit_after>/*!
*	@file	MinimumWeightTriangulation.cpp
*	@brief	Functions for minimum weight triangulation
*/

#include "MinimumWeightTriangulation.h"

namespace psalm
{

/*!
*	Sets default attributes for the minimum-weight triangulation algorithm:
*	The objective function is set to be a minimum-area function.
*/

MinimumWeightTriangulation::MinimumWeightTriangulation()
{
	objective_function = minimum_area_and_normal_angle;
}

/*!
*	Applies triangulation algorithm to the input mesh. The function
*	requires the input mesh to consist solely of unconnected points. If
*	this is not the case, the function will abort.
*
*	@param input_mesh Mesh that will be triangulated.
*
*	@return true if the mesh could be triangulated, else false. Errors may
*	occur when the topology of the mesh is already defined.
*/

bool MinimumWeightTriangulation::apply_to(mesh& input_mesh)
{
	if(	input_mesh.num_faces() > 0 ||
		input_mesh.num_edges() > 0)
		return(false);

	size_t n = input_mesh.num_vertices();
	if(n < 3)
	{
		std::cerr	<< "psalm: MinimumWeightTriangulation::apply_to(): Not enough vertices to perform triangulation"
				<< std::endl;
		return(false);
	}

	indices = new size_t*[n];		// store minimum indices (private member)
	ktuple** weights = new ktuple*[n];	// store weights of triangulation (only required locally)

	for(size_t i = 0; i < n-1; i++)
	{
		indices[i] = new size_t[n];
		weights[i] = new ktuple[n];

		// Initialize weights array correctly
		if(i < n-1)
			weights[i][i+1] = 0;
		if(i < n-2)
			weights[i][i+2] = objective_function(	input_mesh.get_vertex(i),
								input_mesh.get_vertex(i+1),
								input_mesh.get_vertex(i+2));
	}

	size_t j = 2;
	while(j++ < n-1)	// this is correct -- the loop is supposed to start
				// with j == 3
	{
		for(size_t i = 0; i < n-j; i++)
		{
			size_t k = i+j;

			// Find minimum
			ktuple min_weight = boost::tuple<double, double>(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
			size_t min_index = std::numeric_limits<size_t>::max();
			for(size_t m = i+1; m < k; m++)
			{
				ktuple cur_weight = objective_function(	input_mesh.get_vertex(i),
									input_mesh.get_vertex(m),
									input_mesh.get_vertex(k));

				// The first component of the tuples can be
				// added; for the second component, only the
				// maximum of _all_ tuples is used

				double area	= weights[i][m].get<0>()+weights[m][k].get<0>()+cur_weight.get<0>();
				double angle	= std::max(	cur_weight.get<1>(),
								std::max(	weights[i][m].get<1>(),
										weights[m][k].get<1>()));

				ktuple res = boost::tuple<double, double>(area, angle);
				if(res < min_weight)
				{
					min_weight = res;
					min_index = m;
				}
			}

			weights[i][k] = min_weight;
			indices[i][k] = min_index;
		}
	}

	// Now weights[0][n-1] contains the weight of the minimal
	// triangulation. Construct triangulation using the stored indices.
	bool result = construct_triangulation(input_mesh, 0, n-1);

	for(size_t i = 0; i < n-1; i++)
	{
		delete[] weights[i];
		delete[] indices[i];
	}

	delete[] weights;
	delete[] indices;

	/*
		Mark _all_ vertices as boundary vertices. Upon subdivision, the
		boundary vertices will not be changed and we need to identify
		them when storing the subdivided mesh.
	*/

	for(size_t i = 0; i < input_mesh.num_vertices(); i++)
		input_mesh.get_vertex(i)->set_on_boundary();

	return(result);
}

/*!
*	Using the array of indices that achieve the minimum of the
*	minimum-weight triangulation, this function constructs the actual
*	triangulation of the mesh.
*
*	This function calls itself recursively.
*
*	@param input_mesh Mesh for which the triangles are constructed
*	@param i Smallest index for constructing a triangle
*	@param k Largest index for constructing a triangle
*
*	@return true if the triangulation could be constructed, else false.
*/

bool MinimumWeightTriangulation::construct_triangulation(mesh& input_mesh, size_t i, size_t k)
{
	// abort
	if(i+2 == k)
	{
		if(input_mesh.add_face(	input_mesh.get_vertex(i),
					input_mesh.get_vertex(i+1),
					input_mesh.get_vertex(k)) == NULL)
		{
			std::cerr << "psalm: Error: MinimumWeightTriangulation: Unable to construct triangulation\n";
			return(false);
		}
	}

	// use minimum index to branch off
	else
	{
		size_t j = indices[i][k];
		if(j != i+1)
		{
			if(!construct_triangulation(input_mesh, i, j))
				return(false);
		}

		if(input_mesh.add_face(	input_mesh.get_vertex(i),
					input_mesh.get_vertex(j),
					input_mesh.get_vertex(k)) == NULL)
		{
			std::cerr << "psalm: Error: MinimumWeightTriangulation: Unable to construct triangulation\n";
			return(false);
		}

		if(j != k-1)
		{
			if(!construct_triangulation(input_mesh, j, k))
				return(false);
		}
	}

	return(true);
}

} // end of namespace "psalm"
<|endoftext|>


<commit_before>#include "Tutorial4ActorModule.h"
#include "NFComm/NFCore/NFTimer.h"

bool HelloWorld4ActorModule::Init()
{
    //ʼ
    std::cout << "Hello, world4, Init ThreadID: " << GetCurrentThreadId() << std::endl;

    return true;
}

int HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)
{
    //¼ص
    std::cout << "Begin OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << GetCurrentThreadId() << std::endl;

	arg += "  event test ok";

    return 0;
}

int HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)
{
	//¼ص
	std::cout << "End OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << GetCurrentThreadId() << std::endl;

	return 0;
}

bool HelloWorld4ActorModule::AfterInit()
{

    //ʼ
    std::cout << "Hello, world4, AfterInit, ThreadID: " << GetCurrentThreadId() << std::endl;

    m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
    m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
    m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));

	//////////////////////////////////////ͬ/////////////////////////////////////////////////////////////////////
	m_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);

	for (int i = 0; i < 20; ++i)
	{
		m_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast<std::string>(i), false);

	}

	std::cout << "End Test Actor, ThreadID: " << GetCurrentThreadId() << std::endl;

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

    return true;
}

bool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )
{
    //ÿִ֡
    //std::cout << "Hello, world3, Execute" << std::endl;

    return true;
}

bool HelloWorld4ActorModule::BeforeShut()
{
    //ʼ֮ǰ
    std::cout << "Hello, world4, BeforeShut" << std::endl;

    m_pKernelModule->DestroyAll();

    return true;
}

bool HelloWorld4ActorModule::Shut()
{
    //ʼ
    std::cout << "Hello, world4, Shut" << std::endl;

    return true;
}
<commit_msg>modify GetCurrentThreadID() as std::this_thread::get_id()<commit_after>#include "Tutorial4ActorModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include <thread>

bool HelloWorld4ActorModule::Init()
{
    //ʼ
    std::cout << "Hello, world4, Init ThreadID: " << std::this_thread::get_id() << std::endl;

    return true;
}

int HelloWorld4ActorModule::OnASyncEvent(const NFIDENTID& self, const int event, std::string& arg)
{
    //¼ص
    std::cout << "Begin OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;

	arg += "  event test ok";

    return 0;
}

int HelloWorld4ActorModule::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)
{
	//¼ص
	std::cout << "End OnEvent EventID: " << event << " self: " << self.nData64 << " argList: " << arg << " ThreadID: " << std::this_thread::get_id() << std::endl;

	return 0;
}

bool HelloWorld4ActorModule::AfterInit()
{

    //ʼ
    std::cout << "Hello, world4, AfterInit, ThreadID: " << GetCurrentThreadId() << std::endl;

    m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule"));
    m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule"));
    m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule"));

	//////////////////////////////////////ͬ/////////////////////////////////////////////////////////////////////
	m_pEventProcessModule->AddAsyncEventCallBack(NFIDENTID(), 2222, this, &HelloWorld4ActorModule::OnASyncEvent, &HelloWorld4ActorModule::OnSyncEvent);

	for (int i = 0; i < 20; ++i)
	{
		m_pEventProcessModule->DoEvent(NFIDENTID(), 2222, NFCDataList() << boost::lexical_cast<std::string>(i), false);

	}

	std::cout << "End Test Actor, ThreadID: " << std::this_thread::get_id() << std::endl;

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

    return true;
}

bool HelloWorld4ActorModule::Execute( const float fLasFrametime, const float fStartedTime )
{
    //ÿִ֡
    //std::cout << "Hello, world3, Execute" << std::endl;

    return true;
}

bool HelloWorld4ActorModule::BeforeShut()
{
    //ʼ֮ǰ
    std::cout << "Hello, world4, BeforeShut" << std::endl;

    m_pKernelModule->DestroyAll();

    return true;
}

bool HelloWorld4ActorModule::Shut()
{
    //ʼ
    std::cout << "Hello, world4, Shut" << std::endl;

    return true;
}
<|endoftext|>


<commit_before>TEveRGBAPalette *g_zdc_palette = 0;

TEveGeoShape* zdc_make_shape(const Text_t* name, Double_t signal,
			     const Text_t* path)
{
  if ( ! gGeoManager->cd(path))
  {
    Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path);
    return 0;
  }

  UChar_t rgb[3];
  g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE);

  TEveGeoShape *s = new TEveGeoShape(name);
  s->SetPickable(kTRUE);
  s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]);
  s->SetShape(gGeoManager->GetCurrentVolume()->GetShape());
  s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix());

  // Scale z-dictance by 0.1
  Double_t* t = s->RefMainTrans().ArrT();
  t[2] *= 0.1;

  return s;
}

// ???? There are 5 towers in ESD, 4 in geom.
// Not sure about assignment A/C <-> 1/2

void esd_zdc()
{
  AliEveEventManager::AssertGeometry();

  AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC();

  if (g_zdc_palette == 0)
  {
    // Map values from 0, 50 on a spectrum palette.
    g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE);
    g_zdc_palette->IncRefCount();
    gStyle->SetPalette(1, 0);
    g_zdc_palette->SetupColorArray();
  }

  TEveElementList* l = new TEveElementList("ZDC Data", "");
  gEve->AddElement(l);

  TEveElementList *c  = 0;
  TEveGeoShape    *s  = 0;
  Double_t        *te = 0;

  // ZNC geometry ------------------------------------
  c = new TEveElementList("ZNC");
  l->AddElement(c);

  te = esd->GetZN1TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2"));

  // ZNA geometry
  c = new TEveElementList("ZNA");
  l->AddElement(c);

  te = esd->GetZN2TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2"));

  // ZPC geometry ------------------------------------
  c = new TEveElementList("ZPC");
  l->AddElement(c);

  te = esd->GetZP1TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1"));

  // ZPA geometry
  c = new TEveElementList("ZPA");
  l->AddElement(c);

  te = esd->GetZP2TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1"));

  // End - refresh screen
  gEve->Redraw3D();
}
<commit_msg>Prevent destruction of TGeoShape used for ZDC tower visualization.<commit_after>TEveRGBAPalette *g_zdc_palette = 0;

TEveGeoShape* zdc_make_shape(const Text_t* name, Double_t signal,
			     const Text_t* path)
{
  if ( ! gGeoManager->cd(path))
  {
    Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path);
    return 0;
  }

  UChar_t rgb[3];
  g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE);

  TGeoShape *gs = gGeoManager->GetCurrentVolume()->GetShape();
  gs->SetUniqueID(gs->GetUniqueID() + 1);

  TEveGeoShape *s = new TEveGeoShape(name);
  s->SetPickable(kTRUE);
  s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]);
  s->SetShape(gs);
  s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix());

  // Scale z-dictance by 0.1
  Double_t* t = s->RefMainTrans().ArrT();
  t[2] *= 0.1;

  return s;
}

// ???? There are 5 towers in ESD, 4 in geom.
// Not sure about assignment A/C <-> 1/2

void esd_zdc()
{
  AliEveEventManager::AssertGeometry();

  AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC();

  if (g_zdc_palette == 0)
  {
    // Map values from 0, 50 on a spectrum palette.
    g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE);
    g_zdc_palette->IncRefCount();
    gStyle->SetPalette(1, 0);
    g_zdc_palette->SetupColorArray();
  }

  TEveElementList* l = new TEveElementList("ZDC Data", "");
  gEve->AddElement(l);

  TEveElementList *c  = 0;
  TEveGeoShape    *s  = 0;
  Double_t        *te = 0;

  // ZNC geometry ------------------------------------
  c = new TEveElementList("ZNC");
  l->AddElement(c);

  te = esd->GetZN1TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2"));

  // ZNA geometry
  c = new TEveElementList("ZNA");
  l->AddElement(c);

  te = esd->GetZN2TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2"));

  // ZPC geometry ------------------------------------
  c = new TEveElementList("ZPC");
  l->AddElement(c);

  te = esd->GetZP1TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1"));

  // ZPA geometry
  c = new TEveElementList("ZPA");
  l->AddElement(c);

  te = esd->GetZP2TowerEnergy();

  c->AddElement(zdc_make_shape("Tower 1", te[1],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 2", te[2],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 3", te[3],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1"));

  c->AddElement(zdc_make_shape("Tower 4", te[4],
			       "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1"));

  // End - refresh screen
  gEve->Redraw3D();
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/Debug.hpp>

template<typename T>
NzObjectRef<T>::NzObjectRef() :
m_object(nullptr)
{
}

template<typename T>
NzObjectRef<T>::NzObjectRef(T* object) :
m_object(object)
{
	if (m_object)
		m_object->AddReference();
}

template<typename T>
NzObjectRef<T>::NzObjectRef(const NzObjectRef& ref) :
m_object(ref.m_object)
{
	if (m_object)
		m_object->AddReference();
}

template<typename T>
template<typename U>
NzObjectRef<T>::NzObjectRef(const NzObjectRef<U>& ref) :
NzObjectRef(ref.Get())
{
}

template<typename T>
NzObjectRef<T>::NzObjectRef(NzObjectRef&& ref) noexcept :
m_object(ref.m_object)
{
	ref.m_object = nullptr; // On vole la référence
}

template<typename T>
NzObjectRef<T>::~NzObjectRef()
{
	if (m_object)
		m_object->RemoveReference();
}

template<typename T>
T* NzObjectRef<T>::Get() const
{
	return m_object;
}

template<typename T>
bool NzObjectRef<T>::IsValid() const
{
	return m_object != nullptr;
}

template<typename T>
T* NzObjectRef<T>::Release()
{
	T* object = m_object;
	m_object = nullptr;

	return object;
}

template<typename T>
bool NzObjectRef<T>::Reset(T* object)
{
	bool destroyed = false;
	if (m_object != object)
	{
		if (m_object)
		{
			destroyed = m_object->RemoveReference();
			m_object = nullptr;
		}

		m_object = object;
		if (m_object)
			m_object->AddReference();
	}

	return destroyed;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::Swap(NzObjectRef& ref)
{
	std::swap(m_object, ref.m_object);

	return *this;
}

template<typename T>
NzObjectRef<T>::operator bool() const
{
	return IsValid();
}

template<typename T>
NzObjectRef<T>::operator T*() const
{
	return m_object;
}

template<typename T>
T* NzObjectRef<T>::operator->() const
{
	return m_object;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(T* object)
{
	Reset(object);

	return *this;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef& ref)
{
	Reset(ref.m_object);

	return *this;
}

template<typename T>
template<typename U>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef<U>& ref)
{
	Reset(ref.Get());

	return *this;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(NzObjectRef&& ref) noexcept
{
	Reset();

	std::swap(m_object, ref.m_object);

	return *this;
}

#include <Nazara/Core/DebugOff.hpp>
<commit_msg>(ObjectRef) Added static_assert (Improved error message)<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/Debug.hpp>

template<typename T>
NzObjectRef<T>::NzObjectRef() :
m_object(nullptr)
{
}

template<typename T>
NzObjectRef<T>::NzObjectRef(T* object) :
m_object(object)
{
	if (m_object)
		m_object->AddReference();
}

template<typename T>
NzObjectRef<T>::NzObjectRef(const NzObjectRef& ref) :
m_object(ref.m_object)
{
	if (m_object)
		m_object->AddReference();
}

template<typename T>
template<typename U>
NzObjectRef<T>::NzObjectRef(const NzObjectRef<U>& ref) :
NzObjectRef(ref.Get())
{
}

template<typename T>
NzObjectRef<T>::NzObjectRef(NzObjectRef&& ref) noexcept :
m_object(ref.m_object)
{
	ref.m_object = nullptr; // On vole la référence
}

template<typename T>
NzObjectRef<T>::~NzObjectRef()
{
	if (m_object)
		m_object->RemoveReference();
}

template<typename T>
T* NzObjectRef<T>::Get() const
{
	return m_object;
}

template<typename T>
bool NzObjectRef<T>::IsValid() const
{
	return m_object != nullptr;
}

template<typename T>
T* NzObjectRef<T>::Release()
{
	T* object = m_object;
	m_object = nullptr;

	return object;
}

template<typename T>
bool NzObjectRef<T>::Reset(T* object)
{
	bool destroyed = false;
	if (m_object != object)
	{
		if (m_object)
		{
			destroyed = m_object->RemoveReference();
			m_object = nullptr;
		}

		m_object = object;
		if (m_object)
			m_object->AddReference();
	}

	return destroyed;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::Swap(NzObjectRef& ref)
{
	std::swap(m_object, ref.m_object);

	return *this;
}

template<typename T>
NzObjectRef<T>::operator bool() const
{
	return IsValid();
}

template<typename T>
NzObjectRef<T>::operator T*() const
{
	return m_object;
}

template<typename T>
T* NzObjectRef<T>::operator->() const
{
	return m_object;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(T* object)
{
	Reset(object);

	return *this;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef& ref)
{
	Reset(ref.m_object);

	return *this;
}

template<typename T>
template<typename U>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef<U>& ref)
{
	static_assert(std::is_convertible<U*, T*>::value, "U is not implicitly convertible to T");

	Reset(ref.Get());

	return *this;
}

template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(NzObjectRef&& ref) noexcept
{
	Reset();

	std::swap(m_object, ref.m_object);

	return *this;
}

#include <Nazara/Core/DebugOff.hpp>
<|endoftext|>


<commit_before>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.

#ifndef POMDOG_ASSERT_7D111D58_HPP
#define POMDOG_ASSERT_7D111D58_HPP

#include "Pomdog/Basic/Platform.hpp"
#include <cassert>

#if defined(_MSC_VER)
#include <xutility>
#endif
#if defined(linux) || defined(__linux) || defined(__linux__)
#include <csignal>
#endif

namespace Pomdog {
namespace Detail {

// How to use:
// POMDOG_ASSERT(expr);
// POMDOG_ASSERT_MESSAGE(expr, "message");

#if defined(DEBUG) && defined(__APPLE_CC__)
#    // Debug mode under Xcode
#    define POMDOG_ASSERT(expression) assert(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        do {\
            if (!(expression)) {\
                assert(message && expression);\
            }\
        } while(false)
#elif defined(DEBUG) && defined(_MSC_VER)
#    // Debug mode under Visual Studio
#    define POMDOG_ASSERT(expression) \
        static_cast<void>((!!(expression)) \
            || (_CrtDbgBreak(), _ASSERT(expression), false))
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        static_cast<void>((!!(expression)) \
            || (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \
            || (_CrtDbgBreak(), false))
#elif defined(DEBUG)
#    // Debug mode
#    if defined(_MSC_VER)
#        define POMDOG_DEBUGBREAK() __debugbreak()
#    elif defined(linux) || defined(__linux) || defined(__linux__)
#        define POMDOG_DEBUGBREAK() raise(SIGTRAP)
#    elif defined(POMDOG_ARCHITECTURE_POWERPC)
#        define POMDOG_DEBUGBREAK() asm {trap}
#    else
#        define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly
#    endif
#    define POMDOG_ASSERT(expression) assert(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        do {\
            if (!(expression)) {\
                assert(message && expression); \
                POMDOG_DEBUGBREAK(); \
            }\
        } while(false)
#else
#    // Release mode
#    define POMDOG_ASSERT(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message)
#endif

namespace Assertion {

inline constexpr bool ConstexprAssert(
    bool condition,
    char const* expression,
    char const* filename,
    int line)
{
    return (assert(condition), condition);
}

} // namespace Assertion

#if defined(DEBUG)
#   // Debug mode
#   define POMDOG_CONSTEXPR_ASSERT(expression) \
        static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert(\
            static_cast<bool>(expression), #expression, __FILE__, __LINE__))
#else
#   // Release mode
#   define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0)
#endif

} // namespace Detail
} // namespace Pomdog

#endif // POMDOG_ASSERT_7D111D58_HPP
<commit_msg>Fix compiler warnings in MSVC 2015<commit_after>// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.

#ifndef POMDOG_ASSERT_7D111D58_HPP
#define POMDOG_ASSERT_7D111D58_HPP

#include "Pomdog/Basic/Platform.hpp"
#include <cassert>

#if defined(_MSC_VER)
#include <xutility>
#endif
#if defined(linux) || defined(__linux) || defined(__linux__)
#include <csignal>
#endif

namespace Pomdog {
namespace Detail {

// How to use:
// POMDOG_ASSERT(expr);
// POMDOG_ASSERT_MESSAGE(expr, "message");

#if defined(DEBUG) && defined(__APPLE_CC__)
#    // Debug mode under Xcode
#    define POMDOG_ASSERT(expression) assert(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        do {\
            if (!(expression)) {\
                assert(message && expression);\
            }\
        } while(false)
#elif defined(DEBUG) && defined(_MSC_VER)
#    // Debug mode under Visual Studio
#    define POMDOG_ASSERT(expression) \
        static_cast<void>((!!(expression)) \
            || (_CrtDbgBreak(), _ASSERT(expression), false))
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        static_cast<void>((!!(expression)) \
            || (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \
            || (_CrtDbgBreak(), false))
#elif defined(DEBUG)
#    // Debug mode
#    if defined(_MSC_VER)
#        define POMDOG_DEBUGBREAK() __debugbreak()
#    elif defined(linux) || defined(__linux) || defined(__linux__)
#        define POMDOG_DEBUGBREAK() raise(SIGTRAP)
#    elif defined(POMDOG_ARCHITECTURE_POWERPC)
#        define POMDOG_DEBUGBREAK() asm {trap}
#    else
#        define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly
#    endif
#    define POMDOG_ASSERT(expression) assert(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message) \
        do {\
            if (!(expression)) {\
                assert(message && expression); \
                POMDOG_DEBUGBREAK(); \
            }\
        } while(false)
#else
#    // Release mode
#    define POMDOG_ASSERT(expression)
#    define POMDOG_ASSERT_MESSAGE(expression, message)
#endif

namespace Assertion {

inline constexpr bool ConstexprAssert(
    bool condition,
    char const* expression)
{
    return (assert(condition), condition);
}

} // namespace Assertion

#if defined(DEBUG)
#   // Debug mode
#   define POMDOG_CONSTEXPR_ASSERT(expression) \
        static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert( \
            static_cast<bool>(expression), #expression))
#else
#   // Release mode
#   define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0)
#endif

} // namespace Detail
} // namespace Pomdog

#endif // POMDOG_ASSERT_7D111D58_HPP
<|endoftext|>


<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP

#include <type_traits>
#include "meta_list.hpp"
#include "utils.hpp"
#include "traits.hpp"
#include "injected.hpp"

namespace kgr {

struct Container;

template<typename T, T t>
using Method = std::integral_constant<T, t>;

template<typename M, typename... Ps>
struct Invoke : M {
	using Parameters = detail::meta_list<Ps...>;
};

template<template<typename> class M, typename... Ts>
struct AutoCall {
	using Autocall = detail::meta_list<Ts...>;

	template<typename T>
	using Map = M<T>;
};

template<typename... Ts>
struct AutoCallNoMap {
	using Autocall = detail::meta_list<Ts...>;
};

namespace detail {

template<typename T, typename F>
struct autocall_function {
private:
	template<typename U>
	static U identity(U);

	template<typename U, typename C>
	struct get_member_autocall {
		using type = std::integral_constant<
			decltype(identity(&U::template autocall<C, U::template Map>)),
			&U::template autocall<C, U::template Map>
		>;
	};

	template<typename U, typename C, std::size_t... S>
	struct get_invoke_autocall {
		using type = std::integral_constant<
			decltype(identity(&U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...>)),
			&U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...>
		>;
	};

	template<typename U, typename C, std::size_t... S>
	static get_invoke_autocall<U, C, S...> test_helper(seq<S...>);

	template<typename U, typename C, enable_if_t<is_invoke_call<C>::value, int> = 0>
	static decltype(test_helper<U, C>(tuple_seq<typename C::Parameters>{})) test();

	template<typename U, typename C, enable_if_t<is_member_autocall<U, C>::value && !is_invoke_call<C>::value, int> = 0>
	static get_member_autocall<U, C> test();

	using inner_type = decltype(test<T, F>());

public:
	using type = typename inner_type::type;
};

template<typename, typename, typename = void>
struct autocall_arguments;

template<typename T, typename F>
struct autocall_arguments<T, F, enable_if_t<is_invoke_call<F>::value>> {
	using type = typename F::Parameters;
};

template<typename T, typename F>
struct autocall_arguments<T, F, enable_if_t<is_member_autocall<T, F>::value && !is_invoke_call<F>::value>> {
private:
	template<template<typename> class Map>
	struct mapped_type {
		template<typename U>
		using map = service_map_t<Map, U>;
	};

public:
	using type = meta_list_transform_t<function_arguments_t<typename F::value_type>, mapped_type<T::template Map>::template map>;
};

template<typename T, typename F>
using autocall_function_t = typename autocall_function<T, F>::type;

template<typename T, typename F>
using autocall_arguments_t = typename autocall_arguments<T, F>::type;

template<typename T, typename F>
using is_valid_autocall_function = std::integral_constant<bool,
	is_invoke_call<F>::value || is_member_autocall<T, F>::value
>;

template<typename, typename = void>
struct map_entry {};

template<typename P>
struct map_entry<P, enable_if_t<is_service<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>::value>> {
	using Service = decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()));
};

template<typename P>
struct map_entry<P, enable_if_t<is_service<decltype(service_map(std::declval<P>()))>::value>> {
	using Service = decltype(service_map(std::declval<P>()));
};

template<typename P>
struct map_entry<P, enable_if_t<is_map<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>::value>> {
	using Service = typename decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))::Service;
};

template<typename P>
struct map_entry<P, enable_if_t<is_map<decltype(service_map(std::declval<P>()))>::value>> {
	using Service = typename decltype(service_map(std::declval<P>()))::Service;
};

} // namespace detail

template<typename P>
struct AdlMap : detail::map_entry<P> {};

} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP
<commit_msg>fix build with msvc<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP

#include <type_traits>
#include "meta_list.hpp"
#include "utils.hpp"
#include "traits.hpp"
#include "injected.hpp"

namespace kgr {

struct Container;

template<typename T, T t>
using Method = std::integral_constant<T, t>;

template<typename M, typename... Ps>
struct Invoke : M {
	using Parameters = detail::meta_list<Ps...>;
};

template<template<typename> class M, typename... Ts>
struct AutoCall {
	using Autocall = detail::meta_list<Ts...>;

	template<typename T>
	using Map = M<T>;
};

template<typename... Ts>
struct AutoCallNoMap {
	using Autocall = detail::meta_list<Ts...>;
};

namespace detail {

template<typename T, typename F>
struct autocall_function {
private:
	template<typename U>
	static U identity(U);

	template<typename U, typename C>
	struct get_member_autocall {
		using type = std::integral_constant<
			decltype(identity(&U::template autocall<C, U::template Map>)),
			&U::template autocall<C, U::template Map>
		>;
	};

	template<typename U, typename C, std::size_t... S>
	struct get_invoke_autocall {
		using type = std::integral_constant<
			decltype(identity(&U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...>)),
			&U::template autocall<C, detail::meta_list_element_t<S, typename C::Parameters>...>
		>;
	};

	template<typename U, typename C, std::size_t... S>
	static get_invoke_autocall<U, C, S...> test_helper(seq<S...>);

	template<typename U, typename C, enable_if_t<is_invoke_call<C>::value, int> = 0>
	static decltype(test_helper<U, C>(tuple_seq<typename C::Parameters>{})) test();

	template<typename U, typename C, enable_if_t<is_member_autocall<U, C>::value && !is_invoke_call<C>::value, int> = 0>
	static get_member_autocall<U, C> test();

	using inner_type = decltype(test<T, F>());

public:
	using type = typename inner_type::type;
};

template<typename, typename, typename = void>
struct autocall_arguments;

template<typename T, typename F>
struct autocall_arguments<T, F, enable_if_t<is_invoke_call<F>::value>> {
	using type = typename F::Parameters;
};

template<typename T, typename F>
struct autocall_arguments<T, F, enable_if_t<is_member_autocall<T, F>::value && !is_invoke_call<F>::value>> {
private:
	template<template<typename> class Map>
	struct mapped_type {
		template<typename U>
		using map = service_map_t<Map, U>;
	};

public:
	using type = meta_list_transform_t<function_arguments_t<typename F::value_type>, mapped_type<T::template Map>::template map>;
};

template<typename T, typename F>
using autocall_function_t = typename autocall_function<T, F>::type;

template<typename T, typename F>
using autocall_arguments_t = typename autocall_arguments<T, F>::type;

template<typename T, typename F>
using is_valid_autocall_function = std::integral_constant<bool,
	is_invoke_call<F>::value || is_member_autocall<T, F>::value
>;

template<typename, typename = void>
struct map_entry {};

template<typename P>
struct map_entry<P, enable_if_t<is_service<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>::value>> {
	using Service = decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()));
};

template<typename P>
struct map_entry<P, enable_if_t<is_service<decltype(service_map(std::declval<P>()))>::value>> {
	using Service = decltype(service_map(std::declval<P>()));
};

template<typename P>
struct map_entry<P, enable_if_t<is_map<decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >()))>::value>> :
	decltype(service_map(std::declval<P>(), std::declval<kgr::Map<> >())) {};

template<typename P>
struct map_entry<P, enable_if_t<is_map<decltype(service_map(std::declval<P>()))>::value>> :
	decltype(service_map(std::declval<P>())) {};

} // namespace detail

template<typename P>
struct AdlMap : detail::map_entry<P> {};

} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_HPP
<|endoftext|>


<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP

#include "traits.hpp"
#include "meta_list.hpp"

namespace kgr {

struct Single {
	Single() = default;
	~Single() = default;
	Single(const Single&) = delete;
	Single& operator=(const Single&) = delete;
	Single(Single&&) = default;
	Single& operator=(Single&&) = default;
};

struct Virtual {};
struct Abstract : Virtual {};

template<typename T>
struct Default {
	using DefaultService = T;
};

template<typename... Types>
struct Overrides {
	using ParentTypes = detail::meta_list<Types...>;
};

namespace detail {

template<typename, typename = void>
struct parent_type_helper {
	using ParentTypes = meta_list<>;
};

template<typename T>
struct parent_type_helper<T, void_t<typename T::ParentTypes>> {
	using ParentTypes = typename T::ParentTypes;
};

template<typename T>
using parent_types = typename parent_type_helper<T>::ParentTypes;

template<typename, typename = void>
struct default_type_helper {
	using has_default = std::false_type;
};

template<typename T>
struct default_type_helper<T, void_t<typename T::DefaultService>> {
	using has_default = std::true_type;
	using Service = typename T::DefaultService;
};

template<typename T>
using default_type = typename default_type_helper<T>::Service;

template<typename T>
using has_default = typename default_type_helper<T>::has_default;

template<typename T>
using is_abstract_service = std::is_base_of<Abstract, T>;

template<typename T>
using is_single = std::integral_constant<bool, std::is_base_of<Single, T>::value || is_abstract_service<T>::value>;

template<typename T>
using is_virtual = std::integral_constant<bool, std::is_base_of<Virtual, T>::value || !meta_list_empty<parent_types<T>>::value>;

template<typename Service, typename Overrider>
using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>;

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
<commit_msg>Cleaned abstract and single definition<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP

#include "traits.hpp"
#include "meta_list.hpp"

namespace kgr {

struct Single {
	Single() = default;
	~Single() = default;
	Single(const Single&) = delete;
	Single& operator=(const Single&) = delete;
	Single(Single&&) = default;
	Single& operator=(Single&&) = default;
};

struct Virtual {};
struct Abstract : Virtual, Single {};

template<typename T>
struct Default {
	using DefaultService = T;
};

template<typename... Types>
struct Overrides {
	using ParentTypes = detail::meta_list<Types...>;
};

namespace detail {

template<typename, typename = void>
struct parent_type_helper {
	using ParentTypes = meta_list<>;
};

template<typename T>
struct parent_type_helper<T, void_t<typename T::ParentTypes>> {
	using ParentTypes = typename T::ParentTypes;
};

template<typename T>
using parent_types = typename parent_type_helper<T>::ParentTypes;

template<typename, typename = void>
struct default_type_helper {
	using has_default = std::false_type;
};

template<typename T>
struct default_type_helper<T, void_t<typename T::DefaultService>> {
	using has_default = std::true_type;
	using Service = typename T::DefaultService;
};

template<typename T>
using default_type = typename default_type_helper<T>::Service;

template<typename T>
using has_default = typename default_type_helper<T>::has_default;

template<typename T>
using is_abstract_service = std::is_base_of<Abstract, T>;

template<typename T>
using is_single = std::is_base_of<Single, T>;

template<typename T>
using is_virtual = std::integral_constant<bool, std::is_base_of<Virtual, T>::value || !meta_list_empty<parent_types<T>>::value>;

template<typename Service, typename Overrider>
using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>;

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
<|endoftext|>