<commit_before>// This file was automatically generated

/*
	Nazara Engine - Mathematics module

	Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com)
	                   Rémi "overdrivr" Bèges (remi.beges@laposte.net)

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

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

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

#pragma once

#ifndef NAZARA_GLOBAL_MATH_HPP
#define NAZARA_GLOBAL_MATH_HPP

#include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Math/BoundingVolume.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Math/Config.hpp>
#include <Nazara/Math/Enums.hpp>
#include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Frustum.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Math/OrientedBox.hpp>
#include <Nazara/Math/Plane.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Ray.hpp>
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Sphere.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Math/Vector4.hpp>

#endif // NAZARA_GLOBAL_MATH_HPP
<commit_msg>Math: Update global header<commit_after>// This file was automatically generated

/*
	Nazara Engine - Mathematics module

	Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com)
	                   Rémi "overdrivr" Bèges (remi.beges@laposte.net)

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

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

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

#pragma once

#ifndef NAZARA_GLOBAL_MATH_HPP
#define NAZARA_GLOBAL_MATH_HPP

#include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Math/Angle.hpp>
#include <Nazara/Math/BoundingVolume.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Math/Config.hpp>
#include <Nazara/Math/Enums.hpp>
#include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Frustum.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Math/OrientedBox.hpp>
#include <Nazara/Math/Plane.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Ray.hpp>
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Sphere.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Math/Vector4.hpp>

#endif // NAZARA_GLOBAL_MATH_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/web_contents_preferences.h"

#include <algorithm>
#include <string>
#include <vector>

#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/web_preferences.h"
#include "native_mate/dictionary.h"
#include "net/base/filename_util.h"

#if defined(OS_WIN)
#include "ui/gfx/switches.h"
#endif

DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsPreferences);

namespace atom {

// static
std::vector<WebContentsPreferences*> WebContentsPreferences::instances_;

WebContentsPreferences::WebContentsPreferences(
    content::WebContents* web_contents,
    const mate::Dictionary& web_preferences)
    : web_contents_(web_contents) {
  v8::Isolate* isolate = web_preferences.isolate();
  mate::Dictionary copied(isolate, web_preferences.GetHandle()->Clone());
  // Following fields should not be stored.
  copied.Delete("embedder");
  copied.Delete("isGuest");
  copied.Delete("session");

  mate::ConvertFromV8(isolate, copied.GetHandle(), &web_preferences_);
  web_contents->SetUserData(UserDataKey(), this);

  instances_.push_back(this);
}

WebContentsPreferences::~WebContentsPreferences() {
  instances_.erase(
      std::remove(instances_.begin(), instances_.end(), this),
      instances_.end());
}

void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
  web_preferences_.MergeDictionary(&extend);
}

// static
content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID(
    int process_id) {
  for (WebContentsPreferences* preferences : instances_) {
    content::WebContents* web_contents = preferences->web_contents_;
    if (web_contents->GetRenderProcessHost()->GetID() == process_id)
      return web_contents;
  }
  return nullptr;
}

// static
void WebContentsPreferences::AppendExtraCommandLineSwitches(
    content::WebContents* web_contents, base::CommandLine* command_line) {
  WebContentsPreferences* self = FromWebContents(web_contents);
  if (!self)
    return;

  base::DictionaryValue& web_preferences = self->web_preferences_;

  bool b;
#if defined(OS_WIN)
  // Check if DirectWrite is disabled.
  if (web_preferences.GetBoolean(options::kDirectWrite, &b) && !b)
    command_line->AppendSwitch(::switches::kDisableDirectWrite);
#endif

  // Check if plugins are enabled.
  if (web_preferences.GetBoolean("plugins", &b) && b)
    command_line->AppendSwitch(switches::kEnablePlugins);

  // Experimental flags.
  if (web_preferences.GetBoolean(options::kExperimentalFeatures, &b) && b)
    command_line->AppendSwitch(
        ::switches::kEnableExperimentalWebPlatformFeatures);
  if (web_preferences.GetBoolean(options::kExperimentalCanvasFeatures, &b) && b)
    command_line->AppendSwitch(::switches::kEnableExperimentalCanvasFeatures);

  // Check if we have node integration specified.
  bool node_integration = true;
  web_preferences.GetBoolean(options::kNodeIntegration, &node_integration);
  // Be compatible with old API of "node-integration" option.
  std::string old_token;
  if (web_preferences.GetString(options::kNodeIntegration, &old_token) &&
      old_token != "disable")
    node_integration = true;
  command_line->AppendSwitchASCII(switches::kNodeIntegration,
                                  node_integration ? "true" : "false");

  // The preload script.
  base::FilePath::StringType preload;
  if (web_preferences.GetString(options::kPreloadScript, &preload)) {
    if (base::FilePath(preload).IsAbsolute())
      command_line->AppendSwitchNative(switches::kPreloadScript, preload);
    else
      LOG(ERROR) << "preload script must have absolute path.";
  } else if (web_preferences.GetString(options::kPreloadURL, &preload)) {
    // Translate to file path if there is "preload-url" option.
    base::FilePath preload_path;
    if (net::FileURLToFilePath(GURL(preload), &preload_path))
      command_line->AppendSwitchPath(switches::kPreloadScript, preload_path);
    else
      LOG(ERROR) << "preload url must be file:// protocol.";
  }

  // The zoom factor.
  double zoom_factor = 1.0;
  if (web_preferences.GetDouble(options::kZoomFactor, &zoom_factor) &&
      zoom_factor != 1.0)
    command_line->AppendSwitchASCII(switches::kZoomFactor,
                                    base::DoubleToString(zoom_factor));

  // --guest-instance-id, which is used to identify guest WebContents.
  int guest_instance_id;
  if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id))
      command_line->AppendSwitchASCII(switches::kGuestInstanceID,
                                      base::IntToString(guest_instance_id));

  // Pass the opener's window id.
  int opener_id;
  if (web_preferences.GetInteger(options::kOpenerID, &opener_id))
      command_line->AppendSwitchASCII(switches::kOpenerID,
                                      base::IntToString(opener_id));

  // Enable blink features.
  std::string blink_features;
  if (web_preferences.GetString(options::kBlinkFeatures, &blink_features))
      command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
                                      blink_features);
}

// static
void WebContentsPreferences::OverrideWebkitPrefs(
    content::WebContents* web_contents, content::WebPreferences* prefs) {
  WebContentsPreferences* self = FromWebContents(web_contents);
  if (!self)
    return;

  bool b;
  if (self->web_preferences_.GetBoolean("javascript", &b))
    prefs->javascript_enabled = b;
  if (self->web_preferences_.GetBoolean("images", &b))
    prefs->images_enabled = b;
  if (self->web_preferences_.GetBoolean("textAreasAreResizable", &b))
    prefs->text_areas_are_resizable = b;
  if (self->web_preferences_.GetBoolean("webgl", &b))
    prefs->experimental_webgl_enabled = b;
  if (self->web_preferences_.GetBoolean("webaudio", &b))
    prefs->webaudio_enabled = b;
  if (self->web_preferences_.GetBoolean("webSecurity", &b)) {
    prefs->web_security_enabled = b;
    prefs->allow_displaying_insecure_content = !b;
    prefs->allow_running_insecure_content = !b;
  }
  if (self->web_preferences_.GetBoolean("allowDisplayingInsecureContent", &b))
    prefs->allow_displaying_insecure_content = b;
  if (self->web_preferences_.GetBoolean("allowRunningInsecureContent", &b))
    prefs->allow_running_insecure_content = b;
  const base::DictionaryValue* fonts = nullptr;
  if (self->web_preferences_.GetDictionary("defaultFontFamily", &fonts)) {
    base::string16 font;
    if (fonts->GetString("standard", &font))
      prefs->standard_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("serif", &font))
      prefs->serif_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("sansSerif", &font))
      prefs->sans_serif_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("monospace", &font))
      prefs->fixed_font_family_map[content::kCommonScript] = font;
  }
  int size;
  if (self->web_preferences_.GetInteger("defaultFontSize", &size))
    prefs->default_font_size = size;
  if (self->web_preferences_.GetInteger("defaultMonospaceFontSize", &size))
    prefs->default_fixed_font_size = size;
  if (self->web_preferences_.GetInteger("minimumFontSize", &size))
    prefs->minimum_font_size = size;
  std::string encoding;
  if (self->web_preferences_.GetString("defaultEncoding", &encoding))
    prefs->default_encoding = encoding;
}

}  // namespace atom
<commit_msg>Remove path for nodeIntgration value of 'disable'<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/web_contents_preferences.h"

#include <algorithm>
#include <string>
#include <vector>

#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/web_preferences.h"
#include "native_mate/dictionary.h"
#include "net/base/filename_util.h"

#if defined(OS_WIN)
#include "ui/gfx/switches.h"
#endif

DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsPreferences);

namespace atom {

// static
std::vector<WebContentsPreferences*> WebContentsPreferences::instances_;

WebContentsPreferences::WebContentsPreferences(
    content::WebContents* web_contents,
    const mate::Dictionary& web_preferences)
    : web_contents_(web_contents) {
  v8::Isolate* isolate = web_preferences.isolate();
  mate::Dictionary copied(isolate, web_preferences.GetHandle()->Clone());
  // Following fields should not be stored.
  copied.Delete("embedder");
  copied.Delete("isGuest");
  copied.Delete("session");

  mate::ConvertFromV8(isolate, copied.GetHandle(), &web_preferences_);
  web_contents->SetUserData(UserDataKey(), this);

  instances_.push_back(this);
}

WebContentsPreferences::~WebContentsPreferences() {
  instances_.erase(
      std::remove(instances_.begin(), instances_.end(), this),
      instances_.end());
}

void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
  web_preferences_.MergeDictionary(&extend);
}

// static
content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID(
    int process_id) {
  for (WebContentsPreferences* preferences : instances_) {
    content::WebContents* web_contents = preferences->web_contents_;
    if (web_contents->GetRenderProcessHost()->GetID() == process_id)
      return web_contents;
  }
  return nullptr;
}

// static
void WebContentsPreferences::AppendExtraCommandLineSwitches(
    content::WebContents* web_contents, base::CommandLine* command_line) {
  WebContentsPreferences* self = FromWebContents(web_contents);
  if (!self)
    return;

  base::DictionaryValue& web_preferences = self->web_preferences_;

  bool b;
#if defined(OS_WIN)
  // Check if DirectWrite is disabled.
  if (web_preferences.GetBoolean(options::kDirectWrite, &b) && !b)
    command_line->AppendSwitch(::switches::kDisableDirectWrite);
#endif

  // Check if plugins are enabled.
  if (web_preferences.GetBoolean("plugins", &b) && b)
    command_line->AppendSwitch(switches::kEnablePlugins);

  // Experimental flags.
  if (web_preferences.GetBoolean(options::kExperimentalFeatures, &b) && b)
    command_line->AppendSwitch(
        ::switches::kEnableExperimentalWebPlatformFeatures);
  if (web_preferences.GetBoolean(options::kExperimentalCanvasFeatures, &b) && b)
    command_line->AppendSwitch(::switches::kEnableExperimentalCanvasFeatures);

  // Check if we have node integration specified.
  bool node_integration = true;
  web_preferences.GetBoolean(options::kNodeIntegration, &node_integration);
  command_line->AppendSwitchASCII(switches::kNodeIntegration,
                                  node_integration ? "true" : "false");

  // The preload script.
  base::FilePath::StringType preload;
  if (web_preferences.GetString(options::kPreloadScript, &preload)) {
    if (base::FilePath(preload).IsAbsolute())
      command_line->AppendSwitchNative(switches::kPreloadScript, preload);
    else
      LOG(ERROR) << "preload script must have absolute path.";
  } else if (web_preferences.GetString(options::kPreloadURL, &preload)) {
    // Translate to file path if there is "preload-url" option.
    base::FilePath preload_path;
    if (net::FileURLToFilePath(GURL(preload), &preload_path))
      command_line->AppendSwitchPath(switches::kPreloadScript, preload_path);
    else
      LOG(ERROR) << "preload url must be file:// protocol.";
  }

  // The zoom factor.
  double zoom_factor = 1.0;
  if (web_preferences.GetDouble(options::kZoomFactor, &zoom_factor) &&
      zoom_factor != 1.0)
    command_line->AppendSwitchASCII(switches::kZoomFactor,
                                    base::DoubleToString(zoom_factor));

  // --guest-instance-id, which is used to identify guest WebContents.
  int guest_instance_id;
  if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id))
      command_line->AppendSwitchASCII(switches::kGuestInstanceID,
                                      base::IntToString(guest_instance_id));

  // Pass the opener's window id.
  int opener_id;
  if (web_preferences.GetInteger(options::kOpenerID, &opener_id))
      command_line->AppendSwitchASCII(switches::kOpenerID,
                                      base::IntToString(opener_id));

  // Enable blink features.
  std::string blink_features;
  if (web_preferences.GetString(options::kBlinkFeatures, &blink_features))
      command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
                                      blink_features);
}

// static
void WebContentsPreferences::OverrideWebkitPrefs(
    content::WebContents* web_contents, content::WebPreferences* prefs) {
  WebContentsPreferences* self = FromWebContents(web_contents);
  if (!self)
    return;

  bool b;
  if (self->web_preferences_.GetBoolean("javascript", &b))
    prefs->javascript_enabled = b;
  if (self->web_preferences_.GetBoolean("images", &b))
    prefs->images_enabled = b;
  if (self->web_preferences_.GetBoolean("textAreasAreResizable", &b))
    prefs->text_areas_are_resizable = b;
  if (self->web_preferences_.GetBoolean("webgl", &b))
    prefs->experimental_webgl_enabled = b;
  if (self->web_preferences_.GetBoolean("webaudio", &b))
    prefs->webaudio_enabled = b;
  if (self->web_preferences_.GetBoolean("webSecurity", &b)) {
    prefs->web_security_enabled = b;
    prefs->allow_displaying_insecure_content = !b;
    prefs->allow_running_insecure_content = !b;
  }
  if (self->web_preferences_.GetBoolean("allowDisplayingInsecureContent", &b))
    prefs->allow_displaying_insecure_content = b;
  if (self->web_preferences_.GetBoolean("allowRunningInsecureContent", &b))
    prefs->allow_running_insecure_content = b;
  const base::DictionaryValue* fonts = nullptr;
  if (self->web_preferences_.GetDictionary("defaultFontFamily", &fonts)) {
    base::string16 font;
    if (fonts->GetString("standard", &font))
      prefs->standard_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("serif", &font))
      prefs->serif_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("sansSerif", &font))
      prefs->sans_serif_font_family_map[content::kCommonScript] = font;
    if (fonts->GetString("monospace", &font))
      prefs->fixed_font_family_map[content::kCommonScript] = font;
  }
  int size;
  if (self->web_preferences_.GetInteger("defaultFontSize", &size))
    prefs->default_font_size = size;
  if (self->web_preferences_.GetInteger("defaultMonospaceFontSize", &size))
    prefs->default_fixed_font_size = size;
  if (self->web_preferences_.GetInteger("minimumFontSize", &size))
    prefs->minimum_font_size = size;
  std::string encoding;
  if (self->web_preferences_.GetString("defaultEncoding", &encoding))
    prefs->default_encoding = encoding;
}

}  // namespace atom
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2017)

#ifndef DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
#define DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
#if HAVE_DUNE_PYBINDXI

#include <dune/pybindxi/pybind11.h>

#include <dune/xt/grid/grids.bindings.hh>
#include <dune/xt/la/container.bindings.hh>

#include <dune/gdt/spaces.bindings.hh>

#include "dirichlet.hh"

namespace Dune {
namespace GDT {
namespace bindings {

template <class SP, class V>
class DirichletProjectionLocalizableOperator
{
  typedef typename SP::type SpaceType;
  static_assert(is_space<SpaceType>::value, "");
  static_assert(XT::LA::is_vector<V>::value, "");
  typedef typename SpaceType::GridViewType GridViewType;
  typedef typename XT::Functions::LocalizableFunctionInterface<typename SpaceType::EntityType,
                                                               typename SpaceType::DomainFieldType,
                                                               SpaceType::dimDomain,
                                                               typename SpaceType::RangeFieldType,
                                                               SpaceType::dimRange,
                                                               SpaceType::dimRangeCols>
      SourceType;
  typedef DiscreteFunction<SpaceType, V> RangeType;
  typedef XT::Grid::Walker<GridViewType> BaseType;

public:
  typedef GDT::DirichletProjectionLocalizableOperator<GridViewType, SourceType, RangeType, double> type;
  typedef pybind11::class_<type, BaseType> bound_type;

  static bound_type bind(pybind11::module& m)
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    const auto ClassName =
        XT::Common::to_camel_case("dirichlet_projection_localizable_operator_" + space_name<SP>::value() + "_"
                                  + XT::LA::bindings::container_name<V>::value());

    bound_type c(m, ClassName.c_str());
    c.def("apply", [](type& self) { self.apply(); });

    m.def(std::string("make_localizable_dirichlet_projection_operator").c_str(),
          [](const XT::Grid::BoundaryInfo<typename XT::Grid::Intersection<GridViewType>::Type>& boundary_info,
             const SourceType& source,
             RangeType& range) {
            return make_localizable_dirichlet_projection_operator(
                       range.space().grid_view(), boundary_info, source, range)
                .release();
          },
          "boundary_info"_a,
          "source"_a,
          "range"_a,
          py::keep_alive<0, 1>(),
          py::keep_alive<0, 2>(),
          py::keep_alive<0, 3>());

    return c;
  } // ... bind(...)
}; // class DirichletProjectionLocalizableOperator

// begin: this is what we need for the .so

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, _GRID, _layer, _backend, _r, _rC, _la)                                \
  Dune::GDT::bindings::                                                                                \
      DirichletProjectionLocalizableOperator<Dune::GDT::CgSpaceProvider<_GRID,                                         \
                                                                        Dune::XT::Grid::Layers::_layer,                \
                                                                        Dune::GDT::ChooseSpaceBackend::_backend,       \
                                                                        1,                                             \
                                                                        double,                                        \
                                                                        _r,                                            \
                                                                        _rC>,                                          \
                                             typename Dune::XT::LA::Container<double, Dune::XT::LA::Backends::_la>::   \
                                                 VectorType>::bind(_m)

#if HAVE_ALBERTA
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, _layer, _backend, _la)                                        \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, ALBERTA_2D, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, _layer, _backend, _la)
#endif

#if HAVE_DUNE_ALUGRID
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, _layer, _backend, _la)                                            \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, ALU_2D_SIMPLEX_CONFORMING, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, _layer, _backend, _la)
#endif

#if HAVE_DUNE_UGGRID || HAVE_UG
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, _layer, _backend, _la)                                             \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, UG_2D, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, _layer, _backend, _la)
#endif

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, _layer, _backend, _la)                                           \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, YASP_2D_EQUIDISTANT_OFFSET, _layer, _backend, 1, 1, _la)

#if HAVE_DUNE_FEM
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la)                                                              \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, leaf, fem, _la);                                                    \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, leaf, fem, _la);                                                        \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, leaf, fem, _la);                                                         \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, leaf, fem, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la)
#endif

#if HAVE_DUNE_PDELAB
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)                                                           \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, leaf, pdelab, _la);                                                 \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, leaf, pdelab, _la);                                                     \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, leaf, pdelab, _la)
//  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, leaf, pdelab, _la); // <- does not work
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)
#endif

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, _la)                                                         \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la);                                                                   \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_COMMON(_m) _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, common_dense)

#define DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m) _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_COMMON(_m)

// end: this is what we need for the .so

} // namespace bindings
} // namespace GDT
} // namespace Dune

#endif // HAVE_DUNE_PYBINDXI
#endif // DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
<commit_msg>[projections.dirichlet] add other la backends in bindings, refs #95<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2017)

#ifndef DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
#define DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
#if HAVE_DUNE_PYBINDXI

#include <dune/pybindxi/pybind11.h>

#include <dune/xt/grid/grids.bindings.hh>
#include <dune/xt/la/container.bindings.hh>

#include <dune/gdt/spaces.bindings.hh>

#include "dirichlet.hh"

namespace Dune {
namespace GDT {
namespace bindings {

template <class SP, class V>
class DirichletProjectionLocalizableOperator
{
  typedef typename SP::type SpaceType;
  static_assert(is_space<SpaceType>::value, "");
  static_assert(XT::LA::is_vector<V>::value, "");
  typedef typename SpaceType::GridViewType GridViewType;
  typedef typename XT::Functions::LocalizableFunctionInterface<typename SpaceType::EntityType,
                                                               typename SpaceType::DomainFieldType,
                                                               SpaceType::dimDomain,
                                                               typename SpaceType::RangeFieldType,
                                                               SpaceType::dimRange,
                                                               SpaceType::dimRangeCols>
      SourceType;
  typedef DiscreteFunction<SpaceType, V> RangeType;
  typedef XT::Grid::Walker<GridViewType> BaseType;

public:
  typedef GDT::DirichletProjectionLocalizableOperator<GridViewType, SourceType, RangeType, double> type;
  typedef pybind11::class_<type, BaseType> bound_type;

  static bound_type bind(pybind11::module& m)
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    const auto ClassName =
        XT::Common::to_camel_case("dirichlet_projection_localizable_operator_" + space_name<SP>::value() + "_"
                                  + XT::LA::bindings::container_name<V>::value());

    bound_type c(m, ClassName.c_str());
    c.def("apply", [](type& self) { self.apply(); });

    m.def(std::string("make_localizable_dirichlet_projection_operator").c_str(),
          [](const XT::Grid::BoundaryInfo<typename XT::Grid::Intersection<GridViewType>::Type>& boundary_info,
             const SourceType& source,
             RangeType& range) {
            return make_localizable_dirichlet_projection_operator(
                       range.space().grid_view(), boundary_info, source, range)
                .release();
          },
          "boundary_info"_a,
          "source"_a,
          "range"_a,
          py::keep_alive<0, 1>(),
          py::keep_alive<0, 2>(),
          py::keep_alive<0, 3>());

    return c;
  } // ... bind(...)
}; // class DirichletProjectionLocalizableOperator

// begin: this is what we need for the .so

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, _GRID, _layer, _backend, _r, _rC, _la)                                \
  Dune::GDT::bindings::                                                                                \
      DirichletProjectionLocalizableOperator<Dune::GDT::CgSpaceProvider<_GRID,                                         \
                                                                        Dune::XT::Grid::Layers::_layer,                \
                                                                        Dune::GDT::ChooseSpaceBackend::_backend,       \
                                                                        1,                                             \
                                                                        double,                                        \
                                                                        _r,                                            \
                                                                        _rC>,                                          \
                                             typename Dune::XT::LA::Container<double, Dune::XT::LA::Backends::_la>::   \
                                                 VectorType>::bind(_m)

#if HAVE_ALBERTA
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, _layer, _backend, _la)                                        \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, ALBERTA_2D, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, _layer, _backend, _la)
#endif

#if HAVE_DUNE_ALUGRID
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, _layer, _backend, _la)                                            \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, ALU_2D_SIMPLEX_CONFORMING, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, _layer, _backend, _la)
#endif

#if HAVE_DUNE_UGGRID || HAVE_UG
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, _layer, _backend, _la)                                             \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, UG_2D, _layer, _backend, 1, 1, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, _layer, _backend, _la)
#endif

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, _layer, _backend, _la)                                           \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m, YASP_2D_EQUIDISTANT_OFFSET, _layer, _backend, 1, 1, _la)

#if HAVE_DUNE_FEM
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la)                                                              \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, leaf, fem, _la);                                                    \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, leaf, fem, _la);                                                        \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, leaf, fem, _la);                                                         \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, leaf, fem, _la)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la)
#endif

#if HAVE_DUNE_PDELAB
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)                                                           \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALBERTA(_m, leaf, pdelab, _la);                                                 \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ALU(_m, leaf, pdelab, _la);                                                     \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_YASP(_m, leaf, pdelab, _la)
//  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_UG(_m, leaf, pdelab, _la); // <- does not work
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)
#endif

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, _la)                                                         \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_FEM(_m, _la);                                                                   \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_PDELAB(_m, _la)

#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_COMMON(_m) _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, common_dense)

#if HAVE_EIGEN
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_EIGEN(_m) _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, eigen_dense)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_EIGEN(_m)
#endif

#if HAVE_DUNE_ISTL
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ISTL(_m) _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_BACKENDS(_m, istl_dense)
#else
#define _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ISTL(_m)
#endif

#define DUNE_GDT_PROJECTIONS_DIRICHLET_BIND(_m)                                                                        \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_COMMON(_m);                                                                     \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_EIGEN(_m);                                                                      \
  _DUNE_GDT_PROJECTIONS_DIRICHLET_BIND_ISTL(_m)

// end: this is what we need for the .so

} // namespace bindings
} // namespace GDT
} // namespace Dune

#endif // HAVE_DUNE_PYBINDXI
#endif // DUNE_GDT_PROJECTIONS_DIRICHLET_BINDINGS_HH
<|endoftext|>


<commit_before>/*
 * Copyright 2015 C. Brett Witherspoon
 */

#ifndef COMM_BUFFER_HPP_
#define COMM_BUFFER_HPP_

#include <atomic>  // for std::atomic
#include <cstddef> // for std::size_t
#include <limits>  // for std::numeric_limits
#include <memory>  // for std::shared_ptr

namespace comm
{
namespace buffer
{

template<typename> class writer;
template<typename> class reader;

namespace detail
{
//! A class for buffer shared data
class impl
{
public:
    explicit impl(size_t num_items, size_t item_size);
    ~impl();
    impl(const impl &) = delete;
    impl(impl &&) = delete;
    impl & operator=(const impl &) = delete;
    impl & operator=(impl &&) = delete;
private:
    template<typename> friend class ::comm::buffer::writer;
    template<typename> friend class ::comm::buffer::reader;
    template<template<typename> class, typename> friend class base;
    void * d_base;
    size_t d_size;
    std::atomic<size_t> d_read;
    std::atomic<size_t> d_write;
};

//! A base class for a buffer
template<template<typename> class T, typename U>
class base
{
public:
    using value_type      = U;
    using size_type       = std::size_t;
    using difference_type = std::ptrdiff_t;
    using reference       = U &;
    using const_reference = const U &;
    using pointer         = U *;
    using const_pointer   = const U *;
    using iterator        = U *;
    using const_iterator  = const U *;

    static_assert(std::numeric_limits<size_type>::is_modulo,
                  "buffer::base: modulo arithmetic not supported");

    //! Returns an iterator to the beginning of the buffer
    iterator begin();

    //! Returns a constant iterator to the beginning of the buffer
    const_iterator begin() const;

    //! Returns a constant iterator to the beginning of the buffer
    const_iterator cbegin() const { return begin(); }

    //! Returns an iterator to the end of the buffer
    iterator end();

    //! Returns a constant iterator to the end of the buffer
    const_iterator end() const;

    //! Returns a constant iterator to the end of the buffer
    const_iterator cend() const { return end(); }

    //! Checks whether the buffer is empty
    bool empty() const { return d_impl->d_write == d_impl->d_read; }

    //! Returns the number of items in the buffer
    size_type size() const;

    //! Returns the maximum size of the buffer
    size_type max_size() const;

    //! Consume items from the buffer
    void consume(size_type n);

protected:
    explicit base(size_type n);

    explicit base(std::shared_ptr<impl> ptr);

    base(const base &) = delete;

    base(base &&) = default;

    base & operator=(const base &) = delete;

    base & operator=(base &&) = default;

    std::shared_ptr<impl> d_impl;

private:
    template<template<typename> class V, typename X,
             template<typename> class Y, typename Z>
    friend bool operator==(const base<V,X> & lhs, const base<Y,Z> & rhs);
};

template<template<typename> class T, typename U>
base<T,U>::base(size_type n)
    : d_impl{std::make_shared<impl>(n, sizeof(U))}
{ }

template<template<typename> class T, typename U>
base<T,U>::base(std::shared_ptr<impl> ptr)
    : d_impl{ptr}
{ }

template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::begin()
{
    const auto base = static_cast<pointer>(d_impl->d_base);
    return base + static_cast<const T<U> *>(this)->position();
}

template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::begin() const
{
    const auto base = static_cast<pointer>(d_impl->d_base);
    return base + static_cast<const T<U> *>(this)->position();
}

template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::end()
{
    return begin() + size();
}

template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::end() const
{
    return begin() + size();
}

template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::size() const
{
    const auto max = std::numeric_limits<size_type>::max();
    const auto underflow = max - d_impl->d_size / sizeof(U) + 1;

    auto sz = static_cast<const T<U> *>(this)->offset();

    if (sz >= underflow)
        sz -= underflow;

    return sz;
}

template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::max_size() const
{
    return d_impl->d_size / sizeof(U) - 1;
}

template<template<typename> class T, typename U>
void base<T,U>::consume(size_type n)
{
    const auto overflow = d_impl->d_size / sizeof(U);

    auto pos = static_cast<const T<U> *>(this)->position() + n;

    if (pos >= overflow)
        pos -= overflow;

    static_cast<T<U>*>(this)->position(pos);
}

//! Returns true of two buffers share the same data
template<template<typename> class T, typename U,
         template<typename> class V, typename X>
bool operator==(const base<T,U> & lhs, const base<V,X> & rhs)
{
  return lhs.d_impl == rhs.d_impl;
}

//! Returns false of two buffers share the same data
template<template<typename> class T, typename U,
         template<typename> class V, typename X>
bool operator!=(const base<T,U> & lhs, const base<V,X> & rhs)
{
  return !(lhs == rhs);
}

} // namespace detail

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

//! A class to read from a buffer
template<typename T>
class reader : public detail::base<reader,T>
{
public:
    using value_type      = T;
    using size_type       = typename detail::base<reader,T>::size_type;
    using difference_type = typename detail::base<reader,T>::difference_type;
    using reference       = T &;
    using const_reference = const T &;
    using pointer         = T *;
    using const_pointer   = const T *;
    using iterator        = T *;
    using const_iterator  = const T *;

    reader(const reader &) = delete;

    reader(reader &&) = default;

    reader & operator=(const reader &) = delete;

    reader & operator=(reader &&) = default;

private:
    using base_type = detail::base<reader,value_type>;

    template<typename> friend class writer;

    template<template<typename> class, typename> friend class detail::base;

    explicit reader(std::shared_ptr<detail::impl> ptr);

    size_type offset() const
    {
        return base_type::d_impl->d_write - base_type::d_impl->d_read;
    }

    size_type position() const
    {
        return base_type::d_impl->d_read;
    }

    void position(size_type pos)
    {
        base_type::d_impl->d_read = pos;
    }
};

template<typename T>
reader<T>::reader(std::shared_ptr<detail::impl> ptr)
    : detail::base<reader,T>(ptr)
{ }

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

//! A class to write to a buffer
template<typename T>
class writer : public detail::base<writer,T>
{
public:
    using value_type      = T;
    using size_type       = typename detail::base<reader,T>::size_type;
    using difference_type = typename detail::base<reader,T>::difference_type;
    using reference       = T &;
    using const_reference = const T &;
    using pointer         = T *;
    using const_pointer   = const T *;
    using iterator        = T *;
    using const_iterator  = const T *;

    writer();

    explicit writer(size_type n);

    writer(const writer &) = delete;

    writer(writer &&) = default;

    writer & operator=(const writer &) = delete;

    writer & operator=(writer &&) = default;

    template<typename U = T>
    reader<value_type> make_reader();

private:
    using base_type = detail::base<writer,value_type>;

    template<template<typename> class, typename> friend class detail::base;

    size_type offset() const
    {
        return base_type::d_impl->d_read - base_type::d_impl->d_write - 1;
    }

    size_type position() const
    {
        return base_type::d_impl->d_write;
    }

    void position(size_type pos) const
    {
        base_type::d_impl->d_write = pos;
    }
};

template<typename T>
writer<T>::writer()
    : detail::base<writer,T>{std::make_shared<detail::impl>(0, sizeof(T))}
{ }

template<typename T>
writer<T>::writer(size_type n)
    : detail::base<writer,T>{std::make_shared<detail::impl>(n, sizeof(T))}
{ }

template<typename T>
template<typename U>
reader<T> writer<T>::make_reader()
{
    return std::move(reader<U>{detail::base<writer,T>::d_impl});
}

} // namespace buffer
} // namespace comm

#endif /* COMM_BUFFER_HPP_ */
<commit_msg>buffer: add wait method<commit_after>/*
 * Copyright 2015 C. Brett Witherspoon
 */

#ifndef COMM_BUFFER_HPP_
#define COMM_BUFFER_HPP_

#include <atomic>  // for std::atomic
#include <cstddef> // for std::size_t
#include <limits>  // for std::numeric_limits
#include <memory>  // for std::shared_ptr
#include <mutex>
#include <condition_variable>

namespace comm
{
namespace buffer
{

template<typename> class writer;
template<typename> class reader;

namespace detail
{
//! A class for buffer shared data
class impl
{
public:
    explicit impl(size_t num_items, size_t item_size);
    ~impl();
    impl(const impl &) = delete;
    impl(impl &&) = delete;
    impl & operator=(const impl &) = delete;
    impl & operator=(impl &&) = delete;
private:
    template<typename> friend class ::comm::buffer::writer;
    template<typename> friend class ::comm::buffer::reader;
    template<template<typename> class, typename> friend class base;
    void * d_base;
    size_t d_size;
    std::atomic<size_t> d_read;
    std::mutex d_read_mutex;
    std::condition_variable d_read_cond;
    std::atomic<size_t> d_write;
    std::mutex d_write_mutex;
    std::condition_variable d_write_cond;
};

//! A base class for a buffer
template<template<typename> class T, typename U>
class base
{
public:
    using value_type      = U;
    using size_type       = std::size_t;
    using difference_type = std::ptrdiff_t;
    using reference       = U &;
    using const_reference = const U &;
    using pointer         = U *;
    using const_pointer   = const U *;
    using iterator        = U *;
    using const_iterator  = const U *;

    static_assert(std::numeric_limits<size_type>::is_modulo,
                  "buffer::base: modulo arithmetic not supported");

    //! Returns an iterator to the beginning of the buffer
    iterator begin();

    //! Returns a constant iterator to the beginning of the buffer
    const_iterator begin() const;

    //! Returns a constant iterator to the beginning of the buffer
    const_iterator cbegin() const { return begin(); }

    //! Returns an iterator to the end of the buffer
    iterator end();

    //! Returns a constant iterator to the end of the buffer
    const_iterator end() const;

    //! Returns a constant iterator to the end of the buffer
    const_iterator cend() const { return end(); }

    //! Checks whether the buffer is empty
    bool empty() const { return d_impl->d_write == d_impl->d_read; }

    //! Returns the number of items in the buffer
    size_type size() const;

    //! Returns the maximum size of the buffer
    size_type max_size() const;

    //! Consume items from the buffer
    void consume(size_type n);

    //! Wait for a number of items to be in the buffer
    void wait(size_type n);

protected:
    explicit base(size_type n);

    explicit base(std::shared_ptr<impl> ptr);

    base(const base &) = delete;

    base(base &&) = default;

    base & operator=(const base &) = delete;

    base & operator=(base &&) = default;

    std::shared_ptr<impl> d_impl;

private:
    template<template<typename> class V, typename X,
             template<typename> class Y, typename Z>
    friend bool operator==(const base<V,X> & lhs, const base<Y,Z> & rhs);
};

template<template<typename> class T, typename U>
base<T,U>::base(size_type n)
    : d_impl{std::make_shared<impl>(n, sizeof(U))}
{ }

template<template<typename> class T, typename U>
base<T,U>::base(std::shared_ptr<impl> ptr)
    : d_impl{ptr}
{ }

template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::begin()
{
    const auto base = static_cast<pointer>(d_impl->d_base);
    return base + static_cast<const T<U> *>(this)->position();
}

template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::begin() const
{
    const auto base = static_cast<pointer>(d_impl->d_base);
    return base + static_cast<const T<U> *>(this)->position();
}

template<template<typename> class T, typename U>
typename base<T,U>::iterator base<T,U>::end()
{
    return begin() + size();
}

template<template<typename> class T, typename U>
typename base<T,U>::const_iterator base<T,U>::end() const
{
    return begin() + size();
}

template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::size() const
{
    const auto max = std::numeric_limits<size_type>::max();
    const auto underflow = max - d_impl->d_size / sizeof(U) + 1;

    auto sz = static_cast<const T<U> *>(this)->offset();

    if (sz >= underflow)
        sz -= underflow;

    return sz;
}

template<template<typename> class T, typename U>
typename base<T,U>::size_type base<T,U>::max_size() const
{
    return d_impl->d_size / sizeof(U) - 1;
}

template<template<typename> class T, typename U>
void base<T,U>::consume(size_type n)
{
    const auto overflow = d_impl->d_size / sizeof(U);

    auto pos = static_cast<const T<U> *>(this)->position() + n;

    if (pos >= overflow)
        pos -= overflow;

    static_cast<T<U>*>(this)->update(pos);
}

//! Returns true of two buffers share the same data
template<template<typename> class T, typename U,
         template<typename> class V, typename X>
bool operator==(const base<T,U> & lhs, const base<V,X> & rhs)
{
  return lhs.d_impl == rhs.d_impl;
}

//! Returns false of two buffers share the same data
template<template<typename> class T, typename U,
         template<typename> class V, typename X>
bool operator!=(const base<T,U> & lhs, const base<V,X> & rhs)
{
  return !(lhs == rhs);
}

} // namespace detail

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

//! A class to read from a buffer
template<typename T>
class reader : public detail::base<reader,T>
{
public:
    using value_type      = T;
    using size_type       = typename detail::base<reader,T>::size_type;
    using difference_type = typename detail::base<reader,T>::difference_type;
    using reference       = T &;
    using const_reference = const T &;
    using pointer         = T *;
    using const_pointer   = const T *;
    using iterator        = T *;
    using const_iterator  = const T *;

    reader(const reader &) = delete;

    reader(reader &&) = default;

    reader & operator=(const reader &) = delete;

    reader & operator=(reader &&) = default;

    void wait(size_type n);

private:
    using base_type = detail::base<reader,value_type>;

    template<typename> friend class writer;

    template<template<typename> class, typename> friend class detail::base;

    explicit reader(std::shared_ptr<detail::impl> ptr);

    size_type offset() const
    {
        return base_type::d_impl->d_write - base_type::d_impl->d_read;
    }

    size_type position() const
    {
        return base_type::d_impl->d_read;
    }

    void update(size_type pos)
    {
        {
            std::lock_guard<std::mutex> lock(base_type::d_impl->d_read_mutex);
            base_type::d_impl->d_read = pos;
        }
        base_type::d_impl->d_read_cond.notify_all();
    }
};

template<typename T>
reader<T>::reader(std::shared_ptr<detail::impl> ptr)
    : detail::base<reader,T>(ptr)
{ }

template<typename T>
void reader<T>::wait(size_type n)
{
    std::unique_lock<std::mutex> lock(base_type::d_impl->d_read_mutex);
    base_type::d_impl->d_read_cond.wait(lock, [&]{ return this->size() >= n; });
}

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

//! A class to write to a buffer
template<typename T>
class writer : public detail::base<writer,T>
{
public:
    using value_type      = T;
    using size_type       = typename detail::base<reader,T>::size_type;
    using difference_type = typename detail::base<reader,T>::difference_type;
    using reference       = T &;
    using const_reference = const T &;
    using pointer         = T *;
    using const_pointer   = const T *;
    using iterator        = T *;
    using const_iterator  = const T *;

    writer();

    explicit writer(size_type n);

    writer(const writer &) = delete;

    writer(writer &&) = default;

    writer & operator=(const writer &) = delete;

    writer & operator=(writer &&) = default;

    void wait(size_type n);

    template<typename U = T>
    reader<value_type> make_reader();

private:
    using base_type = detail::base<writer,value_type>;

    template<template<typename> class, typename> friend class detail::base;

    size_type offset() const
    {
        return base_type::d_impl->d_read - base_type::d_impl->d_write - 1;
    }

    size_type position() const
    {
        return base_type::d_impl->d_write;
    }

    void update(size_type pos) const
    {
        {
            std::lock_guard<std::mutex> lock(base_type::d_impl->d_write_mutex);
            base_type::d_impl->d_write = pos;;
        }
        base_type::d_impl->d_write_cond.notify_all();
    }
};

template<typename T>
writer<T>::writer()
    : detail::base<writer,T>{std::make_shared<detail::impl>(0, sizeof(T))}
{ }

template<typename T>
writer<T>::writer(size_type n)
    : detail::base<writer,T>{std::make_shared<detail::impl>(n, sizeof(T))}
{ }

template<typename T>
void writer<T>::wait(size_type n)
{
    std::unique_lock<std::mutex> lock(base_type::d_impl->d_write_mutex);
    base_type::d_impl->d_write_cond.wait(lock, [&]{ return this->size() >= n; });
}

template<typename T>
template<typename U>
reader<T> writer<T>::make_reader()
{
    return std::move(reader<U>{detail::base<writer,T>::d_impl});
}

} // namespace buffer
} // namespace comm

#endif /* COMM_BUFFER_HPP_ */
<|endoftext|>


<commit_before>#ifndef RELIGHT_STREAM_HPP
#define RELIGHT_STREAM_HPP

#include "bytes.hpp"
#include "poller.hpp"
#include "var.hpp"

#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/util.h> // Pull PF_INET, PF_INET6

#include <functional>
#include <new>
#include <stdexcept>
#include <string>

#include <string.h>

#include <netinet/in.h>
#include <sys/socket.h>

struct bufferevent;

extern "C" {
void relight_bufev_event(bufferevent *, short, void *);
void relight_bufev_read(bufferevent *, void *);
void relight_bufev_write(bufferevent *, void *);
}

#ifdef RELIGHT_NAMESPACE
namespace RELIGHT_NAMESPACE {
#endif

class Stream {
  public:
    Stream(Var<Poller> poller) : Stream(poller, -1) {}

    Stream(Var<Poller> poller, evutil_socket_t filenum) : poller_(poller) {
        if ((bufev_ = bufferevent_socket_new(poller->get_event_base(), filenum,
                                           BEV_OPT_CLOSE_ON_FREE)) == nullptr) {
            throw std::bad_alloc();
        }
        bufferevent_setcb(bufev_, relight_bufev_read, relight_bufev_write,
                          relight_bufev_event, this);
        if (filenum != -1 && bufferevent_enable(bufev_, EV_READ) != 0) {
            throw std::runtime_error("bufferevent_enable");
        }
    }

    Stream(Stream &) = delete;
    Stream &operator=(Stream &) = delete;
    Stream(Stream &&) = delete;
    Stream &operator=(Stream &&) = delete;

    void connect_ipv4(const char *addr, int port, std::function<void()> cb,
                      std::function<void(int)> eb) {
        on_connect(cb);
        on_error(eb);
        if (bufferevent_getfd(bufev_) != -1) {
            emit_error(10);
            return;
        }
        sockaddr_in sin;
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        if (evutil_inet_pton(AF_INET, addr, &sin.sin_addr) != 1) {
            emit_error(20);
            return;
        }
        if (bufferevent_socket_connect_hostname(bufev_, nullptr, AF_INET, addr,
                                                port) != 0) {
            emit_error(30);
            return;
        }
    }

    void connect_ipv6(const char *addr, int port, std::function<void()> cb,
                      std::function<void(int)> eb) {
        on_connect(cb);
        on_error(eb);
        if (bufferevent_getfd(bufev_) != -1) {
            emit_error(10);
            return;
        }
        sockaddr_in6 sin6;
        memset(&sin6, 0, sizeof(sin6));
        sin6.sin6_family = AF_INET6;
        if (evutil_inet_pton(AF_INET6, addr, &sin6.sin6_addr) != 1) {
            emit_error(20);
            return;
        }
        if (bufferevent_socket_connect_hostname(bufev_, nullptr, AF_INET6, addr,
                                                port) != 0) {
            emit_error(30);
            return;
        }
    }

    void write(Var<Bytes> bytes) {
        if (bufferevent_write_buffer(bufev_, bytes->get_evbuffer()) != 0) {
            throw std::runtime_error("evbuffer_write_buffer");
        }
    }

    void write(std::string s) {
        if (bufferevent_write(bufev_, s.c_str(), s.length()) != 0) {
            throw std::runtime_error("bufferevent_write");
        }
    }

    void on_connect(std::function<void()> f) { connect_fn_ = f; }

    void emit_connect() {
        if (connect_fn_) {
            auto fn = connect_fn_;
            fn();
        }
    }

    void on_data(std::function<void(Var<Bytes>)> f) { data_fn_ = f; }

    void emit_read() {
        auto evbuff = bufferevent_get_input(bufev_);
        if (evbuff == nullptr) {
            throw std::runtime_error("bufferevent_get_input");
        }
        Var<Bytes> bytes(new Bytes(evbuff));
        emit_data(bytes);
    }

    void emit_data(Var<Bytes> bytes) {
        if (data_fn_) {
            auto fn = data_fn_;
            fn(bytes);
        }
    }

    void on_flush(std::function<void()> f) { flush_fn_ = f; }

    void emit_flush() {
        if (flush_fn_) {
            auto fn = flush_fn_;
            fn();
        }
    }

    void on_error(std::function<void(int)> f) { error_fn_ = f; }

    void emit_event(short event) {
        if ((event & BEV_EVENT_CONNECTED)) {
            if (bufferevent_enable(bufev_, EV_READ) != 0) {
                throw std::runtime_error("bufferevent_enable");
            }
            emit_connect();
        } else if ((event & BEV_EVENT_EOF)) {
            emit_error(3);
        } else if ((event & BEV_EVENT_TIMEOUT)) {
            emit_error(2);
        } else {
            emit_error(1);
        }
    }

    void emit_error(int error) {
        if (error_fn_) {
            auto fn = error_fn_;
            fn(error);
        }
    }

    void close() {
        if (bufev_ != nullptr) {
            bufferevent_free(bufev_);
            data_fn_ = nullptr;
            flush_fn_ = nullptr;
            error_fn_ = nullptr;
            bufev_ = nullptr;
        }
    }

    ~Stream() { close(); }

  private:
    bufferevent *bufev_ = nullptr;
    Var<Poller> poller_;
    std::function<void()> connect_fn_;
    std::function<void(Var<Bytes>)> data_fn_;
    std::function<void()> flush_fn_;
    std::function<void(int)> error_fn_;
};

#ifdef RELIGHT_NAMESPACE
}
#endif

#endif
<commit_msg>stream.hpp: fix self reference<commit_after>#ifndef RELIGHT_STREAM_HPP
#define RELIGHT_STREAM_HPP

#include "bytes.hpp"
#include "poller.hpp"
#include "var.hpp"

#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/util.h> // Pull PF_INET, PF_INET6

#include <functional>
#include <new>
#include <stdexcept>
#include <string>

#include <string.h>

#include <netinet/in.h>
#include <sys/socket.h>

struct bufferevent;

extern "C" {
void relight_bufev_event(bufferevent *, short, void *);
void relight_bufev_read(bufferevent *, void *);
void relight_bufev_write(bufferevent *, void *);
}

#ifdef RELIGHT_NAMESPACE
namespace RELIGHT_NAMESPACE {
#endif

class Stream {
  public:
    Stream(Var<Poller> poller) : Stream(poller, -1) {}

    Stream(Var<Poller> poller, evutil_socket_t filenum) : poller_(poller) {
        if ((bufev_ = bufferevent_socket_new(poller->get_event_base(), filenum,
                                           BEV_OPT_CLOSE_ON_FREE)) == nullptr) {
            throw std::bad_alloc();
        }
        bufferevent_setcb(bufev_, relight_bufev_read, relight_bufev_write,
                          relight_bufev_event, this);
        if (filenum != -1 && bufferevent_enable(bufev_, EV_READ) != 0) {
            throw std::runtime_error("bufferevent_enable");
        }
    }

    Stream(Stream &) = delete;
    Stream &operator=(Stream &) = delete;
    Stream(Stream &&) = delete;
    Stream &operator=(Stream &&) = delete;

    void connect_ipv4(const char *addr, int port, std::function<void()> cb,
                      std::function<void(int)> eb) {
        on_connect(cb);
        on_error(eb);
        if (bufferevent_getfd(bufev_) != -1) {
            emit_error(10);
            return;
        }
        sockaddr_in sin;
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        if (evutil_inet_pton(AF_INET, addr, &sin.sin_addr) != 1) {
            emit_error(20);
            return;
        }
        if (bufferevent_socket_connect_hostname(bufev_, nullptr, AF_INET, addr,
                                                port) != 0) {
            emit_error(30);
            return;
        }
    }

    void connect_ipv6(const char *addr, int port, std::function<void()> cb,
                      std::function<void(int)> eb) {
        on_connect(cb);
        on_error(eb);
        if (bufferevent_getfd(bufev_) != -1) {
            emit_error(10);
            return;
        }
        sockaddr_in6 sin6;
        memset(&sin6, 0, sizeof(sin6));
        sin6.sin6_family = AF_INET6;
        if (evutil_inet_pton(AF_INET6, addr, &sin6.sin6_addr) != 1) {
            emit_error(20);
            return;
        }
        if (bufferevent_socket_connect_hostname(bufev_, nullptr, AF_INET6, addr,
                                                port) != 0) {
            emit_error(30);
            return;
        }
    }

    void write(Var<Bytes> bytes) {
        if (bufferevent_write_buffer(bufev_, bytes->get_evbuffer()) != 0) {
            throw std::runtime_error("evbuffer_write_buffer");
        }
    }

    void write(std::string s) {
        if (bufferevent_write(bufev_, s.c_str(), s.length()) != 0) {
            throw std::runtime_error("bufferevent_write");
        }
    }

    void on_connect(std::function<void()> f) { connect_fn_ = f; }

    void emit_connect() {
        if (connect_fn_) {
            auto fn = connect_fn_;
            fn();
        }
    }

    void on_data(std::function<void(Var<Bytes>)> f) { data_fn_ = f; }

    void emit_read() {
        auto evbuff = bufferevent_get_input(bufev_);
        if (evbuff == nullptr) {
            throw std::runtime_error("bufferevent_get_input");
        }
        Var<Bytes> bytes(new Bytes(evbuff));
        emit_data(bytes);
    }

    void emit_data(Var<Bytes> bytes) {
        if (data_fn_) {
            auto fn = data_fn_;
            fn(bytes);
        }
    }

    void on_flush(std::function<void()> f) { flush_fn_ = f; }

    void emit_flush() {
        if (flush_fn_) {
            auto fn = flush_fn_;
            fn();
        }
    }

    void on_error(std::function<void(int)> f) { error_fn_ = f; }

    void emit_event(short event) {
        if ((event & BEV_EVENT_CONNECTED)) {
            if (bufferevent_enable(bufev_, EV_READ) != 0) {
                throw std::runtime_error("bufferevent_enable");
            }
            emit_connect();
        } else if ((event & BEV_EVENT_EOF)) {
            emit_error(3);
        } else if ((event & BEV_EVENT_TIMEOUT)) {
            emit_error(2);
        } else {
            emit_error(1);
        }
    }

    void emit_error(int error) {
        if (error_fn_) {
            auto fn = error_fn_;
            fn(error);
        }
    }

    void close() {
        if (bufev_ != nullptr) {
            bufferevent_free(bufev_);
            connect_fn_ = nullptr;
            data_fn_ = nullptr;
            flush_fn_ = nullptr;
            error_fn_ = nullptr;
            bufev_ = nullptr;
        }
    }

    ~Stream() { close(); }

  private:
    bufferevent *bufev_ = nullptr;
    Var<Poller> poller_;
    std::function<void()> connect_fn_;
    std::function<void(Var<Bytes>)> data_fn_;
    std::function<void()> flush_fn_;
    std::function<void(int)> error_fn_;
};

#ifdef RELIGHT_NAMESPACE
}
#endif

#endif
<|endoftext|>


<commit_before>#include "terminalpp/screen.hpp"
#include "terminalpp/terminal.hpp"
#include "expect_sequence.hpp"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>

using namespace terminalpp::literals;

class screen_test : public CppUnit::TestFixture
{
public :
    CPPUNIT_TEST_SUITE(screen_test);
        CPPUNIT_TEST(first_draw_of_blank_screen_draws_clear_screen_only);
        CPPUNIT_TEST(first_draw_of_screen_with_content_draws_clear_screen_then_content);
        CPPUNIT_TEST(drawing_after_drawing_draws_nothing);
        CPPUNIT_TEST(drawing_after_modifying_one_element_writes_one_element);
        CPPUNIT_TEST(drawing_after_modifying_two_elements_writes_two_elements);
        CPPUNIT_TEST(drawing_consecutive_elements_does_not_write_cursor_moves);
    CPPUNIT_TEST_SUITE_END();

private :
    void first_draw_of_blank_screen_draws_clear_screen_only();
    void first_draw_of_screen_with_content_draws_clear_screen_then_content();
    void drawing_after_drawing_draws_nothing();
    void drawing_after_modifying_one_element_writes_one_element();
    void drawing_after_modifying_two_elements_writes_two_elements();
    void drawing_consecutive_elements_does_not_write_cursor_moves();
};

CPPUNIT_TEST_SUITE_REGISTRATION(screen_test);

void screen_test::first_draw_of_blank_screen_draws_clear_screen_only()
{
    auto const size = terminalpp::extent{5, 5};
    auto const canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    // What is expected is that the screen will be cleared, and then since
    // each element is assumed to be a blank, and the canvas is also blank,
    // no further drawing is necessary.
    auto expected =
        reference_terminal.erase_in_display(
            terminalpp::terminal::erase_display::all);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::first_draw_of_screen_with_content_draws_clear_screen_then_content()
{
    using namespace terminalpp::literals;

    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    char ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    // What is expected here is that the screen will be cleared, and then
    // the content will be drawn starting by moving the cursor to the top
    // left and proceeding left-to-right, top-to-bottom, moving the cursor
    // on each new line.
    auto expected =
        reference_terminal.erase_in_display(
                terminalpp::terminal::erase_display::all);

    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        expected += reference_terminal.move_cursor({0, y});

        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            expected += reference_terminal.write(canvas[x][y]);
        }
    }

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_drawing_draws_nothing()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    // Since we have just drawn this screen, we expect that drawing it again
    // will yield no changes.
    auto expected = std::string("");
    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_modifying_one_element_writes_one_element()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';

    auto expected = reference_terminal.move_cursor({2, 3})
                  + reference_terminal.write("x"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_modifying_two_elements_writes_two_elements()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';
    canvas[3][4] = 'y';

    auto expected = reference_terminal.move_cursor({2, 3})
                  + reference_terminal.write("x"_ts)
                  + reference_terminal.move_cursor({3, 4})
                  + reference_terminal.write("y"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_consecutive_elements_does_not_write_cursor_moves()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';
    canvas[3][3] = 'y';

    auto expected = reference_terminal.move_cursor({2, 3})
                  + reference_terminal.write("xy"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}
<commit_msg>Suspect function order issues; split concatenation into several statements.<commit_after>#include "terminalpp/screen.hpp"
#include "terminalpp/terminal.hpp"
#include "expect_sequence.hpp"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>

using namespace terminalpp::literals;

class screen_test : public CppUnit::TestFixture
{
public :
    CPPUNIT_TEST_SUITE(screen_test);
        CPPUNIT_TEST(first_draw_of_blank_screen_draws_clear_screen_only);
        CPPUNIT_TEST(first_draw_of_screen_with_content_draws_clear_screen_then_content);
        CPPUNIT_TEST(drawing_after_drawing_draws_nothing);
        CPPUNIT_TEST(drawing_after_modifying_one_element_writes_one_element);
        CPPUNIT_TEST(drawing_after_modifying_two_elements_writes_two_elements);
        CPPUNIT_TEST(drawing_consecutive_elements_does_not_write_cursor_moves);
    CPPUNIT_TEST_SUITE_END();

private :
    void first_draw_of_blank_screen_draws_clear_screen_only();
    void first_draw_of_screen_with_content_draws_clear_screen_then_content();
    void drawing_after_drawing_draws_nothing();
    void drawing_after_modifying_one_element_writes_one_element();
    void drawing_after_modifying_two_elements_writes_two_elements();
    void drawing_consecutive_elements_does_not_write_cursor_moves();
};

CPPUNIT_TEST_SUITE_REGISTRATION(screen_test);

void screen_test::first_draw_of_blank_screen_draws_clear_screen_only()
{
    auto const size = terminalpp::extent{5, 5};
    auto const canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    // What is expected is that the screen will be cleared, and then since
    // each element is assumed to be a blank, and the canvas is also blank,
    // no further drawing is necessary.
    auto expected =
        reference_terminal.erase_in_display(
            terminalpp::terminal::erase_display::all);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::first_draw_of_screen_with_content_draws_clear_screen_then_content()
{
    using namespace terminalpp::literals;

    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    char ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    // What is expected here is that the screen will be cleared, and then
    // the content will be drawn starting by moving the cursor to the top
    // left and proceeding left-to-right, top-to-bottom, moving the cursor
    // on each new line.
    auto expected =
        reference_terminal.erase_in_display(
                terminalpp::terminal::erase_display::all);

    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        expected += reference_terminal.move_cursor({0, y});

        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            expected += reference_terminal.write(canvas[x][y]);
        }
    }

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_drawing_draws_nothing()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    // Since we have just drawn this screen, we expect that drawing it again
    // will yield no changes.
    auto expected = std::string("");
    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_modifying_one_element_writes_one_element()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';

    auto expected = reference_terminal.move_cursor({2, 3})
                  + reference_terminal.write("x"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_after_modifying_two_elements_writes_two_elements()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';
    canvas[3][4] = 'y';

    auto expected = reference_terminal.move_cursor({2, 3});
    expected += reference_terminal.write("x"_ts);
    expected += reference_terminal.move_cursor({3, 4});
    expected += reference_terminal.write("y"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}

void screen_test::drawing_consecutive_elements_does_not_write_cursor_moves()
{
    auto const size = terminalpp::extent{5, 5};
    auto canvas = terminalpp::canvas(size);
    auto terminal = terminalpp::terminal();
    auto reference_terminal = terminalpp::terminal();

    terminal.set_size(size);
    reference_terminal.set_size(size);

    auto screen = terminalpp::screen();

    auto ch = 'a';
    for (terminalpp::s32 y = 0; y < canvas.size().height; ++y)
    {
        for (terminalpp::s32 x = 0; x < canvas.size().width; ++x)
        {
            canvas[x][y] = ch++;
        }
    }

    screen.draw(terminal, canvas);

    canvas[2][3] = 'x';
    canvas[3][3] = 'y';

    auto expected = reference_terminal.move_cursor({2, 3})
                  + reference_terminal.write("xy"_ts);

    auto result = screen.draw(terminal, canvas);

    expect_sequence(expected, result);
}
<|endoftext|>


<commit_before>#include "struct.h"
#include "iterator.h"
Iterator * Struct::createIterator()
{
  return new StructIterator(this);
}

// bool Struct::match( Term &term ){
//   Struct *s = dynamic_cast<Struct*>(&term);
//   if( s ){
//     if( _name.symbol() != s->_name.symbol() ) return false;
//     if(arity() != s->arity())return false;
//     Iterator *s1 = createIterator();
//     Iterator *s2 = term.createIterator();
//     for( s1->first(), s2->first(); !s1->isDone() ; s1->next(), s2->next() ){
//       if( !s1->currentItem()->match( *s2->currentItem() ))
//         return false;
//     }
//     return true;
//   }
//   return Term::match(term);
// }

// string Struct::symbol() const {
//   if(_args.empty())
//   return  _name.symbol() + "()";
//   string ret = _name.symbol() + "(";
//   std::vector<Term *>::const_iterator it = _args.begin();
//   for (; it != _args.end()-1; ++it)
//     ret += (*it)->symbol()+", ";
//   ret  += (*it)->symbol()+")";
//   return ret;
// }
<commit_msg>Delete struct.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ci_atag2.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:22:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <ary_i/ci_atag2.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary_i/disdocum.hxx>

namespace ary
{
namespace inf
{

void    DocuTag_Display::Display_TextToken(
                            const csi::dsapi::DT_TextToken & ) {}
void    DocuTag_Display::Display_White() {}
void    DocuTag_Display::Display_MupType(
                            const csi::dsapi::DT_MupType & ) {}
void    DocuTag_Display::Display_MupMember(
                            const csi::dsapi::DT_MupMember & ) {}
void    DocuTag_Display::Display_MupConst(
                            const csi::dsapi::DT_MupConst & ) {}
void    DocuTag_Display::Display_Style(
                            const csi::dsapi::DT_Style & ) {}
void    DocuTag_Display::Display_EOL() {}

}   // namespace inf
}   // namespace ary

<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/03/28 16:01:55 rt 1.6.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ci_atag2.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include <ary_i/ci_atag2.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary_i/disdocum.hxx>

namespace ary
{
namespace inf
{

void    DocuTag_Display::Display_TextToken(
                            const csi::dsapi::DT_TextToken & ) {}
void    DocuTag_Display::Display_White() {}
void    DocuTag_Display::Display_MupType(
                            const csi::dsapi::DT_MupType & ) {}
void    DocuTag_Display::Display_MupMember(
                            const csi::dsapi::DT_MupMember & ) {}
void    DocuTag_Display::Display_MupConst(
                            const csi::dsapi::DT_MupConst & ) {}
void    DocuTag_Display::Display_Style(
                            const csi::dsapi::DT_Style & ) {}
void    DocuTag_Display::Display_EOL() {}

}   // namespace inf
}   // namespace ary

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parsenv2.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 14:19:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/parsenv2.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary/ary.hxx>
#include <ary/qualiname.hxx>
#include <ary_i/codeinf2.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_enumvalue.hxx>
#include <ary/idl/ip_ce.hxx>
#include <parser/parserinfo.hxx>
#include <adc_msg.hxx>
#include <s2_luidl/uidl_tok.hxx>
#include <x_parse2.hxx>

namespace csi
{
namespace uidl
{

UnoIDL_PE::~UnoIDL_PE()
{
}

void
UnoIDL_PE::EstablishContacts( UnoIDL_PE *               io_pParentPE,
                              ary::n22::Repository &    io_rRepository,
                              TokenProcessing_Result &  o_rResult )
{
    pRepository = &io_rRepository;
    aMyNode.EstablishContacts(io_pParentPE, io_rRepository.Gate_Idl(), o_rResult);
}

//void
//UnoIDL_PE::EstablishContacts( UnoIDL_PE *             io_pParentPE,
//                            ary::idl::Gate &          io_rGate,
//                            TokenProcessing_Result &  o_rResult )
//{
//  aMyNode.EstablishContacts(io_pParentPE, io_rGate, o_rResult);
//}

void
UnoIDL_PE::Enter( E_EnvStackAction  i_eWayOfEntering )
{
    switch (i_eWayOfEntering)
    {
        case push_sure:
                InitData();
                break;
        case push_try:
                csv_assert(false);
                break;
        case pop_success:
                ReceiveData();
                break;
        case pop_failure:
                throw X_AutodocParser(X_AutodocParser::x_Any);
                // no break because of throw
        default:
            csv_assert(false);
    }   // end switch
}

void
UnoIDL_PE::Leave( E_EnvStackAction  i_eWayOfLeaving )
{
    switch (i_eWayOfLeaving)
    {
        case push_sure:
                break;
        case push_try:
                csv_assert(false);
                break;
        case pop_success:
                TransferData();
                break;
        case pop_failure:
                throw X_AutodocParser(X_AutodocParser::x_Any);
                // no break because of throw
        default:
            csv_assert(false);
    }   // end switch
}

void
UnoIDL_PE::SetDocu( DYN ary::info::CodeInformation * let_dpDocu )
{
    pDocu = let_dpDocu;
}

void
UnoIDL_PE::SetPublished()
{
    if (NOT pDocu)
    {
        pDocu = new ary::info::CodeInformation;
    }
    pDocu->SetPublished();
}

void
UnoIDL_PE::SetOptional()
{
    if (NOT pDocu)
    {
        pDocu = new ary::info::CodeInformation;
    }
    pDocu->SetOptional();
}

void
UnoIDL_PE::PassDocuAt( ary::idl::CodeEntity & io_rCe )
{
    if (pDocu)
    {
        io_rCe.Set_Docu(pDocu.Release());
    }
    else if // KORR_FUTURE
            // Re-enable doc-warning for Enum Values, as soon as there is a
            //   @option -no-doc-for-enumvalues.
            (     io_rCe.ClassId() != ary::idl::Module::class_id
              AND io_rCe.ClassId() != ary::idl::EnumValue::class_id  )
    {
        TheMessages().Out_MissingDoc(
                        io_rCe.LocalName(),
                        ParseInfo().CurFile(),
                        ParseInfo().CurLine() );
    }
}

void
UnoIDL_PE::InitData()
{
    // Needs not anything to do.
}

void
UnoIDL_PE::ReceiveData()
{
    // Needs not anything to do.
}

const ary::idl::Module &
UnoIDL_PE::CurNamespace() const
{
    if ( Parent() != 0 )
        return Parent()->CurNamespace();
    else
    {
        csv_assert(false);
        return *(const ary::idl::Module*)0;
    }
}

const ParserInfo &
UnoIDL_PE::ParseInfo() const
{
    if ( Parent() != 0 )
        return Parent()->ParseInfo();
    else
    {
        csv_assert(false);
        return *(const ParserInfo*)0;
    }
}

UnoIDL_PE::UnoIDL_PE()
    :   aMyNode(),
        pDocu(),
        pRepository(0)
{
}

}   // namespace uidl
}   // namespace csi
<commit_msg>INTEGRATION: CWS adc18 (1.12.2); FILE MERGED 2007/10/19 13:03:22 np 1.12.2.3: #i81775# 2007/10/19 11:50:49 np 1.12.2.2: #i81775# 2007/10/18 15:23:20 np 1.12.2.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parsenv2.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 17:05:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/parsenv2.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary/ary.hxx>
#include <ary/getncast.hxx>
#include <ary/qualiname.hxx>
#include <ary/doc/d_oldidldocu.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_enum.hxx>
#include <ary/idl/i_enumvalue.hxx>
#include <ary/idl/i_module.hxx>
#include <ary/idl/ip_ce.hxx>
#include <parser/parserinfo.hxx>
#include <adc_msg.hxx>
#include <s2_luidl/uidl_tok.hxx>
#include <x_parse2.hxx>

namespace csi
{
namespace uidl
{

UnoIDL_PE::~UnoIDL_PE()
{
}

void
UnoIDL_PE::EstablishContacts( UnoIDL_PE *               io_pParentPE,
                              ary::Repository &         io_rRepository,
                              TokenProcessing_Result &  o_rResult )
{
    pRepository = &io_rRepository;
    aMyNode.EstablishContacts(io_pParentPE, io_rRepository.Gate_Idl(), o_rResult);
}

//void
//UnoIDL_PE::EstablishContacts( UnoIDL_PE *             io_pParentPE,
//                            ary::idl::Gate &          io_rGate,
//                            TokenProcessing_Result &  o_rResult )
//{
//  aMyNode.EstablishContacts(io_pParentPE, io_rGate, o_rResult);
//}

void
UnoIDL_PE::Enter( E_EnvStackAction  i_eWayOfEntering )
{
    switch (i_eWayOfEntering)
    {
        case push_sure:
                InitData();
                break;
        case push_try:
                csv_assert(false);
                break;
        case pop_success:
                ReceiveData();
                break;
        case pop_failure:
                throw X_AutodocParser(X_AutodocParser::x_Any);
                // no break because of throw
        default:
            csv_assert(false);
    }   // end switch
}

void
UnoIDL_PE::Leave( E_EnvStackAction  i_eWayOfLeaving )
{
    switch (i_eWayOfLeaving)
    {
        case push_sure:
                break;
        case push_try:
                csv_assert(false);
                break;
        case pop_success:
                TransferData();
                break;
        case pop_failure:
                throw X_AutodocParser(X_AutodocParser::x_Any);
                // no break because of throw
        default:
            csv_assert(false);
    }   // end switch
}

void
UnoIDL_PE::SetDocu( DYN ary::doc::OldIdlDocu * let_dpDocu )
{
    pDocu = let_dpDocu;
}

void
UnoIDL_PE::SetPublished()
{
    if (NOT pDocu)
    {
        pDocu = new ary::doc::OldIdlDocu;
    }
    pDocu->SetPublished();
}

void
UnoIDL_PE::SetOptional()
{
    if (NOT pDocu)
    {
        pDocu = new ary::doc::OldIdlDocu;
    }
    pDocu->SetOptional();
}

void
UnoIDL_PE::PassDocuAt( ary::idl::CodeEntity & io_rCe )
{
    if (pDocu)
    {
        io_rCe.Set_Docu(*pDocu.Release());
    }
    else if // KORR_FUTURE
            // Re-enable doc-warning for Enum Values, as soon as there is a
            //   @option -no-doc-for-enumvalues.
            (     NOT ary::is_type<ary::idl::Module>(io_rCe)
              AND NOT ary::is_type<ary::idl::Enum>(io_rCe)  )
    {
        TheMessages().Out_MissingDoc(
                        io_rCe.LocalName(),
                        ParseInfo().CurFile(),
                        ParseInfo().CurLine() );
    }
}

void
UnoIDL_PE::InitData()
{
    // Needs not anything to do.
}

void
UnoIDL_PE::ReceiveData()
{
    // Needs not anything to do.
}

const ary::idl::Module &
UnoIDL_PE::CurNamespace() const
{
    if ( Parent() != 0 )
        return Parent()->CurNamespace();
    else
    {
        csv_assert(false);
        return *(const ary::idl::Module*)0;
    }
}

const ParserInfo &
UnoIDL_PE::ParseInfo() const
{
    if ( Parent() != 0 )
        return Parent()->ParseInfo();
    else
    {
        csv_assert(false);
        return *(const ParserInfo*)0;
    }
}

UnoIDL_PE::UnoIDL_PE()
    :   aMyNode(),
        pDocu(),
        pRepository(0)
{
}

}   // namespace uidl
}   // namespace csi
<|endoftext|>