<commit_before>/**
 *  Base.cpp
 *
 *  Implementation file for the base of all classes
 *
 *  @copyright 2014 Copernica BV
 */
#include "includes.h"

/**
 *  Set up namespace
 */
namespace Php {

/**
 *  Store the object in the PHP object cache
 *  @param  entry               Class entry
 *  @return MixedObject
 */
MixedObject *Base::store(zend_class_entry *entry)
{
    // allocate memory for the object
    MixedObject *result = (MixedObject *)emalloc(sizeof(MixedObject));

    // store the new c++ object
    result->cpp = this;

    // store the class entry in the newly created object
    result->php.ce = entry;

    // @todo is this really necessary - and when do we destruct this data?
    // (if we remove this code, everything breaks down in a for ($object as $k => $v) loop)

    // the original create_object fills the initial object with the default properties,
    // we're going to do exactly the same. start with setting up a hashtable for the props
    ALLOC_HASHTABLE(result->php.properties);

    // initialize the hash table
    zend_hash_init(result->php.properties, 0, NULL, ZVAL_PTR_DTOR, 0);

#if PHP_VERSION_ID < 50399
    // initialize the properties
    zend_hash_copy(result->php.properties, &entry->default_properties, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
#else
    // version higher than 5.3 have an easier way to initialize
    object_properties_init(&result->php, entry);
#endif

    // the destructor and clone handlers are set to NULL. I dont know why, but they do not
    // seem to be necessary...
    _handle = zend_objects_store_put(result, (zend_objects_store_dtor_t)ClassBase::destructObject, (zend_objects_free_object_storage_t)ClassBase::freeObject, NULL TSRMLS_CC);

    // done
    return result;
}

/**
 *  Overridable method that is called right before an object is destructed
 */
void Base::__destruct() const
{
    // throw exception, so that the PHP-CPP library will check if the user
    // somehow registered an explicit __destruct method
    throw NotImplemented();
}

/**
 *  Overridable method that is called to check if a property is set
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @return bool
 */
bool Base::__isset(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the unset function can be called
    throw NotImplemented();
}

/**
 *  Overridable method that is called to set a new property
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @param  value
 */
void Base::__set(const Php::Value &key, const Php::Value &value) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the unset function can be called
    throw NotImplemented();
}

/**
 *  Retrieve a property
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @return value
 */
Php::Value Base::__get(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Remove a member
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param key
 */
void Base::__unset(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();
}

/**
 *  Call a method
 *
 *  This method is called when a method is called from the PHP script that
 *  was not explicitly defined. You can use this to catch variable method
 *  names, or to support all thinkable method names.
 *
 *  @param  method      Name of the method that was called
 *  @param  params      The parameters that were passed to the function
 *  @return Value       The return value
 */
Value Base::__call(const char *method, Parameters &params) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Call the class as if it was a function
 *
 *  This method is called when a an object is used with () operators:
 *  $object(). You can override this method to make objects callable.
 *
 *  @param  params      The parameters that were passed to the function
 *  @return Value       The return value
 */
Value Base::__invoke(Parameters &params) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Cast the object to a string
 *
 *  This method is called when an object is casted to a string, or when
 *  it is used in a string context
 *
 *  @return Value       The object as a string
 */
Value Base::__toString() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Cast the object to an integer
 *
 *  This method is called when an object is casted to an integer, or when
 *  it is used in an integer context
 *
 *  @return int         Integer value
 */
Value Base::__toInteger() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 0;
}

/**
 *  Cast the object to a float
 *
 *  This method is called when an object is casted to a float, or when it
 *  is used in a float context
 *
 *  @return double      Floating point value
 */
Value Base::__toFloat() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 0.0;
}

/**
 *  Cast the object to a boolean
 *
 *  This method is called when an object is casted to a bool, or when it
 *  is used in a boolean context
 *
 *  @return bool
 */
Value Base::__toBool() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return false;
}

/**
 *  Compare the object with a different object
 *
 *  Check how a different object compares to this object
 *
 *  @param  that        Object to compare with
 *  @return int
 */
int Base::__compare(const Base &that) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 1;
}

/**
 *  End namespace
 */
}

<commit_msg>fixed crashes for certain test cases on php 5.3<commit_after>/**
 *  Base.cpp
 *
 *  Implementation file for the base of all classes
 *
 *  @copyright 2014 Copernica BV
 */
#include "includes.h"

/**
 *  Set up namespace
 */
namespace Php {

/**
 *  Store the object in the PHP object cache
 *  @param  entry               Class entry
 *  @return MixedObject
 */
MixedObject *Base::store(zend_class_entry *entry)
{
    // allocate memory for the object
    MixedObject *result = (MixedObject *)emalloc(sizeof(MixedObject));

    // store the new c++ object
    result->cpp = this;

    // store the class entry in the newly created object
    result->php.ce = entry;

    // initialize the object
    zend_object_std_init(&result->php, entry);

#if PHP_VERSION_ID < 50399

    // tmp variable
    zval *tmp;

    // initialize the properties, php 5.3 way
    zend_hash_copy(result->php.properties, &entry->default_properties, (copy_ctor_func_t) zval_property_ctor, &tmp, sizeof(zval*));

#else

    // version higher than 5.3 have an easier way to initialize
    object_properties_init(&result->php, entry);

#endif

    // the destructor and clone handlers are set to NULL. I dont know why, but they do not
    // seem to be necessary...
    _handle = zend_objects_store_put(result, (zend_objects_store_dtor_t)ClassBase::destructObject, (zend_objects_free_object_storage_t)ClassBase::freeObject, NULL TSRMLS_CC);

    // done
    return result;
}

/**
 *  Overridable method that is called right before an object is destructed
 */
void Base::__destruct() const
{
    // throw exception, so that the PHP-CPP library will check if the user
    // somehow registered an explicit __destruct method
    throw NotImplemented();
}

/**
 *  Overridable method that is called to check if a property is set
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @return bool
 */
bool Base::__isset(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the unset function can be called
    throw NotImplemented();
}

/**
 *  Overridable method that is called to set a new property
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @param  value
 */
void Base::__set(const Php::Value &key, const Php::Value &value) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the unset function can be called
    throw NotImplemented();
}

/**
 *  Retrieve a property
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param  key
 *  @return value
 */
Php::Value Base::__get(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Remove a member
 *
 *  The default implementation does nothing, and the script will fall back
 *  to accessing the regular object properties
 *
 *  @param key
 */
void Base::__unset(const Php::Value &key) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();
}

/**
 *  Call a method
 *
 *  This method is called when a method is called from the PHP script that
 *  was not explicitly defined. You can use this to catch variable method
 *  names, or to support all thinkable method names.
 *
 *  @param  method      Name of the method that was called
 *  @param  params      The parameters that were passed to the function
 *  @return Value       The return value
 */
Value Base::__call(const char *method, Parameters &params) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Call the class as if it was a function
 *
 *  This method is called when a an object is used with () operators:
 *  $object(). You can override this method to make objects callable.
 *
 *  @param  params      The parameters that were passed to the function
 *  @return Value       The return value
 */
Value Base::__invoke(Parameters &params) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Cast the object to a string
 *
 *  This method is called when an object is casted to a string, or when
 *  it is used in a string context
 *
 *  @return Value       The object as a string
 */
Value Base::__toString() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return nullptr;
}

/**
 *  Cast the object to an integer
 *
 *  This method is called when an object is casted to an integer, or when
 *  it is used in an integer context
 *
 *  @return int         Integer value
 */
Value Base::__toInteger() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 0;
}

/**
 *  Cast the object to a float
 *
 *  This method is called when an object is casted to a float, or when it
 *  is used in a float context
 *
 *  @return double      Floating point value
 */
Value Base::__toFloat() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 0.0;
}

/**
 *  Cast the object to a boolean
 *
 *  This method is called when an object is casted to a bool, or when it
 *  is used in a boolean context
 *
 *  @return bool
 */
Value Base::__toBool() const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return false;
}

/**
 *  Compare the object with a different object
 *
 *  Check how a different object compares to this object
 *
 *  @param  that        Object to compare with
 *  @return int
 */
int Base::__compare(const Base &that) const
{
    // throw an exception that will be caught in the ClassBase class,
    // so that the default implementation of the function can be called
    throw NotImplemented();

    // unreachable code
    return 1;
}

/**
 *  End namespace
 */
}

<|endoftext|>


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

#ifndef lnav_bin2c_hh
#define lnav_bin2c_hh

#include <zlib.h>
#include <assert.h>
#include <sys/types.h>

#include "base/intern_string.hh"

struct bin_src_file {
    bin_src_file(const char *name, const unsigned char *data,
                 size_t compressed_size, size_t size)
        : bsf_name(name), bsf_data(new unsigned char[size + 1]), bsf_size(size)
    {
        uLongf zsize = size;
        auto rc = uncompress(this->bsf_data.get(), &zsize, data, compressed_size);
        assert(rc == Z_OK);
        assert(zsize == size);
        this->bsf_data[size] = '\0';
    };

    string_fragment to_string_fragment() const
    {
        return string_fragment{this->bsf_data.get(), 0, (int) this->bsf_size};
    }

    const char *get_name() const
    {
        return this->bsf_name;
    }

private:
    const char *bsf_name;
    std::unique_ptr<unsigned char[]> bsf_data;
    ssize_t bsf_size;
};

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

#ifndef lnav_bin2c_hh
#define lnav_bin2c_hh

#include <zlib.h>
#include <assert.h>
#include <sys/types.h>

#include <memory>

#include "base/intern_string.hh"

struct bin_src_file {
    bin_src_file(const char *name, const unsigned char *data,
                 size_t compressed_size, size_t size)
        : bsf_name(name), bsf_data(new unsigned char[size + 1]), bsf_size(size)
    {
        uLongf zsize = size;
        auto rc = uncompress(this->bsf_data.get(), &zsize, data, compressed_size);
        assert(rc == Z_OK);
        assert(zsize == size);
        this->bsf_data[size] = '\0';
    };

    string_fragment to_string_fragment() const
    {
        return string_fragment{this->bsf_data.get(), 0, (int) this->bsf_size};
    }

    const char *get_name() const
    {
        return this->bsf_name;
    }

private:
    const char *bsf_name;
    std::unique_ptr<unsigned char[]> bsf_data;
    ssize_t bsf_size;
};

#endif
<|endoftext|>


<commit_before><commit_msg>add inline to inlineable methods remove extraneous parameter<commit_after><|endoftext|>


<commit_before><commit_msg>Error fixed<commit_after><|endoftext|>


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

#include "ui/aura/shared/compound_event_filter.h"

#include "base/hash_tables.h"
#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/env.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/events/event.h"
#include "ui/base/hit_test.h"

namespace aura {
namespace shared {

namespace {

Window* FindFocusableWindowFor(Window* window) {
  while (window && !window->CanFocus())
    window = window->parent();
  return window;
}

Window* GetActiveWindow(Window* window) {
  DCHECK(window->GetRootWindow());
  return client::GetActivationClient(window->GetRootWindow())->
      GetActiveWindow();
}

bool ShouldHideCursorOnKeyEvent(const ui::KeyEvent& event) {
  // All alt and control key commands are ignored.
  if (event.IsAltDown() || event.IsControlDown())
    return false;

  static bool inited = false;
  static base::hash_set<int32> ignored_keys;
  if (!inited) {
    // Modifiers.
    ignored_keys.insert(ui::VKEY_SHIFT);
    ignored_keys.insert(ui::VKEY_CONTROL);
    ignored_keys.insert(ui::VKEY_MENU);

    // Search key == VKEY_LWIN.
    ignored_keys.insert(ui::VKEY_LWIN);

    // Function keys.
    for (int key = ui::VKEY_F1; key <= ui::VKEY_F24; ++key)
      ignored_keys.insert(key);

    // Media keys.
    for (int key = ui::VKEY_BROWSER_BACK; key <= ui::VKEY_MEDIA_LAUNCH_APP2;
         ++key) {
      ignored_keys.insert(key);
    }
    ignored_keys.insert(ui::VKEY_WLAN);
    ignored_keys.insert(ui::VKEY_BRIGHTNESS_DOWN);
    ignored_keys.insert(ui::VKEY_BRIGHTNESS_UP);
    ignored_keys.insert(ui::VKEY_KBD_BRIGHTNESS_DOWN);
    ignored_keys.insert(ui::VKEY_KBD_BRIGHTNESS_UP);

#if defined(OS_POSIX)
    ignored_keys.insert(ui::VKEY_POWER);
#endif

    inited = true;
  }

  if (ignored_keys.count(event.key_code()) > 0)
    return false;

  return true;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, public:

CompoundEventFilter::CompoundEventFilter() : cursor_hidden_by_filter_(false) {
}

CompoundEventFilter::~CompoundEventFilter() {
  // Additional filters are not owned by CompoundEventFilter and they
  // should all be removed when running here. |filters_| has
  // check_empty == true and will DCHECK failure if it is not empty.
}

// static
gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent(
    int window_component) {
  switch (window_component) {
    case HTBOTTOM:
      return ui::kCursorSouthResize;
    case HTBOTTOMLEFT:
      return ui::kCursorSouthWestResize;
    case HTBOTTOMRIGHT:
      return ui::kCursorSouthEastResize;
    case HTLEFT:
      return ui::kCursorWestResize;
    case HTRIGHT:
      return ui::kCursorEastResize;
    case HTTOP:
      return ui::kCursorNorthResize;
    case HTTOPLEFT:
      return ui::kCursorNorthWestResize;
    case HTTOPRIGHT:
      return ui::kCursorNorthEastResize;
    default:
      return ui::kCursorNull;
  }
}

void CompoundEventFilter::AddFilter(EventFilter* filter) {
  filters_.AddObserver(filter);
}

void CompoundEventFilter::RemoveFilter(EventFilter* filter) {
  filters_.RemoveObserver(filter);
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, private:

void CompoundEventFilter::UpdateCursor(Window* target, ui::MouseEvent* event) {
  // If drag and drop is in progress, let the drag drop client set the cursor
  // instead of setting the cursor here.
  aura::RootWindow* root_window = target->GetRootWindow();
  client::DragDropClient* drag_drop_client =
      client::GetDragDropClient(root_window);
  if (drag_drop_client && drag_drop_client->IsDragDropInProgress())
    return;

  client::CursorClient* cursor_client =
      client::GetCursorClient(root_window);
  if (cursor_client) {
    gfx::NativeCursor cursor = target->GetCursor(event->location());
    if (event->flags() & ui::EF_IS_NON_CLIENT) {
      int window_component =
          target->delegate()->GetNonClientComponent(event->location());
      cursor = CursorForWindowComponent(window_component);
    }

    cursor_client->SetCursor(cursor);
    cursor_client->SetDeviceScaleFactor(
        root_window->AsRootWindowHostDelegate()->GetDeviceScaleFactor());
  }
}

ui::EventResult CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnKeyEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnMouseEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL) {
      result |= filter->OnTouchEvent(event);
    }
  }
  return static_cast<ui::EventResult>(result);
}

void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target,
                                                     ui::Event* event,
                                                     bool show) {
  if (!(event->flags() & ui::EF_IS_SYNTHESIZED)) {
    client::CursorClient* client =
        client::GetCursorClient(target->GetRootWindow());
    if (client) {
      if (show && cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = false;
        client->ShowCursor(true);
      } else if (client->IsCursorVisible() && !show &&
                 !cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = true;
        client->ShowCursor(false);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, ui::EventHandler implementation:

ui::EventResult CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) {
  if (ShouldHideCursorOnKeyEvent(*event)) {
    SetCursorVisibilityOnEvent(
        static_cast<Window*>(event->target()), event, false);
  }

  return FilterKeyEvent(event);
}

ui::EventResult CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) {
  Window* window = static_cast<Window*>(event->target());
  WindowTracker window_tracker;
  window_tracker.Add(window);

  // We must always update the cursor, otherwise the cursor can get stuck if an
  // event filter registered with us consumes the event.
  // It should also update the cursor for clicking and wheels for ChromeOS boot.
  // When ChromeOS is booted, it hides the mouse cursor but immediate mouse
  // operation will show the cursor.
  // We also update the cursor for mouse enter in case a mouse cursor is sent to
  // outside of the root window and moved back for some reasons (e.g. running on
  // on Desktop for testing, or a bug in pointer barrier).
  if (event->type() == ui::ET_MOUSE_ENTERED ||
      event->type() == ui::ET_MOUSE_MOVED ||
      event->type() == ui::ET_MOUSE_PRESSED ||
      event->type() == ui::ET_MOUSEWHEEL) {
    SetCursorVisibilityOnEvent(window, event, true);
    UpdateCursor(window, event);
  }

  ui::EventResult result = FilterMouseEvent(event);
  if ((result & ui::ER_CONSUMED) ||
      !window_tracker.Contains(window) ||
      !window->GetRootWindow()) {
    return result;
  }

  if (event->type() == ui::ET_MOUSE_PRESSED &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return result;
}

ui::EventResult CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) {
  return ui::ER_UNHANDLED;
}

ui::EventResult CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) {
  ui::EventResult result = FilterTouchEvent(event);
  if (result == ui::ER_UNHANDLED &&
      event->type() == ui::ET_TOUCH_PRESSED) {
    SetCursorVisibilityOnEvent(
        static_cast<aura::Window*>(event->target()), event, false);
  }
  return result;
}

ui::EventResult CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnGestureEvent(event);
  }

  Window* window = static_cast<Window*>(event->target());
  if (event->type() == ui::ET_GESTURE_BEGIN &&
      event->details().touch_points() == 1 &&
      !(result & ui::ER_CONSUMED) &&
      window->GetRootWindow() &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return static_cast<ui::EventResult>(result);
}

}  // namespace shared
}  // namespace aura
<commit_msg>Revert 161386 - Ignore certain keys when hiding the cursor<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/aura/shared/compound_event_filter.h"

#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/env.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/events/event.h"
#include "ui/base/hit_test.h"

namespace aura {
namespace shared {

namespace {

Window* FindFocusableWindowFor(Window* window) {
  while (window && !window->CanFocus())
    window = window->parent();
  return window;
}

Window* GetActiveWindow(Window* window) {
  DCHECK(window->GetRootWindow());
  return client::GetActivationClient(window->GetRootWindow())->
      GetActiveWindow();
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, public:

CompoundEventFilter::CompoundEventFilter() : cursor_hidden_by_filter_(false) {
}

CompoundEventFilter::~CompoundEventFilter() {
  // Additional filters are not owned by CompoundEventFilter and they
  // should all be removed when running here. |filters_| has
  // check_empty == true and will DCHECK failure if it is not empty.
}

// static
gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent(
    int window_component) {
  switch (window_component) {
    case HTBOTTOM:
      return ui::kCursorSouthResize;
    case HTBOTTOMLEFT:
      return ui::kCursorSouthWestResize;
    case HTBOTTOMRIGHT:
      return ui::kCursorSouthEastResize;
    case HTLEFT:
      return ui::kCursorWestResize;
    case HTRIGHT:
      return ui::kCursorEastResize;
    case HTTOP:
      return ui::kCursorNorthResize;
    case HTTOPLEFT:
      return ui::kCursorNorthWestResize;
    case HTTOPRIGHT:
      return ui::kCursorNorthEastResize;
    default:
      return ui::kCursorNull;
  }
}

void CompoundEventFilter::AddFilter(EventFilter* filter) {
  filters_.AddObserver(filter);
}

void CompoundEventFilter::RemoveFilter(EventFilter* filter) {
  filters_.RemoveObserver(filter);
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, private:

void CompoundEventFilter::UpdateCursor(Window* target, ui::MouseEvent* event) {
  // If drag and drop is in progress, let the drag drop client set the cursor
  // instead of setting the cursor here.
  aura::RootWindow* root_window = target->GetRootWindow();
  client::DragDropClient* drag_drop_client =
      client::GetDragDropClient(root_window);
  if (drag_drop_client && drag_drop_client->IsDragDropInProgress())
    return;

  client::CursorClient* cursor_client =
      client::GetCursorClient(root_window);
  if (cursor_client) {
    gfx::NativeCursor cursor = target->GetCursor(event->location());
    if (event->flags() & ui::EF_IS_NON_CLIENT) {
      int window_component =
          target->delegate()->GetNonClientComponent(event->location());
      cursor = CursorForWindowComponent(window_component);
    }

    cursor_client->SetCursor(cursor);
    cursor_client->SetDeviceScaleFactor(
        root_window->AsRootWindowHostDelegate()->GetDeviceScaleFactor());
  }
}

ui::EventResult CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnKeyEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnMouseEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL) {
      result |= filter->OnTouchEvent(event);
    }
  }
  return static_cast<ui::EventResult>(result);
}

void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target,
                                                     ui::Event* event,
                                                     bool show) {
  if (!(event->flags() & ui::EF_IS_SYNTHESIZED)) {
    client::CursorClient* client =
        client::GetCursorClient(target->GetRootWindow());
    if (client) {
      if (show && cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = false;
        client->ShowCursor(true);
      } else if (client->IsCursorVisible() && !show &&
                 !cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = true;
        client->ShowCursor(false);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, ui::EventHandler implementation:

ui::EventResult CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) {
  SetCursorVisibilityOnEvent(
      static_cast<Window*>(event->target()), event, false);
  return FilterKeyEvent(event);
}

ui::EventResult CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) {
  Window* window = static_cast<Window*>(event->target());
  WindowTracker window_tracker;
  window_tracker.Add(window);

  // We must always update the cursor, otherwise the cursor can get stuck if an
  // event filter registered with us consumes the event.
  // It should also update the cursor for clicking and wheels for ChromeOS boot.
  // When ChromeOS is booted, it hides the mouse cursor but immediate mouse
  // operation will show the cursor.
  // We also update the cursor for mouse enter in case a mouse cursor is sent to
  // outside of the root window and moved back for some reasons (e.g. running on
  // on Desktop for testing, or a bug in pointer barrier).
  if (event->type() == ui::ET_MOUSE_ENTERED ||
      event->type() == ui::ET_MOUSE_MOVED ||
      event->type() == ui::ET_MOUSE_PRESSED ||
      event->type() == ui::ET_MOUSEWHEEL) {
    SetCursorVisibilityOnEvent(window, event, true);
    UpdateCursor(window, event);
  }

  ui::EventResult result = FilterMouseEvent(event);
  if ((result & ui::ER_CONSUMED) ||
      !window_tracker.Contains(window) ||
      !window->GetRootWindow()) {
    return result;
  }

  if (event->type() == ui::ET_MOUSE_PRESSED &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return result;
}

ui::EventResult CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) {
  return ui::ER_UNHANDLED;
}

ui::EventResult CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) {
  ui::EventResult result = FilterTouchEvent(event);
  if (result == ui::ER_UNHANDLED &&
      event->type() == ui::ET_TOUCH_PRESSED) {
    SetCursorVisibilityOnEvent(
        static_cast<aura::Window*>(event->target()), event, false);
  }
  return result;
}

ui::EventResult CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnGestureEvent(event);
  }

  Window* window = static_cast<Window*>(event->target());
  if (event->type() == ui::ET_GESTURE_BEGIN &&
      event->details().touch_points() == 1 &&
      !(result & ui::ER_CONSUMED) &&
      window->GetRootWindow() &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return static_cast<ui::EventResult>(result);
}

}  // namespace shared
}  // namespace aura
<|endoftext|>


<commit_before><commit_msg>Update to latest `bspc wm --dump` format<commit_after><|endoftext|>


<commit_before><commit_msg>Fix small bug in class ByteBuffer.<commit_after><|endoftext|>


<commit_before>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * bbb/core/type/sequence/sequence_operation.hpp
 *
 * author: ISHII 2bit
 * mail:   bit_by_bit@2bit.jp
 *
 * **** **** **** **** **** **** **** **** */

#pragma once

#include <bbb/core/tmp/integer_sequence/integer_sequence.hpp>

namespace bbb {
    namespace sequence_utils {
        namespace detail {
            template <typename sequence1, typename sequence2, typename ... sequences>
            struct sequence_cat;

            template <typename integer_type, integer_type ... indices1, integer_type ... indices2, typename sequence, typename ... sequences>
            struct sequence_cat<
                integer_sequence<integer_type, indices1 ...>,
                integer_sequence<integer_type, indices2 ...>,
                sequence,
                sequences ...
            > {
                using type = get_type<sequence_cat<integer_sequence<integer_type, indices1 ..., indices2 ...>, sequence, sequences ...>>;
            };

            template <typename integer_type, integer_type ... indices1, integer_type ... indices2>
            struct sequence_cat<
                integer_sequence<integer_type, indices1 ...>,
                integer_sequence<integer_type, indices2 ...>
            > {
                using type = integer_sequence<integer_type, indices1 ..., indices2 ...>;
            };
        };

        template <typename ... sequences>
        using sequence_cat = get_type<detail::sequence_cat<sequences ...>>;

        namespace detail {
            template <typename integer_type, typename sequence, integer_type ... fronts>
            struct sequence_prepend;

            template <typename integer_type, integer_type ... fronts, integer_type ... backs>
            struct sequence_prepend<integer_type, integer_sequence<integer_type, backs ...>, fronts ...> {
                using type = integer_sequence<integer_type, fronts ..., backs ...>;
            };
        };

        template <typename integer_type, typename sequence, integer_type ... fronts>
        using sequence_prepend = get_type<detail::sequence_prepend<integer_type, sequence, fronts ...>>;

        namespace detail {
            template <typename integer_type, typename sequence, integer_type ... backs>
            struct sequence_append;

            template <typename integer_type, integer_type ... fronts, integer_type ... backs>
            struct sequence_append<integer_type, integer_sequence<integer_type, fronts ...>, backs ...> {
                using type = integer_sequence<integer_type, fronts ..., backs ...>;
            };
        };

        template <typename integer_type, typename sequence, integer_type ... backs>
        using sequence_append = get_type<detail::sequence_append<integer_type, sequence, backs ...>>;
    };
    using namespace sequence_utils;
};
<commit_msg>add _t<commit_after>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * bbb/core/type/sequence/sequence_operation.hpp
 *
 * author: ISHII 2bit
 * mail:   bit_by_bit@2bit.jp
 *
 * **** **** **** **** **** **** **** **** */

#pragma once

#include <bbb/core/tmp/integer_sequence/integer_sequence.hpp>

namespace bbb {
    namespace sequence_utils {
        namespace detail {
            template <typename sequence1, typename sequence2, typename ... sequences>
            struct sequence_cat;

            template <typename integer_type, integer_type ... indices1, integer_type ... indices2, typename sequence, typename ... sequences>
            struct sequence_cat<
                integer_sequence<integer_type, indices1 ...>,
                integer_sequence<integer_type, indices2 ...>,
                sequence,
                sequences ...
            > {
                using type = get_type<sequence_cat<integer_sequence<integer_type, indices1 ..., indices2 ...>, sequence, sequences ...>>;
            };

            template <typename integer_type, integer_type ... indices1, integer_type ... indices2>
            struct sequence_cat<
                integer_sequence<integer_type, indices1 ...>,
                integer_sequence<integer_type, indices2 ...>
            > {
                using type = integer_sequence<integer_type, indices1 ..., indices2 ...>;
            };
        };

        template <typename ... sequences>
        using sequence_cat = detail::sequence_cat<sequences ...>;
        template <typename ... sequences>
        using sequence_cat_t = get_type<sequence_cat<sequences ...>>;

        namespace detail {
            template <typename integer_type, typename sequence, integer_type ... fronts>
            struct sequence_prepend;

            template <typename integer_type, integer_type ... fronts, integer_type ... backs>
            struct sequence_prepend<integer_type, integer_sequence<integer_type, backs ...>, fronts ...> {
                using type = integer_sequence<integer_type, fronts ..., backs ...>;
            };
        };

        template <typename integer_type, typename sequence, integer_type ... fronts>
        using sequence_prepend = detail::sequence_prepend<integer_type, sequence, fronts ...>;
        template <typename integer_type, typename sequence, integer_type ... fronts>
        using sequence_prepend_t = get_type<sequence_prepend<integer_type, sequence, fronts ...>>;

        namespace detail {
            template <typename integer_type, typename sequence, integer_type ... backs>
            struct sequence_append;

            template <typename integer_type, integer_type ... fronts, integer_type ... backs>
            struct sequence_append<integer_type, integer_sequence<integer_type, fronts ...>, backs ...> {
                using type = integer_sequence<integer_type, fronts ..., backs ...>;
            };
        };

        template <typename integer_type, typename sequence, integer_type ... backs>
        using sequence_append = detail::sequence_append<integer_type, sequence, backs ...>;
        template <typename integer_type, typename sequence, integer_type ... backs>
        using sequence_append_t = get_type<sequence_append<integer_type, sequence, backs ...>>;
    };
    using namespace sequence_utils;
};
<|endoftext|>


<commit_before><commit_msg>Fix router for routing to the same dest wire twice<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: exctools.cxx,v $
 *
 *  $Revision: 1.55 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:56:58 $
 *
 *  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
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------------

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include <svx/editdata.hxx>
#include <svx/editeng.hxx>
#include <svx/editobj.hxx>
#include <svx/editstat.hxx>

#include "document.hxx"
#include "patattr.hxx"
#include "attrib.hxx"
#include "globstr.hrc"
#include "scextopt.hxx"
#include "progress.hxx"
#include "rangenam.hxx"
#include "editutil.hxx"

#include "root.hxx"
#include "imp_op.hxx"
#include "excimp8.hxx"
#include "otlnbuff.hxx"
#include "excrecds.hxx"
#include "xcl97rec.hxx"
#include "formel.hxx"

#ifndef SC_XILINK_HXX
#include "xilink.hxx"
#endif
#ifndef SC_XECONTENT_HXX
#include "xecontent.hxx"
#endif

// - ALLGEMEINE ----------------------------------------------------------

RootData::RootData( void )
{
    eDateiTyp = BiffX;
    pExtSheetBuff = NULL;
    pTabNameBuff = NULL;
    pShrfmlaBuff = NULL;
    pExtNameBuff = NULL;
    pFmlaConverter = NULL;

    pAutoFilterBuffer = NULL;
    pPrintRanges = new _ScRangeListTabs;
    pPrintTitles = new _ScRangeListTabs;

    pTabId = NULL;
    pUserBViewList = NULL;

    pObjRecs = NULL;
    pEscher = NULL;

    pIR = NULL;
    pER = NULL;
}

RootData::~RootData()
{
    delete pExtSheetBuff;
    delete pTabNameBuff;
    delete pShrfmlaBuff;
    delete pExtNameBuff;
    delete pAutoFilterBuffer;
    delete pPrintRanges;
    delete pPrintTitles;
}

XclImpOutlineBuffer::XclImpOutlineBuffer( SCSIZE nNewSize )
{
    DBG_ASSERT( nNewSize > 0, "-OutlineBuffer::Ctor: nNewSize == 0!" );

    nSize = nNewSize + 1;
    pLevel = new BYTE[ nSize ];
    pOuted = new BOOL[ nSize ];
    pHidden = new BOOL[ nSize ];
    pOutlineArray = NULL;

    Reset();
}

XclImpOutlineBuffer::~XclImpOutlineBuffer()
{
    delete[] pLevel;
    delete[] pOuted;
    delete[] pHidden;
}

void XclImpOutlineBuffer::SetLevel( SCSIZE nIndex, BYTE nVal, BOOL bOuted, BOOL bHidden )
{
    if( nIndex < nSize )
    {
        pLevel[ nIndex ] = nVal;
        pOuted[ nIndex ] = bOuted;
        pHidden[ nIndex ] = bHidden;

        if( nIndex > nLast )
            nLast = nIndex;
        if( nVal > nMaxLevel )
            nMaxLevel = nVal;
    }
}

void XclImpOutlineBuffer::SetOutlineArray( ScOutlineArray* pOArray )
{
    pOutlineArray = pOArray;
}

// transtorm xcl-outline into SC-outline
void XclImpOutlineBuffer::MakeScOutline( void )
{
    if( !pOutlineArray || !HasOutline() )
        return;

    const UINT16    nNumLev         = 8;
    BOOL            bPreOutedLevel  = FALSE;
    BYTE            nCurrLevel      = 0;
    UINT16          nC;
    BOOL            bMakeHidden[ nNumLev ];
    BOOL            bMakeVisible[ nNumLev + 1 ];

    for( nC = 0; nC < nNumLev; nC++ )
        bMakeHidden[ nC ] = FALSE;
    for( nC = 0; nC <= nNumLev; nC++ )
        bMakeVisible[ nC ] = TRUE;
    if( nLast < (nSize - 1) )
        nLast++;

    // search for hidden attributes at end of level, move them to begin
    if( bButtonNormal )
    {
        for( BYTE nWorkLevel = 1; nWorkLevel <= nMaxLevel; nWorkLevel++ )
        {
            UINT16  nStartPos       = 0;
            BYTE    nCurrLevel  = 0;
            BYTE    nPrevLevel  = 0;

            for( UINT16 nC = 0 ; nC <= nLast ; nC++ )
            {
                nPrevLevel = nCurrLevel;
                nCurrLevel = pLevel[ nC ];
                if( (nPrevLevel < nWorkLevel) && (nCurrLevel >= nWorkLevel) )
                    nStartPos = nC;
                else if( (nPrevLevel >= nWorkLevel) && (nCurrLevel < nWorkLevel) )
                {
                    if( pOuted[ nC ] && pHidden[ nStartPos ] )
                    {
                        if( nStartPos )
                            pOuted[ nStartPos - 1 ] = TRUE;
                        else
                            bPreOutedLevel = TRUE;
                        pOuted[ nC ] = FALSE;
                    }
                }
            }
        }
    }
    else
        bPreOutedLevel = pHidden[ 0 ];

    // generate SC outlines
    UINT16  nPrevC;
    UINT16  nStart[ nNumLev ];
    BOOL    bDummy;
    BOOL    bPrevOuted  = bPreOutedLevel;
    BOOL    bCurrHidden = FALSE;
    BOOL    bPrevHidden = FALSE;

    for( nC = 0; nC <= nLast; nC++ )
    {
        BYTE nWorkLevel = pLevel[ nC ];

        nPrevC      = nC ? nC - 1 : 0;
        bPrevHidden = bCurrHidden;
        bCurrHidden = pHidden[ nC ];

        // open new levels
        while( nWorkLevel > nCurrLevel )
        {
            nCurrLevel++;
            bMakeHidden[ nCurrLevel ] = bPrevOuted;
            bMakeVisible[ nCurrLevel + 1 ] =
                bMakeVisible[ nCurrLevel ] && !bMakeHidden[ nCurrLevel ];
            nStart[ nCurrLevel ] = nC;
        }
        // close levels
        while( nWorkLevel < nCurrLevel )
        {
            BOOL bLastLevel     = (nWorkLevel == (nCurrLevel - 1));
            BOOL bRealHidden    = (bMakeHidden[ nCurrLevel ] && bPrevHidden );
            BOOL bRealVisible   = (bMakeVisible[ nCurrLevel ] ||
                                    (!bCurrHidden && bLastLevel));

            pOutlineArray->Insert( nStart[ nCurrLevel ], nPrevC , bDummy,
                bRealHidden, bRealVisible );
            nCurrLevel--;
        }

        bPrevOuted = pOuted[ nC ];
    }
}

void XclImpOutlineBuffer::SetLevelRange( SCSIZE nF, SCSIZE nL, BYTE nVal,
                                    BOOL bOuted, BOOL bHidden )
{
    DBG_ASSERT( nF <= nL, "+OutlineBuffer::SetLevelRange(): Last < First!" );

    if( nL < nSize )
    {
        if( nL > nLast )
            nLast = nL;

        BYTE*   pLevelCount;
        BYTE*   pLast;
        BOOL*   pOutedCount;
        BOOL*   pHiddenCount;

        pLevelCount = &pLevel[ nF ];
        pLast = &pLevel[ nL ];
        pOutedCount = &pOuted[ nF ];
        pHiddenCount = &pHidden[ nF ];

        while( pLevelCount <= pLast )
        {
            *( pLevelCount++ ) = nVal;
            *( pOutedCount++ ) = bOuted;
            *( pHiddenCount++ ) = bHidden;
        }

        if( nVal > nMaxLevel )
            nMaxLevel = nVal;
    }
}

void XclImpOutlineBuffer::Reset( void )
{
    for( SCSIZE nC = 0 ; nC < nSize ; nC++  )
    {
        pLevel[ nC ] = 0;
        pOuted[ nC ] = pHidden[ nC ] = FALSE;
    }
    nLast = 0;
    nMaxLevel = 0;
}

void XclImpOutlineBuffer::Reset( ScOutlineArray *pOArray )
{
    for( SCSIZE nC = 0 ; nC < nSize ; nC++  )
    {
        pLevel[ nC ] = 0;
        pOuted[ nC ] = pHidden[ nC ] = FALSE;
    }
    pOutlineArray = pOArray;
}

//___________________________________________________________________

ExcScenarioCell::ExcScenarioCell( const UINT16 nC, const UINT16 nR ) : nCol( nC ), nRow( nR )
{
}

void ExcScenarioCell::SetValue( const String& r )
{
    aValue = r;
}

#define EXCSCAPPEND(EXCSCCELL)  (List::Insert(EXCSCCELL,LIST_APPEND))
#define EXCSCFIRST()            ((ExcScenarioCell*)List::First())
#define EXCSCNEXT()             ((ExcScenarioCell*)List::Next())

ExcScenario::ExcScenario( XclImpStream& rIn, const RootData& rR ) : nTab( rR.pIR->GetCurrScTab() )
{
    UINT16          nCref;
    UINT8           nName, nComment;

    rIn >> nCref;
    rIn >> nProtected;
    rIn.Ignore( 1 );                // Hide
    rIn >> nName >> nComment;
    rIn.Ignore( 1 );        // statt nUser!

    if( nName )
        pName = new String( rIn.ReadUniString( nName ) );
    else
    {
        pName = new String( RTL_CONSTASCII_USTRINGPARAM( "Scenery" ) );
        rIn.Ignore( 1 );
    }

    pUserName = new String( rIn.ReadUniString() );

    if( nComment )
        pComment = new String( rIn.ReadUniString() );
    else
        pComment = new String;

    UINT16          n = nCref;
    UINT16          nC, nR;
    while( n )
    {
        rIn >> nR >> nC;

        EXCSCAPPEND( new ExcScenarioCell( nC, nR ) );

        n--;
    }

    n = nCref;
    ExcScenarioCell*    p = EXCSCFIRST();
    while( p )
    {
        p->SetValue( rIn.ReadUniString() );

        p = EXCSCNEXT();
    }
}

ExcScenario::~ExcScenario()
{
    ExcScenarioCell*    p = EXCSCFIRST();

    while( p )
    {
        delete p;
        p = EXCSCNEXT();
    }

    if( pName )
        delete pName;
    if( pComment )
        delete pComment;
    if( pUserName )
        delete pUserName;
}

void ExcScenario::Apply( const XclImpRoot& rRoot, const BOOL bLast )
{
    UINT32              nNumCells = List::Count();

    ScDocument&         r = rRoot.GetDoc();
    ExcScenarioCell*    p = EXCSCFIRST();
    String              aSzenName( *pName );
    ScfTools::ConvertToScSheetName( aSzenName );
    UINT16              nNewTab = nTab + 1;

    if( !r.InsertTab( nNewTab, aSzenName ) )
        return;

    r.SetScenario( nNewTab, TRUE );
    // #112621# do not show scenario frames
    r.SetScenarioData( nNewTab, *pComment, COL_LIGHTGRAY, /*SC_SCENARIO_SHOWFRAME|*/SC_SCENARIO_COPYALL|(nProtected ? SC_SCENARIO_PROTECT : 0) );

    while( p )
    {
        UINT16          nCol = p->nCol;
        UINT16          nRow = p->nRow;
        String          aVal = p->GetValue();

        r.ApplyFlagsTab( nCol, nRow, nCol, nRow, nNewTab, SC_MF_SCENARIO );

        r.SetString( nCol, nRow, nNewTab, aVal );

        p = EXCSCNEXT();
    }

    if( bLast )
        r.SetActiveScenario( nNewTab, TRUE );

    // #111896# modify what the Active tab is set to if the new
    // scenario tab occurs before the active tab.
    ScExtDocSettings& rDocSett = rRoot.GetExtDocOptions().GetDocSettings();
    if( (static_cast< SCCOL >( nTab ) < rDocSett.mnDisplTab) && (rDocSett.mnDisplTab < MAXTAB) )
        ++rDocSett.mnDisplTab;
    rRoot.GetTabInfo().InsertScTab( nNewTab );
}

ExcScenarioList::~ExcScenarioList()
{
    ExcScenario*    p = _First();

    while( p )
    {
        delete p;
        p = _Next();
    }
}

void ExcScenarioList::Apply( const XclImpRoot& rRoot )
{
    ExcScenario*    p = _Last();
    UINT16          n = ( UINT16 ) Count();

    while( p )
    {
        n--;
        p->Apply( rRoot, ( BOOL ) ( n == nLastScenario ) );
        p = _Prev();
    }
}

<commit_msg>INTEGRATION: CWS dr37 (1.54.4); FILE MERGED 2005/08/10 11:56:25 dr 1.54.4.1: #i53062# endless loop with outline in row 65536<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: exctools.cxx,v $
 *
 *  $Revision: 1.56 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-28 11:42:36 $
 *
 *  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
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------------

#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD

#include <svx/editdata.hxx>
#include <svx/editeng.hxx>
#include <svx/editobj.hxx>
#include <svx/editstat.hxx>

#include "document.hxx"
#include "patattr.hxx"
#include "attrib.hxx"
#include "globstr.hrc"
#include "scextopt.hxx"
#include "progress.hxx"
#include "rangenam.hxx"
#include "editutil.hxx"

#include "root.hxx"
#include "imp_op.hxx"
#include "excimp8.hxx"
#include "otlnbuff.hxx"
#include "excrecds.hxx"
#include "xcl97rec.hxx"
#include "formel.hxx"

#ifndef SC_XILINK_HXX
#include "xilink.hxx"
#endif
#ifndef SC_XECONTENT_HXX
#include "xecontent.hxx"
#endif

// - ALLGEMEINE ----------------------------------------------------------

RootData::RootData( void )
{
    eDateiTyp = BiffX;
    pExtSheetBuff = NULL;
    pTabNameBuff = NULL;
    pShrfmlaBuff = NULL;
    pExtNameBuff = NULL;
    pFmlaConverter = NULL;

    pAutoFilterBuffer = NULL;
    pPrintRanges = new _ScRangeListTabs;
    pPrintTitles = new _ScRangeListTabs;

    pTabId = NULL;
    pUserBViewList = NULL;

    pObjRecs = NULL;
    pEscher = NULL;

    pIR = NULL;
    pER = NULL;
}

RootData::~RootData()
{
    delete pExtSheetBuff;
    delete pTabNameBuff;
    delete pShrfmlaBuff;
    delete pExtNameBuff;
    delete pAutoFilterBuffer;
    delete pPrintRanges;
    delete pPrintTitles;
}

XclImpOutlineBuffer::XclImpOutlineBuffer( SCSIZE nNewSize )
{
    DBG_ASSERT( nNewSize > 0, "-OutlineBuffer::Ctor: nNewSize == 0!" );

    nSize = nNewSize + 1;
    pLevel = new BYTE[ nSize ];
    pOuted = new BOOL[ nSize ];
    pHidden = new BOOL[ nSize ];
    pOutlineArray = NULL;

    Reset();
}

XclImpOutlineBuffer::~XclImpOutlineBuffer()
{
    delete[] pLevel;
    delete[] pOuted;
    delete[] pHidden;
}

void XclImpOutlineBuffer::SetLevel( SCSIZE nIndex, BYTE nVal, BOOL bOuted, BOOL bHidden )
{
    if( nIndex < nSize )
    {
        pLevel[ nIndex ] = nVal;
        pOuted[ nIndex ] = bOuted;
        pHidden[ nIndex ] = bHidden;

        if( nIndex > nLast )
            nLast = nIndex;
        if( nVal > nMaxLevel )
            nMaxLevel = nVal;
    }
}

void XclImpOutlineBuffer::SetOutlineArray( ScOutlineArray* pOArray )
{
    pOutlineArray = pOArray;
}

// transtorm xcl-outline into SC-outline
void XclImpOutlineBuffer::MakeScOutline( void )
{
    if( !pOutlineArray || !HasOutline() )
        return;

    const UINT16    nNumLev         = 8;
    BOOL            bPreOutedLevel  = FALSE;
    BYTE            nCurrLevel      = 0;
    BOOL            bMakeHidden[ nNumLev ];
    BOOL            bMakeVisible[ nNumLev + 1 ];

    sal_uInt16 nLevel;
    for( nLevel = 0; nLevel < nNumLev; ++nLevel )
        bMakeHidden[ nLevel ] = FALSE;
    for( nLevel = 0; nLevel <= nNumLev; ++nLevel )
        bMakeVisible[ nLevel ] = TRUE;
    if( nLast < (nSize - 1) )
        nLast++;

    // search for hidden attributes at end of level, move them to begin
    if( bButtonNormal )
    {
        for( BYTE nWorkLevel = 1; nWorkLevel <= nMaxLevel; nWorkLevel++ )
        {
            UINT16  nStartPos       = 0;
            BYTE    nCurrLevel  = 0;
            BYTE    nPrevLevel  = 0;

            for( SCSIZE nC = 0 ; nC <= nLast ; nC++ )
            {
                nPrevLevel = nCurrLevel;
                nCurrLevel = pLevel[ nC ];
                if( (nPrevLevel < nWorkLevel) && (nCurrLevel >= nWorkLevel) )
                    nStartPos = static_cast< sal_uInt16 >( nC );
                else if( (nPrevLevel >= nWorkLevel) && (nCurrLevel < nWorkLevel) )
                {
                    if( pOuted[ nC ] && pHidden[ nStartPos ] )
                    {
                        if( nStartPos )
                            pOuted[ nStartPos - 1 ] = TRUE;
                        else
                            bPreOutedLevel = TRUE;
                        pOuted[ nC ] = FALSE;
                    }
                }
            }
        }
    }
    else
        bPreOutedLevel = pHidden[ 0 ];

    // generate SC outlines
    UINT16  nPrevC;
    UINT16  nStart[ nNumLev ];
    BOOL    bDummy;
    BOOL    bPrevOuted  = bPreOutedLevel;
    BOOL    bCurrHidden = FALSE;
    BOOL    bPrevHidden = FALSE;

    for( SCSIZE nC = 0; nC <= nLast; nC++ )
    {
        BYTE nWorkLevel = pLevel[ nC ];

        nPrevC      = static_cast< sal_uInt16 >( nC ? nC - 1 : 0 );
        bPrevHidden = bCurrHidden;
        bCurrHidden = pHidden[ nC ];

        // open new levels
        while( nWorkLevel > nCurrLevel )
        {
            nCurrLevel++;
            bMakeHidden[ nCurrLevel ] = bPrevOuted;
            bMakeVisible[ nCurrLevel + 1 ] =
                bMakeVisible[ nCurrLevel ] && !bMakeHidden[ nCurrLevel ];
            nStart[ nCurrLevel ] = static_cast< sal_uInt16 >( nC );
        }
        // close levels
        while( nWorkLevel < nCurrLevel )
        {
            BOOL bLastLevel     = (nWorkLevel == (nCurrLevel - 1));
            BOOL bRealHidden    = (bMakeHidden[ nCurrLevel ] && bPrevHidden );
            BOOL bRealVisible   = (bMakeVisible[ nCurrLevel ] ||
                                    (!bCurrHidden && bLastLevel));

            pOutlineArray->Insert( nStart[ nCurrLevel ], nPrevC , bDummy,
                bRealHidden, bRealVisible );
            nCurrLevel--;
        }

        bPrevOuted = pOuted[ nC ];
    }
}

void XclImpOutlineBuffer::SetLevelRange( SCSIZE nF, SCSIZE nL, BYTE nVal,
                                    BOOL bOuted, BOOL bHidden )
{
    DBG_ASSERT( nF <= nL, "+OutlineBuffer::SetLevelRange(): Last < First!" );

    if( nL < nSize )
    {
        if( nL > nLast )
            nLast = nL;

        BYTE*   pLevelCount;
        BYTE*   pLast;
        BOOL*   pOutedCount;
        BOOL*   pHiddenCount;

        pLevelCount = &pLevel[ nF ];
        pLast = &pLevel[ nL ];
        pOutedCount = &pOuted[ nF ];
        pHiddenCount = &pHidden[ nF ];

        while( pLevelCount <= pLast )
        {
            *( pLevelCount++ ) = nVal;
            *( pOutedCount++ ) = bOuted;
            *( pHiddenCount++ ) = bHidden;
        }

        if( nVal > nMaxLevel )
            nMaxLevel = nVal;
    }
}

void XclImpOutlineBuffer::Reset( void )
{
    for( SCSIZE nC = 0 ; nC < nSize ; nC++  )
    {
        pLevel[ nC ] = 0;
        pOuted[ nC ] = pHidden[ nC ] = FALSE;
    }
    nLast = 0;
    nMaxLevel = 0;
}

void XclImpOutlineBuffer::Reset( ScOutlineArray *pOArray )
{
    for( SCSIZE nC = 0 ; nC < nSize ; nC++  )
    {
        pLevel[ nC ] = 0;
        pOuted[ nC ] = pHidden[ nC ] = FALSE;
    }
    pOutlineArray = pOArray;
}

//___________________________________________________________________

ExcScenarioCell::ExcScenarioCell( const UINT16 nC, const UINT16 nR ) : nCol( nC ), nRow( nR )
{
}

void ExcScenarioCell::SetValue( const String& r )
{
    aValue = r;
}

#define EXCSCAPPEND(EXCSCCELL)  (List::Insert(EXCSCCELL,LIST_APPEND))
#define EXCSCFIRST()            ((ExcScenarioCell*)List::First())
#define EXCSCNEXT()             ((ExcScenarioCell*)List::Next())

ExcScenario::ExcScenario( XclImpStream& rIn, const RootData& rR ) : nTab( rR.pIR->GetCurrScTab() )
{
    UINT16          nCref;
    UINT8           nName, nComment;

    rIn >> nCref;
    rIn >> nProtected;
    rIn.Ignore( 1 );                // Hide
    rIn >> nName >> nComment;
    rIn.Ignore( 1 );        // statt nUser!

    if( nName )
        pName = new String( rIn.ReadUniString( nName ) );
    else
    {
        pName = new String( RTL_CONSTASCII_USTRINGPARAM( "Scenery" ) );
        rIn.Ignore( 1 );
    }

    pUserName = new String( rIn.ReadUniString() );

    if( nComment )
        pComment = new String( rIn.ReadUniString() );
    else
        pComment = new String;

    UINT16          n = nCref;
    UINT16          nC, nR;
    while( n )
    {
        rIn >> nR >> nC;

        EXCSCAPPEND( new ExcScenarioCell( nC, nR ) );

        n--;
    }

    n = nCref;
    ExcScenarioCell*    p = EXCSCFIRST();
    while( p )
    {
        p->SetValue( rIn.ReadUniString() );

        p = EXCSCNEXT();
    }
}

ExcScenario::~ExcScenario()
{
    ExcScenarioCell*    p = EXCSCFIRST();

    while( p )
    {
        delete p;
        p = EXCSCNEXT();
    }

    if( pName )
        delete pName;
    if( pComment )
        delete pComment;
    if( pUserName )
        delete pUserName;
}

void ExcScenario::Apply( const XclImpRoot& rRoot, const BOOL bLast )
{
    UINT32              nNumCells = List::Count();

    ScDocument&         r = rRoot.GetDoc();
    ExcScenarioCell*    p = EXCSCFIRST();
    String              aSzenName( *pName );
    ScfTools::ConvertToScSheetName( aSzenName );
    UINT16              nNewTab = nTab + 1;

    if( !r.InsertTab( nNewTab, aSzenName ) )
        return;

    r.SetScenario( nNewTab, TRUE );
    // #112621# do not show scenario frames
    r.SetScenarioData( nNewTab, *pComment, COL_LIGHTGRAY, /*SC_SCENARIO_SHOWFRAME|*/SC_SCENARIO_COPYALL|(nProtected ? SC_SCENARIO_PROTECT : 0) );

    while( p )
    {
        UINT16          nCol = p->nCol;
        UINT16          nRow = p->nRow;
        String          aVal = p->GetValue();

        r.ApplyFlagsTab( nCol, nRow, nCol, nRow, nNewTab, SC_MF_SCENARIO );

        r.SetString( nCol, nRow, nNewTab, aVal );

        p = EXCSCNEXT();
    }

    if( bLast )
        r.SetActiveScenario( nNewTab, TRUE );

    // #111896# modify what the Active tab is set to if the new
    // scenario tab occurs before the active tab.
    ScExtDocSettings& rDocSett = rRoot.GetExtDocOptions().GetDocSettings();
    if( (static_cast< SCCOL >( nTab ) < rDocSett.mnDisplTab) && (rDocSett.mnDisplTab < MAXTAB) )
        ++rDocSett.mnDisplTab;
    rRoot.GetTabInfo().InsertScTab( nNewTab );
}

ExcScenarioList::~ExcScenarioList()
{
    ExcScenario*    p = _First();

    while( p )
    {
        delete p;
        p = _Next();
    }
}

void ExcScenarioList::Apply( const XclImpRoot& rRoot )
{
    ExcScenario*    p = _Last();
    UINT16          n = ( UINT16 ) Count();

    while( p )
    {
        n--;
        p->Apply( rRoot, ( BOOL ) ( n == nLastScenario ) );
        p = _Prev();
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
//
//      ----------------------------------------------------------------
//      Check timeintegrator Miniapp:
//      ----------------------------------------------------------------
//
//
// Compile with: make check-timeintegrator
//
// Sample runs:  check-timeintegrator
//               check-timeintegrator -s 10
#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

/** Class for simple linear first order ODE.
 *
 *     du/dt  + a u = 0
 *
 */
class ODE : public TimeDependentOperator
{
protected:
   DenseMatrix A;
public:
   ODE(double a00,double a01,double a10,double a11) : TimeDependentOperator(2, 0.0)
   {
      A.SetSize(2,2);
      A(0,0) = a00;
      A(0,1) = a01;
      A(1,0) = a10;
      A(1,1) = a11;
   };

   virtual void Mult(const Vector &u, Vector &dudt) const;

   virtual void ImplicitSolve(const double dt,const Vector &u, Vector &dudt);

   virtual ~ODE() {};
};

void ODE::Mult(const Vector &u, Vector &dudt)  const
{
   A.Mult(u,dudt);
   dudt.Neg();
}

void ODE::ImplicitSolve(const double dt, const Vector &u, Vector &dudt)
{
   DenseMatrix I(2,2),T(2,2);
   I =  0.0;
   I(0,0) = I(1,1) = 1.0;
   Add(I,A,dt,T);
   T.Invert();

   Vector r(2);
   A.Mult(u,r);
   r.Neg();
   T.Mult(r,dudt);
}

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   int ode_solver_type = 11;
   double t_final = 0.5;
   double dt = 1.0e-2;
   double a00 =  0.0;
   double a01 =  1.0;
   double a10 = -1.0;
   double a11 =  0.0;

   int precision = 8;
   cout.precision(precision);

   OptionsParser args(argc, argv);
   args.AddOption(&ode_solver_type, "-s", "--ode-solver",
                  "ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
                  "\t   11 - Forward Euler, 12 - RK2, 13 - RK3 SSP, 14 - RK4, \n\t"
                  "\t   22 - Midpoint, 23 - SDIRK23, 24 - SDIRK34\n\t"
                  //"\t   70 -- 80 - Generalized alpha"
                 );
   args.AddOption(&t_final, "-tf", "--t-final",
                  "Final time; start time is 0.");
   args.AddOption(&dt, "-dt", "--time-step",
                  "Time step.");
   args.AddOption(&a00, "-a00", "--stiffness00",
                  "Coefficient.");
   args.AddOption(&a01, "-a01", "--stiffness01",
                  "Coefficient.");
   args.AddOption(&a10, "-a10", "--stiffness10",
                  "Coefficient.");
   args.AddOption(&a11, "-a11", "--stiffness11",
                  "Coefficient.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // 2. Define the ODE solver used for time integration. Several implicit
   //    singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
   //    explicit Runge-Kutta methods are available.
   ODESolver *ode_solver;
   switch (ode_solver_type)
   {
      // Implicit L-stable methods
      case 1: ode_solver = new BackwardEulerSolver; break;
      case 2: ode_solver = new SDIRK23Solver(2); break;
      case 3: ode_solver = new SDIRK33Solver; break;
      // Explicit methods
      case 11: ode_solver = new ForwardEulerSolver; break;
      case 12: ode_solver = new RK2Solver(0.5); break; // midpoint method
      case 13: ode_solver = new RK3SSPSolver; break;
      case 14: ode_solver = new RK4Solver; break;
      // Implicit A-stable methods (not L-stable)
      case 22: ode_solver = new ImplicitMidpointSolver; break;
      case 23: ode_solver = new SDIRK23Solver; break;
      case 24: ode_solver = new SDIRK34Solver; break;
      // Generalized-alpha solvers
      //case 70: ode_solver = new GeneralizedAlphaSolver(0.0); break;
      //case 71: ode_solver = new GeneralizedAlphaSolver(0.1); break;
      //case 72: ode_solver = new GeneralizedAlphaSolver(0.2); break;
      //case 73: ode_solver = new GeneralizedAlphaSolver(0.3); break;
      //case 74: ode_solver = new GeneralizedAlphaSolver(0.4); break;
      //case 75: ode_solver = new GeneralizedAlphaSolver(0.5); break;
      //case 76: ode_solver = new GeneralizedAlphaSolver(0.6); break;
      //case 77: ode_solver = new GeneralizedAlphaSolver(0.7); break;
      //case 78: ode_solver = new GeneralizedAlphaSolver(0.8); break;
      //case 79: ode_solver = new GeneralizedAlphaSolver(0.9); break;
      //case 80: ode_solver = new GeneralizedAlphaSolver(1.0); break;
      default:
         cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
         return 3;
   }

   // 3. Set the initial conditions for u.
   Vector u(2);
   u    = 1.0;

   // 4. Perform time-integration (looping over the time iterations, ti, with a
   //    time-step dt).
   ODE oper(a00,a01,a10,a11);
   ode_solver->Init(oper);
   double t = 0.0;

   bool last_step = false;
   ofstream output("output.dat");
   output<<t<<" "<<u[0]<<" "<<u[1]<<endl;
   for (int ti = 1; !last_step; ti++)
   {
      if (t + dt >= t_final - dt/2)
      {
         last_step = true;
      }

      ode_solver->Step(u, t, dt);
      output<<t<<" "<<u[0]<<" "<<u[1]<<endl;
   }
   output.close();

   // 5. Free the used memory.
   delete ode_solver;

   return 0;
}

<commit_msg>Update check-1st-ti.cpp<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
//
//      ----------------------------------------------------------------
//      Check timeintegrator Miniapp:
//      ----------------------------------------------------------------
//
// Compile with: make check-timeintegrator
//
// Sample runs:  check-timeintegrator
//               check-timeintegrator -s 10
#include "mfem.hpp"
#include <fstream>
#include <iostream>

using namespace std;
using namespace mfem;

/** Class for simple linear first order ODE.
 *
 *     du/dt  + a u = 0
 *
 */
class ODE : public TimeDependentOperator
{
protected:
   DenseMatrix A;
public:
   ODE(double a00,double a01,double a10,double a11) : TimeDependentOperator(2, 0.0)
   {
      A.SetSize(2,2);
      A(0,0) = a00;
      A(0,1) = a01;
      A(1,0) = a10;
      A(1,1) = a11;
   };

   virtual void Mult(const Vector &u, Vector &dudt) const;

   virtual void ImplicitSolve(const double dt,const Vector &u, Vector &dudt);

   virtual ~ODE() {};
};

void ODE::Mult(const Vector &u, Vector &dudt)  const
{
   A.Mult(u,dudt);
   dudt.Neg();
}

void ODE::ImplicitSolve(const double dt, const Vector &u, Vector &dudt)
{
   DenseMatrix I(2,2),T(2,2);
   I =  0.0;
   I(0,0) = I(1,1) = 1.0;
   Add(I,A,dt,T);
   T.Invert();

   Vector r(2);
   A.Mult(u,r);
   r.Neg();
   T.Mult(r,dudt);
}

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   int ode_solver_type = 11;
   double t_final = 0.5;
   double dt = 1.0e-2;
   double a00 =  0.0;
   double a01 =  1.0;
   double a10 = -1.0;
   double a11 =  0.0;

   int precision = 8;
   cout.precision(precision);

   OptionsParser args(argc, argv);
   args.AddOption(&ode_solver_type, "-s", "--ode-solver",
                  "ODE solver: 1 - Backward Euler, 2 - SDIRK2, 3 - SDIRK3,\n\t"
                  "\t   11 - Forward Euler, 12 - RK2, 13 - RK3 SSP, 14 - RK4, \n\t"
                  "\t   22 - Midpoint, 23 - SDIRK23, 24 - SDIRK34\n\t"
                  //"\t   70 -- 80 - Generalized alpha"
                 );
   args.AddOption(&t_final, "-tf", "--t-final",
                  "Final time; start time is 0.");
   args.AddOption(&dt, "-dt", "--time-step",
                  "Time step.");
   args.AddOption(&a00, "-a00", "--stiffness00",
                  "Coefficient.");
   args.AddOption(&a01, "-a01", "--stiffness01",
                  "Coefficient.");
   args.AddOption(&a10, "-a10", "--stiffness10",
                  "Coefficient.");
   args.AddOption(&a11, "-a11", "--stiffness11",
                  "Coefficient.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   args.PrintOptions(cout);

   // 2. Define the ODE solver used for time integration. Several implicit
   //    singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
   //    explicit Runge-Kutta methods are available.
   ODESolver *ode_solver;
   switch (ode_solver_type)
   {
      // Implicit L-stable methods
      case 1: ode_solver = new BackwardEulerSolver; break;
      case 2: ode_solver = new SDIRK23Solver(2); break;
      case 3: ode_solver = new SDIRK33Solver; break;
      // Explicit methods
      case 11: ode_solver = new ForwardEulerSolver; break;
      case 12: ode_solver = new RK2Solver(0.5); break; // midpoint method
      case 13: ode_solver = new RK3SSPSolver; break;
      case 14: ode_solver = new RK4Solver; break;
      // Implicit A-stable methods (not L-stable)
      case 22: ode_solver = new ImplicitMidpointSolver; break;
      case 23: ode_solver = new SDIRK23Solver; break;
      case 24: ode_solver = new SDIRK34Solver; break;
      // Generalized-alpha solvers
      //case 70: ode_solver = new GeneralizedAlphaSolver(0.0); break;
      //case 71: ode_solver = new GeneralizedAlphaSolver(0.1); break;
      //case 72: ode_solver = new GeneralizedAlphaSolver(0.2); break;
      //case 73: ode_solver = new GeneralizedAlphaSolver(0.3); break;
      //case 74: ode_solver = new GeneralizedAlphaSolver(0.4); break;
      //case 75: ode_solver = new GeneralizedAlphaSolver(0.5); break;
      //case 76: ode_solver = new GeneralizedAlphaSolver(0.6); break;
      //case 77: ode_solver = new GeneralizedAlphaSolver(0.7); break;
      //case 78: ode_solver = new GeneralizedAlphaSolver(0.8); break;
      //case 79: ode_solver = new GeneralizedAlphaSolver(0.9); break;
      //case 80: ode_solver = new GeneralizedAlphaSolver(1.0); break;
      default:
         cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
         return 3;
   }

   // 3. Set the initial conditions for u.
   Vector u(2);
   u    = 1.0;

   // 4. Perform time-integration (looping over the time iterations, ti, with a
   //    time-step dt).
   ODE oper(a00,a01,a10,a11);
   ode_solver->Init(oper);
   double t = 0.0;

   bool last_step = false;
   ofstream output("output.dat");
   output<<t<<" "<<u[0]<<" "<<u[1]<<endl;
   for (int ti = 1; !last_step; ti++)
   {
      if (t + dt >= t_final - dt/2)
      {
         last_step = true;
      }

      ode_solver->Step(u, t, dt);
      output<<t<<" "<<u[0]<<" "<<u[1]<<endl;
   }
   output.close();

   // 5. Free the used memory.
   delete ode_solver;

   return 0;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Sam Bloomberg

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.
*/

#include <iostream>

#include "ECS.h"

using namespace ECS;

struct Position
{
	Position(float x, float y) : x(x), y(y) {}
	Position() {}

	float x;
	float y;
};

struct Rotation
{
	Rotation(float angle) : angle(angle) {}
	Rotation() {}

	float angle;
};

struct SomeComponent
{
	SomeComponent() {}
};

class TestSystem : public EntitySystem, public EventSubscriber<Events::OnEntityCreated>
{
public:
	virtual ~TestSystem() {}

	virtual void configure(class World* world) override
	{
		world->subscribe<Events::OnEntityCreated>(this);
	}

	virtual void tick(class World* world, float deltaTime) override
	{
		world->each<Position, Rotation>([&](Entity* ent, auto pos, auto rot) {
			pos->x += deltaTime;
			pos->y += deltaTime;
			rot->angle += deltaTime * 2;
		});
	}

	virtual void receive(class World* world, const Events::OnEntityCreated& event) override
	{
		std::cout << "An entity was created!" << std::endl;
	}
};

int main(int argc, char** argv)
{
	std::cout << "EntityComponentSystem Test" << std::endl
		<< "==========================" << std::endl;

	World world;

	world.registerSystem(new TestSystem());

	Entity* ent = world.create();
	auto pos = ent->assign<Position>(0.f, 0.f);
	auto rot = ent->assign<Rotation>(0.f);

	std::cout << "Initial values: position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	world.tick(10.f);

	std::cout << "After tick(10): position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	std::cout << "Creating more entities..." << std::endl;

	for (int i = 0; i < 10; ++i)
	{
		ent = world.create();
		ent->assign<SomeComponent>();
	}

	int count = 0;
	std::cout << "Counting entities with SomeComponent..." << std::endl;
	// range based for loop
	for (auto ent : world.each<SomeComponent>())
	{
		++count;
		std::cout << "Found entity #" << ent->getEntityId() << std::endl;
	}
	std::cout << count << " entities have SomeComponent!" << std::endl;

	std::cout << "Press any key to exit..." << std::endl;
	std::getchar();

	return 0;
}<commit_msg>add unconfigure to sample system<commit_after>/*
Copyright (c) 2016 Sam Bloomberg

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.
*/

#include <iostream>

#include "ECS.h"

using namespace ECS;

struct Position
{
	Position(float x, float y) : x(x), y(y) {}
	Position() {}

	float x;
	float y;
};

struct Rotation
{
	Rotation(float angle) : angle(angle) {}
	Rotation() {}

	float angle;
};

struct SomeComponent
{
	SomeComponent() {}
};

class TestSystem : public EntitySystem, public EventSubscriber<Events::OnEntityCreated>
{
public:
	virtual ~TestSystem() {}

	virtual void configure(class World* world) override
	{
		world->subscribe<Events::OnEntityCreated>(this);
	}

	virtual void unconfigure(class World* world) override
	{
		world->unsubscribeAll(this);
	}

	virtual void tick(class World* world, float deltaTime) override
	{
		world->each<Position, Rotation>([&](Entity* ent, auto pos, auto rot) {
			pos->x += deltaTime;
			pos->y += deltaTime;
			rot->angle += deltaTime * 2;
		});
	}

	virtual void receive(class World* world, const Events::OnEntityCreated& event) override
	{
		std::cout << "An entity was created!" << std::endl;
	}
};

int main(int argc, char** argv)
{
	std::cout << "EntityComponentSystem Test" << std::endl
		<< "==========================" << std::endl;

	World world;

	world.registerSystem(new TestSystem());

	Entity* ent = world.create();
	auto pos = ent->assign<Position>(0.f, 0.f);
	auto rot = ent->assign<Rotation>(0.f);

	std::cout << "Initial values: position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	world.tick(10.f);

	std::cout << "After tick(10): position(" << pos->x << ", " << pos->y << "), rotation(" << rot->angle << ")" << std::endl;

	std::cout << "Creating more entities..." << std::endl;

	for (int i = 0; i < 10; ++i)
	{
		ent = world.create();
		ent->assign<SomeComponent>();
	}

	int count = 0;
	std::cout << "Counting entities with SomeComponent..." << std::endl;
	// range based for loop
	for (auto ent : world.each<SomeComponent>())
	{
		++count;
		std::cout << "Found entity #" << ent->getEntityId() << std::endl;
	}
	std::cout << count << " entities have SomeComponent!" << std::endl;

	std::cout << "Press any key to exit..." << std::endl;
	std::getchar();

	return 0;
}<|endoftext|>


<commit_before>#include "AnimatorHolder.hpp"
using namespace cs454_2006;

std::list<Animator*>
	AnimatorHolder::running,
	AnimatorHolder::suspended,
	AnimatorHolder::x_running;
amc_t const *AnimatorHolder::amc;
AnimatorHolder::_susres AnimatorHolder::susres(running, x_running);

// ProgressFunctor members    -------------
void AnimatorHolder::ProgressFunctor::operator () (Animator *a) const {
	while (a->ShouldProgress(t)) {
		a->Progress(t);
		// make all necessary checks after every move
		if (amc)
			(*amc)(a);
	}
} // operator ()

// Constructor
AnimatorHolder::ProgressFunctor::ProgressFunctor(timestamp_t _t) : t(_t) { }
// End ProgressFunctor members  -------------

// TimeshiftFunctor members     -------------
void AnimatorHolder::TimeshiftFunctor::operator () (Animator *a) const {
	a->TimeShift(t);
} // operator ()
 // Constructor
AnimatorHolder::TimeshiftFunctor::TimeshiftFunctor(timestamp_t _t): t(_t){ }
// End TimeshiftFunctor members -------------

void AnimatorHolder::Register (Animator *a) { suspended.push_back(a); }
void AnimatorHolder::Cancel (Animator *a) { suspended.remove(a); }
void AnimatorHolder::MarkAsRunning (Animator *a)
	{ suspended.remove(a); running.push_back(a); }
void AnimatorHolder::MarkAsSuspended (Animator *a)
	{ running.remove(a); suspended.push_back(a); }
void AnimatorHolder::Progress (timestamp_t currTime) {
    std::for_each(
	running.begin(), running.end(), ProgressFunctor(currTime)
    );
}
void AnimatorHolder::TimeShift (timestamp_t currTime) {
	if (running.size())
		std::for_each(
		 running.begin(),
		 running.end(),
		 TimeshiftFunctor(currTime)
		);
	if (suspended.size())
		std::for_each(
		 suspended.begin(),
		 suspended.end(),
		 TimeshiftFunctor(currTime)
		);
}

amc_t const *AnimatorHolder::getAfterMoveCall(void) { return amc; }

void AnimatorHolder::setAfterMoveCall(amc_t const *_amc) { amc = _amc; }

std::list<Animator*> AnimatorHolder::getRunning(void) {
	return running;
} // getRunning

std::list<Animator*> AnimatorHolder::getSuspended(void) {
	return suspended;
} // getSuspended

void AnimatorHolder::suspendAllRunning(timestamp_t currTime) {
	std::for_each(running.begin(), running.end(),
	 susres[susres.suspend] = currTime);
} // suspendAllRunning

void AnimatorHolder::resumeAllExRunning(timestamp_t currTime) {
	std::for_each(x_running.begin(), x_running.end(),
	 susres[susres.resume] = currTime);
} // resumeAllExRunning

// Suspender/Resumer Implementation ------------------------------------
AnimatorHolder::_susres::_susres(std::list<Animator*> &_r,
 std::list<Animator*> &_x) : r(_r), x(_x) { }

AnimatorHolder::_susres &AnimatorHolder::_susres::operator[](enum mode _m) {
	m = _m;
	return *this;
} // susres[]

AnimatorHolder::_susres &AnimatorHolder::_susres::operator=(timestamp_t T) {
	t = T;
	return *this;
} // susres =

AnimatorHolder::_susres::result_type
AnimatorHolder::_susres::operator()(argument_type animator) {
	switch (m) {
		case suspend :
			x.push_back(animator);
			animator->Suspend(t);
			break;
		case resume :
			x.remove(animator);
			animator->Resume(t);
			break;
	}
} // susres()
// -----------------------------------------------------------------------
<commit_msg>Completed fully functional pause -- except for scheduler<commit_after>#include "AnimatorHolder.hpp"
using namespace cs454_2006;

std::list<Animator*>
	AnimatorHolder::running,
	AnimatorHolder::suspended,
	AnimatorHolder::x_running;
amc_t const *AnimatorHolder::amc;
AnimatorHolder::_susres AnimatorHolder::susres(running, x_running);

// ProgressFunctor members    -------------
void AnimatorHolder::ProgressFunctor::operator () (Animator *a) const {
	while (a->ShouldProgress(t)) {
		a->Progress(t);
		// make all necessary checks after every move
		if (amc)
			(*amc)(a);
	}
} // operator ()

// Constructor
AnimatorHolder::ProgressFunctor::ProgressFunctor(timestamp_t _t) : t(_t) { }
// End ProgressFunctor members  -------------

// TimeshiftFunctor members     -------------
void AnimatorHolder::TimeshiftFunctor::operator () (Animator *a) const {
	a->TimeShift(t);
} // operator ()
 // Constructor
AnimatorHolder::TimeshiftFunctor::TimeshiftFunctor(timestamp_t _t): t(_t){ }
// End TimeshiftFunctor members -------------

void AnimatorHolder::Register (Animator *a) { suspended.push_back(a); }
void AnimatorHolder::Cancel (Animator *a) { suspended.remove(a); }
void AnimatorHolder::MarkAsRunning (Animator *a)
	{ suspended.remove(a); running.push_back(a); }
void AnimatorHolder::MarkAsSuspended (Animator *a)
	{ running.remove(a); suspended.push_back(a); }
void AnimatorHolder::Progress (timestamp_t currTime) {
    std::for_each(
	running.begin(), running.end(), ProgressFunctor(currTime)
    );
}
void AnimatorHolder::TimeShift (timestamp_t currTime) {
	if (running.size())
		std::for_each(
		 running.begin(),
		 running.end(),
		 TimeshiftFunctor(currTime)
		);
	if (suspended.size())
		std::for_each(
		 suspended.begin(),
		 suspended.end(),
		 TimeshiftFunctor(currTime)
		);
}

amc_t const *AnimatorHolder::getAfterMoveCall(void) { return amc; }

void AnimatorHolder::setAfterMoveCall(amc_t const *_amc) { amc = _amc; }

std::list<Animator*> AnimatorHolder::getRunning(void) {
	return running;
} // getRunning

std::list<Animator*> AnimatorHolder::getSuspended(void) {
	return suspended;
} // getSuspended

void AnimatorHolder::suspendAllRunning(timestamp_t currTime) {
	std::list<Animator*> r = running;
	std::for_each(r.begin(), r.end(), susres[susres.suspend] = currTime);
} // suspendAllRunning

void AnimatorHolder::resumeAllExRunning(timestamp_t currTime) {
	std::list<Animator*> x = x_running;
	std::for_each(x.begin(), x.end(), susres[susres.resume] = currTime);
} // resumeAllExRunning

// Suspender/Resumer Implementation ------------------------------------
AnimatorHolder::_susres::_susres(std::list<Animator*> &_r,
 std::list<Animator*> &_x) : r(_r), x(_x) { }

AnimatorHolder::_susres &AnimatorHolder::_susres::operator[](enum mode _m) {
	m = _m;
	return *this;
} // susres[]

AnimatorHolder::_susres &AnimatorHolder::_susres::operator=(timestamp_t T) {
	t = T;
	return *this;
} // susres =

AnimatorHolder::_susres::result_type
AnimatorHolder::_susres::operator()(argument_type animator) {
	switch (m) {
		case suspend :
			x.push_back(animator);
			animator->Suspend(t);
			break;
		case resume :
			x.remove(animator);
			animator->Resume(t);
			break;
	}
} // susres()
// -----------------------------------------------------------------------
<|endoftext|>