<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: RTableConnectionData.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 15:17:02 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#define DBAUI_RTABLECONNECTIONDATA_HXX

#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif

namespace dbaui
{
    const UINT16 CARDINAL_UNDEFINED = 0x0000;
    const UINT16 CARDINAL_ONE_MANY  = 0x0001;
    const UINT16 CARDINAL_MANY_ONE  = 0x0002;
    const UINT16 CARDINAL_ONE_ONE   = 0x0004;

    class OConnectionLineData;
    //==================================================================
    class ORelationTableConnectionData :    public OTableConnectionData
    {
        friend bool operator==(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs);
        friend bool operator!=(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs) { return !(lhs == rhs); }

        ::osl::Mutex    m_aMutex;
        ::rtl::OUString m_sDatabaseName;

        // @see com.sun.star.sdbc.KeyRule
        sal_Int32 m_nUpdateRules;
        sal_Int32 m_nDeleteRules;
        sal_Int32 m_nCardinality;

        BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xTable,EConnectionSide _eEConnectionSide) const;
        BOOL IsSourcePrimKey()  const { return checkPrimaryKey(getReferencingTable()->getTable(),JTCS_FROM);    }
        BOOL IsDestPrimKey()    const { return checkPrimaryKey(getReferencedTable()->getTable(),JTCS_TO);       }

    protected:
        virtual OConnectionLineDataRef CreateLineDataObj();
        virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );

        ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );
    public:
        ORelationTableConnectionData();
        ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );
        ORelationTableConnectionData( const TTableWindowData::value_type& _pReferencingTable,
                                      const TTableWindowData::value_type& _pReferencedTable,
                                      const ::rtl::OUString& rConnName = ::rtl::OUString() );
        virtual ~ORelationTableConnectionData();

        virtual void CopyFrom(const OTableConnectionData& rSource);
        virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }

        inline ::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }

        /** Update create a new relation

            @return true if successful
        */
        virtual BOOL Update();

        void        SetCardinality();
        inline void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }
        inline void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }

        inline sal_Int32    GetUpdateRules() const { return m_nUpdateRules; }
        inline sal_Int32    GetDeleteRules() const { return m_nDeleteRules; }
        inline sal_Int32    GetCardinality() const { return m_nCardinality; }

        BOOL        IsConnectionPossible();
        void        ChangeOrientation();
        BOOL        DropRelation();
    };
}

#endif // DBAUI_RTABLECONNECTIONDATA_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.7.96); FILE MERGED 2008/03/31 13:27:43 rt 1.7.96.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: RTableConnectionData.hxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#define DBAUI_RTABLECONNECTIONDATA_HXX

#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif

namespace dbaui
{
    const UINT16 CARDINAL_UNDEFINED = 0x0000;
    const UINT16 CARDINAL_ONE_MANY  = 0x0001;
    const UINT16 CARDINAL_MANY_ONE  = 0x0002;
    const UINT16 CARDINAL_ONE_ONE   = 0x0004;

    class OConnectionLineData;
    //==================================================================
    class ORelationTableConnectionData :    public OTableConnectionData
    {
        friend bool operator==(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs);
        friend bool operator!=(const ORelationTableConnectionData& lhs, const ORelationTableConnectionData& rhs) { return !(lhs == rhs); }

        ::osl::Mutex    m_aMutex;
        ::rtl::OUString m_sDatabaseName;

        // @see com.sun.star.sdbc.KeyRule
        sal_Int32 m_nUpdateRules;
        sal_Int32 m_nDeleteRules;
        sal_Int32 m_nCardinality;

        BOOL checkPrimaryKey(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xTable,EConnectionSide _eEConnectionSide) const;
        BOOL IsSourcePrimKey()  const { return checkPrimaryKey(getReferencingTable()->getTable(),JTCS_FROM);    }
        BOOL IsDestPrimKey()    const { return checkPrimaryKey(getReferencedTable()->getTable(),JTCS_TO);       }

    protected:
        virtual OConnectionLineDataRef CreateLineDataObj();
        virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData );

        ORelationTableConnectionData& operator=( const ORelationTableConnectionData& rConnData );
    public:
        ORelationTableConnectionData();
        ORelationTableConnectionData( const ORelationTableConnectionData& rConnData );
        ORelationTableConnectionData( const TTableWindowData::value_type& _pReferencingTable,
                                      const TTableWindowData::value_type& _pReferencedTable,
                                      const ::rtl::OUString& rConnName = ::rtl::OUString() );
        virtual ~ORelationTableConnectionData();

        virtual void CopyFrom(const OTableConnectionData& rSource);
        virtual OTableConnectionData* NewInstance() const { return new ORelationTableConnectionData(); }

        inline ::rtl::OUString GetDatabaseName() const { return m_sDatabaseName; }

        /** Update create a new relation

            @return true if successful
        */
        virtual BOOL Update();

        void        SetCardinality();
        inline void SetUpdateRules( sal_Int32 nAttr ){ m_nUpdateRules = nAttr; }
        inline void SetDeleteRules( sal_Int32 nAttr ){ m_nDeleteRules = nAttr; }

        inline sal_Int32    GetUpdateRules() const { return m_nUpdateRules; }
        inline sal_Int32    GetDeleteRules() const { return m_nDeleteRules; }
        inline sal_Int32    GetCardinality() const { return m_nCardinality; }

        BOOL        IsConnectionPossible();
        void        ChangeOrientation();
        BOOL        DropRelation();
    };
}

#endif // DBAUI_RTABLECONNECTIONDATA_HXX

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPlotLine.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkPlotLine.h"

#include "vtkContext2D.h"
#include "vtkPen.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkExecutive.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"

#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkPlotLine, "1.4");

//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotLine);

//-----------------------------------------------------------------------------
vtkPlotLine::vtkPlotLine()
{
  this->Points = 0;
  this->Label = 0;
}

//-----------------------------------------------------------------------------
vtkPlotLine::~vtkPlotLine()
{
  this->SetLabel(NULL);
  if (this->Points)
    {
    this->Points->Delete();
    this->Points = NULL;
    }
}

//-----------------------------------------------------------------------------
bool vtkPlotLine::Paint(vtkContext2D *painter)
{
  // This is where everything should be drawn, or dispatched to other methods.
  vtkDebugMacro(<< "Paint event called in vtkPlotLine.");

  // First check if we have an input
  vtkTable *table = this->Data->GetInput();
  if (!table)
    {
    vtkDebugMacro(<< "Paint event called with no input table set.");
    return false;
    }
  else if(this->GetMTime() > this->BuildTime ||
          table->GetMTime() > this->BuildTime)
    {
    vtkDebugMacro(<< "Paint event called with outdated table cache. Updating.");
    this->UpdateTableCache(table);
    }

  // Now add some decorations for our selected points...
  if (this->Selection)
    {
    vtkDebugMacro(<<"Selection set " << this->Selection->GetNumberOfTuples());
    for (int i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
      {
      painter->GetPen()->SetWidth(this->Width*15.0);
      painter->GetPen()->SetColor(0, 0, 255, 255);
      vtkIdType id = 0;
      this->Selection->GetTupleValue(i, &id);
      if (id < this->Points->GetNumberOfPoints())
        {
        double *point = this->Points->GetPoint(id);
        painter->DrawPoint(point[0], point[1]);
        }
      }
    }
  else
    {
    vtkDebugMacro("No selectionn set.");
    }

  // Now to plot the points
  if (this->Points)
    {
    painter->GetPen()->SetColor(this->Color);
    painter->GetPen()->SetOpacity(this->Color[3]);
    painter->GetPen()->SetWidth(this->Width);
    painter->DrawPoly(this->Points);
    }

  return true;
}

//-----------------------------------------------------------------------------
void vtkPlotLine::GetBounds(double bounds[4])
{
  // Get the x and y arrays (index 0 and 1 respectively)
  vtkTable *table = this->Data->GetInput();
  vtkDataArray *x = this->Data->GetInputArrayToProcess(0, table);
  vtkDataArray *y = this->Data->GetInputArrayToProcess(1, table);

  if (x && y)
    {
    x->GetRange(&bounds[0]);
    y->GetRange(&bounds[2]);
    }
  vtkDebugMacro(<< "Bounds: " << bounds[0] << "\t" << bounds[1] << "\t"
                << bounds[2] << "\t" << bounds[3]);
}

//-----------------------------------------------------------------------------
template<class A, class B>
void CopyToPoints(vtkPoints2D *points, A *a, B *b, int n)
{
  points->SetNumberOfPoints(n);
  for (int i = 0; i < n; ++i)
    {
    points->SetPoint(i, a[i], b[i]);
    }
}

//-----------------------------------------------------------------------------
bool vtkPlotLine::UpdateTableCache(vtkTable *table)
{
  // Get the x and y arrays (index 0 and 1 respectively)
  vtkAbstractArray *x = this->Data->GetInputAbstractArrayToProcess(0, table);
  vtkAbstractArray *y = this->Data->GetInputAbstractArrayToProcess(1, table);
  if (!x)
    {
    vtkErrorMacro(<< "No X column is set (index 0).");
    return false;
    }
  else if (!y)
    {
    vtkErrorMacro(<< "No Y column is set (index 1).");
    return false;
    }
  else if (x->GetSize() != y->GetSize())
    {
    vtkErrorMacro("The x and y columns must have the same number of elements.");
    return false;
    }

  if (!this->Points)
    {
    this->Points = vtkPoints2D::New();
    }

  // Figure out the type and copy to our points
  if (x->IsA("vtkFloatArray") && y->IsA("vtkFloatArray"))
    {
    CopyToPoints(this->Points,
                 vtkFloatArray::SafeDownCast(x)->GetPointer(0),
                 vtkFloatArray::SafeDownCast(y)->GetPointer(0),
                 x->GetSize());
    this->BuildTime.Modified();
    double bounds[4];
    this->GetBounds(&bounds[0]);
    }
  else if (x->IsA("vtkDoubleArray") && y->IsA("vtkDoubleArray"))
    {
    CopyToPoints(this->Points,
                 vtkDoubleArray::SafeDownCast(x)->GetPointer(0),
                 vtkDoubleArray::SafeDownCast(y)->GetPointer(0),
                 x->GetSize());
    this->BuildTime.Modified();
    double bounds[4];
    this->GetBounds(&bounds[0]);
    }
  else
    {
    vtkErrorMacro(<< "Error the x or y array was not a valid type."
                  << endl
                  << x->GetClassName() << "\tT=" << x->GetNumberOfTuples()
                  << "\tC=" << x->GetNumberOfComponents()
                  << endl
                  << y->GetClassName() << "\tT=" << y->GetNumberOfTuples()
                  << "\tC=" << y->GetNumberOfComponents());
    // Give a little more information about them
    vtkErrorMacro(<<"Table: " << table->GetNumberOfColumns())
    }
  return true;
}

//-----------------------------------------------------------------------------
void vtkPlotLine::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<commit_msg>ENH: Improved the UpdateCacheTable function.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPlotLine.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkPlotLine.h"

#include "vtkContext2D.h"
#include "vtkPen.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkExecutive.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"

#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkPlotLine, "1.5");

//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotLine);

//-----------------------------------------------------------------------------
vtkPlotLine::vtkPlotLine()
{
  this->Points = 0;
  this->Label = 0;
}

//-----------------------------------------------------------------------------
vtkPlotLine::~vtkPlotLine()
{
  this->SetLabel(NULL);
  if (this->Points)
    {
    this->Points->Delete();
    this->Points = NULL;
    }
}

//-----------------------------------------------------------------------------
bool vtkPlotLine::Paint(vtkContext2D *painter)
{
  // This is where everything should be drawn, or dispatched to other methods.
  vtkDebugMacro(<< "Paint event called in vtkPlotLine.");

  // First check if we have an input
  vtkTable *table = this->Data->GetInput();
  if (!table)
    {
    vtkDebugMacro(<< "Paint event called with no input table set.");
    return false;
    }
  else if(this->GetMTime() > this->BuildTime ||
          table->GetMTime() > this->BuildTime)
    {
    vtkDebugMacro(<< "Paint event called with outdated table cache. Updating.");
    this->UpdateTableCache(table);
    }

  // Now add some decorations for our selected points...
  if (this->Selection)
    {
    vtkDebugMacro(<<"Selection set " << this->Selection->GetNumberOfTuples());
    for (int i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
      {
      painter->GetPen()->SetWidth(this->Width*15.0);
      painter->GetPen()->SetColor(0, 0, 255, 255);
      vtkIdType id = 0;
      this->Selection->GetTupleValue(i, &id);
      if (id < this->Points->GetNumberOfPoints())
        {
        double *point = this->Points->GetPoint(id);
        painter->DrawPoint(point[0], point[1]);
        }
      }
    }
  else
    {
    vtkDebugMacro("No selectionn set.");
    }

  // Now to plot the points
  if (this->Points)
    {
    painter->GetPen()->SetColor(this->Color);
    painter->GetPen()->SetOpacity(this->Color[3]);
    painter->GetPen()->SetWidth(this->Width);
    painter->DrawPoly(this->Points);
    }

  return true;
}

//-----------------------------------------------------------------------------
void vtkPlotLine::GetBounds(double bounds[4])
{
  // Get the x and y arrays (index 0 and 1 respectively)
  vtkTable *table = this->Data->GetInput();
  vtkDataArray *x = this->Data->GetInputArrayToProcess(0, table);
  vtkDataArray *y = this->Data->GetInputArrayToProcess(1, table);

  if (x && y)
    {
    x->GetRange(&bounds[0]);
    y->GetRange(&bounds[2]);
    }
  vtkDebugMacro(<< "Bounds: " << bounds[0] << "\t" << bounds[1] << "\t"
                << bounds[2] << "\t" << bounds[3]);
}

//-----------------------------------------------------------------------------
namespace {

// Copy the two arrays into the points array
template<class A>
void CopyToPointsSwitch(vtkPoints2D *points, A *a, vtkDataArray *b, int n)
{
  switch(b->GetDataType())
    {
    vtkTemplateMacro(
        CopyToPoints(points, a, static_cast<VTK_TT*>(b->GetVoidPointer(0)), n));
    }
}

// Copy the two arrays into the points array
template<class A, class B>
void CopyToPoints(vtkPoints2D *points, A *a, B *b, int n)
{
  points->SetNumberOfPoints(n);
  for (int i = 0; i < n; ++i)
    {
    points->SetPoint(i, a[i], b[i]);
    }
}

}

//-----------------------------------------------------------------------------
bool vtkPlotLine::UpdateTableCache(vtkTable *table)
{
  // Get the x and y arrays (index 0 and 1 respectively)
  vtkDataArray* x = this->Data->GetInputArrayToProcess(0, table);
  vtkDataArray* y = this->Data->GetInputArrayToProcess(1, table);
  if (!x)
    {
    vtkErrorMacro(<< "No X column is set (index 0).");
    return false;
    }
  else if (!y)
    {
    vtkErrorMacro(<< "No Y column is set (index 1).");
    return false;
    }
  else if (x->GetSize() != y->GetSize())
    {
    vtkErrorMacro("The x and y columns must have the same number of elements.");
    return false;
    }

  if (!this->Points)
    {
    this->Points = vtkPoints2D::New();
    }

  // Now copy the components into their new columns
  switch(x->GetDataType())
    {
      vtkTemplateMacro(
          CopyToPointsSwitch(this->Points,
                             static_cast<VTK_TT*>(x->GetVoidPointer(0)),
                             y, x->GetSize()));
      this->BuildTime.Modified();
      break;
    }
  return true;
}

//-----------------------------------------------------------------------------
void vtkPlotLine::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>


<commit_before>#include <IOKit/hid/IOHIDKeys.h>
#include "CommonData.hpp"
#include "Config.hpp"
#include "EventInputQueue.hpp"
#include "FlagStatus.hpp"
#include "GlobalLock.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace {
    ListHookedKeyboard listHookedKeyboard;
  }
  TimerWrapper ListHookedKeyboard::setcapslock_timer_;

  void
  ListHookedKeyboard::static_initialize(IOWorkLoop& workloop)
  {
    setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setcapslock_timer_callback);
  }

  void
  ListHookedKeyboard::static_terminate(void)
  {
    setcapslock_timer_.terminate();
  }

  ListHookedKeyboard&
  ListHookedKeyboard::instance(void)
  {
    return listHookedKeyboard;
  }

  ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),
    orig_keyboardEventAction_(NULL),
    orig_keyboardEventTarget_(NULL),
    orig_updateEventFlagsAction_(NULL),
    orig_updateEventFlagsTarget_(NULL)
  {}

  ListHookedKeyboard::Item::~Item(void)
  {
    IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n");
    restoreEventAction();
  }

  // ======================================================================
  bool
  ListHookedKeyboard::Item::refresh(void)
  {
    if (! device_) goto restore;

    {
      const char* name = device_->getName();
      if (! name) goto restore;

      if (ListHookedDevice::Item::isConsumer(name)) goto restore;
    }

    // ------------------------------------------------------------
    if (! Config::get_initialized()) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) &&
        deviceType_ != DeviceType::APPLE_INTERNAL &&
        deviceType_ != DeviceType::APPLE_EXTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) &&
        deviceType_ == DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) &&
        deviceType_ != DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&
        isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_non_apple_keyboard) &&
        ! isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }

    // Logitech USB Headset
    if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {
      goto restore;
    }
    // Logitech Cordless Presenter
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&
        isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {
      goto restore;
    }
    // Kensington Virtual Device (0x0, 0x0)
    if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) {
      // Note: USB Overdrive also use 0x0,0x0.
      // We allow to use USB Overdrive.
      if (deviceType_ != DeviceType::USB_OVERDRIVE) {
        goto restore;
      }
    }

#if 0
    // Apple Internal Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {
      goto restore;
    }

    // Apple External Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {
      goto restore;
    }
#endif

    // ------------------------------------------------------------
    return replaceEventAction();

  restore:
    return restoreEventAction();
  }

  bool
  ListHookedKeyboard::Item::replaceEventAction(void)
  {
    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ------------------------------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback != EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_);

        orig_keyboardEventAction_ = callback;
        orig_keyboardEventTarget_ = kbd->_keyboardEventTarget;

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback != EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        orig_updateEventFlagsAction_ = callback;
        orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget;

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback);

        result = true;
      }
    }

    return result;
  }

  bool
  ListHookedKeyboard::Item::restoreEventAction(void)
  {
    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ----------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback == EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_);

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback == EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_);

        result = true;
      }
    }

    orig_keyboardEventAction_ = NULL;
    orig_keyboardEventTarget_ = NULL;
    orig_updateEventFlagsAction_ = NULL;
    orig_updateEventFlagsTarget_ = NULL;

    return result;
  }

  // ======================================================================
  void
  ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
  {
    if (params.key >= KeyCode::VK__BEGIN__) {
      // Invalid keycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get());
      return;
    }
    if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) {
      // Invalid modifierkeycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get());
      return;
    }
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    if (RemapClassManager::remap_dropkeyafterremap(params)) return;

    // ------------------------------------------------------------
    KeyboardEventCallback callback = orig_keyboardEventAction_;
    if (! callback) return;

    OSObject* target = orig_keyboardEventTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    const AbsoluteTime& ts = CommonData::getcurrent_ts();
    OSObject* refcon = NULL;

    Params_KeyboardEventCallBack::log(false, params.eventType, params.flags, params.key, params.keyboardType, params.repeat);
    {
      // We need to unlock the global lock while we are calling the callback function.
      //
      // When Sticky Keys (in Universal Access) is activated,
      // Apple driver calls EventInputQueue::push_* recursively.
      //
      // If we don't unlock the global lock, deadlock is occured.
      GlobalLock::ScopedUnlock lk;
      callback(target, params.eventType.get(), params.flags.get(), params.key.get(),
               params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(),
               params.keyboardType.get(), params.repeat, ts, sender, refcon);
    }

    // The CapsLock LED is not designed to turn it on/off frequently.
    // So, we have to use the timer to call a setAlphaLock function at appropriate frequency.
    enum {
      CAPSLOCK_LED_DELAY_MS = 5,
    };
    setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false);
  }

  void
  ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params)
  {
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_;
    if (! callback) return;

    OSObject* target = orig_updateEventFlagsTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    OSObject* refcon = NULL;

    Params_UpdateEventFlagsCallback::log(false, params.flags);
    {
      // We need to unlock the global lock while we are calling the callback function.
      // For more information, See ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
      GlobalLock::ScopedUnlock lk;
      callback(target, params.flags.get(), sender, refcon);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params)
  {
    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params)
  {
    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::setcapslock_timer_callback(OSObject* owner, IOTimerEventSource* sender)
  {
    ListHookedKeyboard& self = ListHookedKeyboard::instance();

    if (! self.list_) return;

    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return;

    Flags flags = FlagStatus::makeFlags();

    for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) {
      if (! p->isReplaced()) continue;

      IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get());
      if (! kbd) continue;

      // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock.
      if (flags.isOn(ModifierFlag::CAPSLOCK)) {
        if (! kbd->alphaLock()) {
          kbd->setAlphaLock(true);
        }
      } else {
        if (kbd->alphaLock()) {
          kbd->setAlphaLock(false);
        }
      }

      if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) {
        // Set CapsLock LED always.
        // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. ***
        enum {
          CAPSLOCK_LED_MASK = 0x2,
        };
        bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK);
        if (! isLED) {
          kbd->setAlphaLockFeedback(true);
        }
      }
    }
  }
}
<commit_msg>unlock GlobalLock before we call kbd->alphaLock<commit_after>#include <IOKit/hid/IOHIDKeys.h>
#include "CommonData.hpp"
#include "Config.hpp"
#include "EventInputQueue.hpp"
#include "FlagStatus.hpp"
#include "GlobalLock.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace {
    ListHookedKeyboard listHookedKeyboard;
  }
  TimerWrapper ListHookedKeyboard::setcapslock_timer_;

  void
  ListHookedKeyboard::static_initialize(IOWorkLoop& workloop)
  {
    setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setcapslock_timer_callback);
  }

  void
  ListHookedKeyboard::static_terminate(void)
  {
    setcapslock_timer_.terminate();
  }

  ListHookedKeyboard&
  ListHookedKeyboard::instance(void)
  {
    return listHookedKeyboard;
  }

  ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),
    orig_keyboardEventAction_(NULL),
    orig_keyboardEventTarget_(NULL),
    orig_updateEventFlagsAction_(NULL),
    orig_updateEventFlagsTarget_(NULL)
  {}

  ListHookedKeyboard::Item::~Item(void)
  {
    IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n");
    restoreEventAction();
  }

  // ======================================================================
  bool
  ListHookedKeyboard::Item::refresh(void)
  {
    if (! device_) goto restore;

    {
      const char* name = device_->getName();
      if (! name) goto restore;

      if (ListHookedDevice::Item::isConsumer(name)) goto restore;
    }

    // ------------------------------------------------------------
    if (! Config::get_initialized()) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) &&
        deviceType_ != DeviceType::APPLE_INTERNAL &&
        deviceType_ != DeviceType::APPLE_EXTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) &&
        deviceType_ == DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) &&
        deviceType_ != DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&
        isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_non_apple_keyboard) &&
        ! isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }

    // Logitech USB Headset
    if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {
      goto restore;
    }
    // Logitech Cordless Presenter
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&
        isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {
      goto restore;
    }
    // Kensington Virtual Device (0x0, 0x0)
    if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) {
      // Note: USB Overdrive also use 0x0,0x0.
      // We allow to use USB Overdrive.
      if (deviceType_ != DeviceType::USB_OVERDRIVE) {
        goto restore;
      }
    }

#if 0
    // Apple Internal Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {
      goto restore;
    }

    // Apple External Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {
      goto restore;
    }
#endif

    // ------------------------------------------------------------
    return replaceEventAction();

  restore:
    return restoreEventAction();
  }

  bool
  ListHookedKeyboard::Item::replaceEventAction(void)
  {
    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ------------------------------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback != EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_);

        orig_keyboardEventAction_ = callback;
        orig_keyboardEventTarget_ = kbd->_keyboardEventTarget;

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback != EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        orig_updateEventFlagsAction_ = callback;
        orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget;

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback);

        result = true;
      }
    }

    return result;
  }

  bool
  ListHookedKeyboard::Item::restoreEventAction(void)
  {
    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ----------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback == EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_);

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback == EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_);

        result = true;
      }
    }

    orig_keyboardEventAction_ = NULL;
    orig_keyboardEventTarget_ = NULL;
    orig_updateEventFlagsAction_ = NULL;
    orig_updateEventFlagsTarget_ = NULL;

    return result;
  }

  // ======================================================================
  void
  ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
  {
    if (params.key >= KeyCode::VK__BEGIN__) {
      // Invalid keycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get());
      return;
    }
    if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) {
      // Invalid modifierkeycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get());
      return;
    }
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    if (RemapClassManager::remap_dropkeyafterremap(params)) return;

    // ------------------------------------------------------------
    KeyboardEventCallback callback = orig_keyboardEventAction_;
    if (! callback) return;

    OSObject* target = orig_keyboardEventTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    const AbsoluteTime& ts = CommonData::getcurrent_ts();
    OSObject* refcon = NULL;

    Params_KeyboardEventCallBack::log(false, params.eventType, params.flags, params.key, params.keyboardType, params.repeat);
    {
      // We need to unlock the global lock while we are calling the callback function.
      //
      // When Sticky Keys (in Universal Access) is activated,
      // Apple driver calls EventInputQueue::push_* recursively.
      //
      // If we don't unlock the global lock, deadlock is occured.
      GlobalLock::ScopedUnlock lk;
      callback(target, params.eventType.get(), params.flags.get(), params.key.get(),
               params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(),
               params.keyboardType.get(), params.repeat, ts, sender, refcon);
    }

    // The CapsLock LED is not designed to turn it on/off frequently.
    // So, we have to use the timer to call a setAlphaLock function at appropriate frequency.
    enum {
      CAPSLOCK_LED_DELAY_MS = 5,
    };
    setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false);
  }

  void
  ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params)
  {
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_;
    if (! callback) return;

    OSObject* target = orig_updateEventFlagsTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    OSObject* refcon = NULL;

    Params_UpdateEventFlagsCallback::log(false, params.flags);
    {
      // We need to unlock the global lock while we are calling the callback function.
      // For more information, See ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
      GlobalLock::ScopedUnlock lk;
      callback(target, params.flags.get(), sender, refcon);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params)
  {
    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params)
  {
    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::setcapslock_timer_callback(OSObject* owner, IOTimerEventSource* sender)
  {
    ListHookedKeyboard& self = ListHookedKeyboard::instance();

    if (! self.list_) return;

    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return;

    Flags flags = FlagStatus::makeFlags();

    for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) {
      if (! p->isReplaced()) continue;

      IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get());
      if (! kbd) continue;

      {
        GlobalLock::ScopedUnlock lk;

        // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock.
        if (flags.isOn(ModifierFlag::CAPSLOCK)) {
          if (! kbd->alphaLock()) {
            kbd->setAlphaLock(true);
          }
        } else {
          if (kbd->alphaLock()) {
            kbd->setAlphaLock(false);
          }
        }

        if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) {
          // Set CapsLock LED always.
          // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. ***
          enum {
            CAPSLOCK_LED_MASK = 0x2,
          };
          bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK);
          if (! isLED) {
            kbd->setAlphaLockFeedback(true);
          }
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>#include "UnitTest++/UnitTest++.h"

#include "pugixml.hpp"

#include "angular_quadrature.hpp"
#include "boundary_condition.hpp"

using namespace mocc;
using std::cout;
using std::endl;

// This is a fixture that provides an in and out boundary condition that look a
// lot like you would expect for an MoC sweeper. there are only boundary values
// on the X and Y normal faces, and a different number on each, depending on
// angle
class BCIrregularFixture {
    public:
        BCIrregularFixture():
            angquad(make_angquad()),
            nang(angquad.ndir()/2),
            ngroup(2),
            nbc(
                    {
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0}
                    }),
            bc_(
                {
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT
                }),
            in(2, angquad, bc_, nbc),
            out(1, angquad, bc_, nbc)
        {
            return;
        }

    // Data
    public:
        AngularQuadrature angquad;
        int nang;
        int ngroup;
        std::vector< BC_Size_t > nbc;
    private:
        BC_Type_t bc_;
    public:
        BoundaryCondition in;
        BoundaryCondition out;

    private:
        AngularQuadrature make_angquad() {
            std::string angquad_xml = "<ang_quad type=\"ls\" order=\"4\" />";
            pugi::xml_document angquad_node;
            angquad_node.load_string(angquad_xml.c_str());
            return AngularQuadrature(angquad_node.child("ang_quad"));
        }

        // Data

};

TEST_FIXTURE( BCIrregularFixture, test_bc )
{
    CHECK_EQUAL( 192, in.size() );

    in.initialize_scalar( 7.345 );
    for( int ig=0; ig<ngroup; ig++ ) {
        for( int ia=0; ia<nang; ia++ ) {
            auto face = in.get_face( ig, ia, Normal::X_NORM );
            CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
            for( int ibc=0; ibc<8; ibc++ ) {
                CHECK_EQUAL( 7.345, face.second[ibc] );
            }
        }
    }

    ArrayB1 spectrum(2);
    spectrum(0) = 2.2222;
    spectrum(1) = 4.4444;
    in.initialize_spectrum( spectrum );
    for( int ia=0; ia<nang; ia++ ) {
        auto face = in.get_face( 0, ia, Normal::X_NORM );
        CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
        for( int ibc=0; ibc<8; ibc++ ) {
            CHECK_EQUAL( 2.2222, face.second[ibc] );
        }
    }
    for( int ia=0; ia<nang; ia++ ) {
        auto face = in.get_face( 1, ia, Normal::X_NORM );
        CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
        for( int ibc=0; ibc<8; ibc++ ) {
            CHECK_EQUAL( 4.4444, face.second[ibc] );
        }
    }

    out.initialize_scalar(0.0);

    auto outface = out.get_face(0, 0, Normal::X_NORM);
    for( int i=0; i<nbc[0][(int)Normal::X_NORM]; i++ ) {
        outface.second[i] = 3.3333;
    }

    in.update(0, out);

    int iang_refl = angquad.reflect(0, Normal::X_NORM);
    auto inface = in.get_face(0, iang_refl, Normal::X_NORM);
    for( int ibc=0; ibc<5; ibc++ ) {
        CHECK_EQUAL(3.3333, inface.second[ibc]);
    }
    for( int ibc=5; ibc<8; ibc++ ) {
        CHECK_EQUAL(0.0, inface.second[ibc]);
    }
}

int main(int, const char*[]) {
    return UnitTest::RunAllTests();
}
<commit_msg>Add some things to BC test<commit_after>#include "UnitTest++/UnitTest++.h"

#include "pugixml.hpp"

#include "angular_quadrature.hpp"
#include "boundary_condition.hpp"

using namespace mocc;
using std::cout;
using std::endl;

// This is a fixture that provides an in and out boundary condition that look a
// lot like you would expect for an MoC sweeper. there are only boundary values
// on the X and Y normal faces, and a different number on each, depending on
// angle
class BCIrregularFixture {
    public:
        BCIrregularFixture():
            angquad(make_angquad()),
            nang(angquad.ndir()/2),
            ngroup(2),
            nbc(
                    {
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0},
                        {5, 3, 0},
                        {4, 4, 0},
                        {3, 5, 0}
                    }),
            bc_(
                {
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT,
                    Boundary::REFLECT
                }),
            in(2, angquad, bc_, nbc),
            out(1, angquad, bc_, nbc)
        {
            return;
        }

    // Data
    public:
        AngularQuadrature angquad;
        int nang;
        int ngroup;
        std::vector< BC_Size_t > nbc;
    private:
        BC_Type_t bc_;
    public:
        BoundaryCondition in;
        BoundaryCondition out;

    private:
        AngularQuadrature make_angquad() {
            std::string angquad_xml = "<ang_quad type=\"ls\" order=\"4\" />";
            pugi::xml_document angquad_node;
            angquad_node.load_string(angquad_xml.c_str());
            return AngularQuadrature(angquad_node.child("ang_quad"));
        }
};

TEST_FIXTURE( BCIrregularFixture, test_bc )
{
    CHECK_EQUAL( 192, in.size() );

    in.initialize_scalar( 7.345 );
    for( int ig=0; ig<ngroup; ig++ ) {
        for( int ia=0; ia<nang; ia++ ) {
            auto face = in.get_face( ig, ia, Normal::X_NORM );
            CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
            for( int ibc=0; ibc<8; ibc++ ) {
                CHECK_EQUAL( 7.345, face.second[ibc] );
            }
        }
    }

    ArrayB1 spectrum(2);
    spectrum(0) = 2.2222;
    spectrum(1) = 4.4444;
    in.initialize_spectrum( spectrum );
    for( int ia=0; ia<nang; ia++ ) {
        auto face = in.get_face( 0, ia, Normal::X_NORM );
        CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
        for( int ibc=0; ibc<8; ibc++ ) {
            CHECK_EQUAL( 2.2222, face.second[ibc] );
        }
    }
    for( int ia=0; ia<nang; ia++ ) {
        auto face = in.get_face( 1, ia, Normal::X_NORM );
        CHECK_EQUAL(nbc[ia][(int)Normal::X_NORM], face.first);
        for( int ibc=0; ibc<8; ibc++ ) {
            CHECK_EQUAL( 4.4444, face.second[ibc] );
        }
    }

    out.initialize_scalar(0.0);

    auto outface = out.get_face(0, 0, Normal::X_NORM);
    for( int i=0; i<nbc[0][(int)Normal::X_NORM]; i++ ) {
        outface.second[i] = 3.3333;
    }

    in.update(0, out);

    int iang_refl = angquad.reflect(0, Normal::X_NORM);
    auto inface = in.get_face(0, iang_refl, Normal::X_NORM);
    for( int ibc=0; ibc<5; ibc++ ) {
        CHECK_EQUAL(3.3333, inface.second[ibc]);
    }
    for( int ibc=5; ibc<8; ibc++ ) {
        CHECK_EQUAL(0.0, inface.second[ibc]);
    }

    std::cout << in << std::endl;

}

int main() {
    return UnitTest::RunAllTests();
}
<|endoftext|>


<commit_before>#include <cppunit/Portability.h>

#if defined(CPPUNIT_HAVE_UNIX_DLL_LOADER)
#include <cppunit/plugin/DynamicLibraryManager.h>

#include <dlfcn.h>
#include <unistd.h>

namespace CppUnit
{

DynamicLibraryManager::LibraryHandle
DynamicLibraryManager::doLoadLibrary( const std::string &libraryName )
{
  return ::dlopen( libraryName.c_str(), DLOPEN_MODE );
}

void
DynamicLibraryManager::doReleaseLibrary()
{
  ::dlclose( m_libraryHandle);
}

DynamicLibraryManager::Symbol
DynamicLibraryManager::doFindSymbol( const std::string &symbol )
{
  return ::dlsym ( m_libraryHandle, symbol.c_str() );
}

} //  namespace CppUnit

#endif // defined(CPPUNIT_HAVE_UNIX_DLL_LOADER)
<commit_msg>* fixed flag for dlopen<commit_after>#include <cppunit/Portability.h>

#if defined(CPPUNIT_HAVE_UNIX_DLL_LOADER)
#include <cppunit/plugin/DynamicLibraryManager.h>

#include <dlfcn.h>
#include <unistd.h>

namespace CppUnit
{

DynamicLibraryManager::LibraryHandle
DynamicLibraryManager::doLoadLibrary( const std::string &libraryName )
{
  return ::dlopen( libraryName.c_str(), RTLD_NOW );   // RTLD_LAZY ?
}

void
DynamicLibraryManager::doReleaseLibrary()
{
  ::dlclose( m_libraryHandle);
}

DynamicLibraryManager::Symbol
DynamicLibraryManager::doFindSymbol( const std::string &symbol )
{
  return ::dlsym ( m_libraryHandle, symbol.c_str() );
}

} //  namespace CppUnit

#endif // defined(CPPUNIT_HAVE_UNIX_DLL_LOADER)
<|endoftext|>


<commit_before>/// HEADER
#include <csapex/scheduling/thread_pool.h>

/// COMPONENT
#include <csapex/utility/yaml_io.hpp>
#include <csapex/utility/thread.h>
#include <csapex/scheduling/thread_group.h>
#include <csapex/scheduling/task.h>
#include <csapex/scheduling/task_generator.h>

/// SYSTEM
#include <set>
#include <unordered_map>

using namespace csapex;

ThreadPool::ThreadPool(bool enable_threading, bool grouping, bool paused)
    : enable_threading_(enable_threading), grouping_(grouping)
{
    default_group_ = std::make_shared<ThreadGroup>(ThreadGroup::DEFAULT_GROUP_ID, "default", paused);
}

void ThreadPool::stop()
{
    for(auto g : groups_) {
        g->stop();
    }
}

void ThreadPool::clear()
{
    bool p = isPaused();
    setPause(true);
    for(auto g : groups_) {
        g->clear();
    }
    setPause(p);
}

void ThreadPool::pauseChanged(bool pause)
{
    for(auto g : groups_) {
        g->setPause(pause);
    }
}

void ThreadPool::add(TaskGenerator *schedulable)
{
    if(enable_threading_) {
        if(!grouping_) {
            usePrivateThreadFor(schedulable);
        } else {
            // if we use grouping -> wait for structure change
            useDefaultThreadFor(schedulable);
        }
    } else {
        // this is the one thread to use when threading is disabled
        // we need this to make the ui responsive
        useDefaultThreadFor(schedulable);
    }
}

void ThreadPool::remove(TaskGenerator *task)
{
    task->detach();
    group_assignment_.erase(task);
}

std::vector<ThreadGroupPtr> ThreadPool::getGroups()
{
    return groups_;
}

ThreadGroup *ThreadPool::getGroup(int id)
{
    for(auto group : groups_) {
        if(group->id() == id) {
            return group.get();
        }
    }

    throw std::runtime_error("group doesn't exist");
}

ThreadGroup* ThreadPool::getGroupFor(TaskGenerator* generator)
{
    auto pos = group_assignment_.find(generator);
    if(pos == group_assignment_.end()) {
        throw std::runtime_error("group doesn't exist");
    } else {
        return pos->second;
    }
}

void ThreadPool::assignGeneratorToGroup(TaskGenerator *task, ThreadGroup *group)
{
    if(!isInGroup(task, group->id())) {
        auto pos = group_assignment_.find(task);
        if(pos != group_assignment_.end()) {
            group_assignment_.erase(pos);
        }

        task->detach();
        task->assignToScheduler(group);
        group_assignment_[task] = group;
    }
}

bool ThreadPool::isInPrivateThread(TaskGenerator *task) const
{
    return isInGroup(task, ThreadGroup::PRIVATE_THREAD);
}

bool ThreadPool::isInGroup(TaskGenerator *task, int id) const
{
    auto pos = group_assignment_.find(task);
    if(pos != group_assignment_.end()) {
        return pos->second->id() == id;
    }
    return false;
}

void ThreadPool::usePrivateThreadFor(TaskGenerator *task)
{
    if(!isInPrivateThread(task)) {
        auto group = std::make_shared<ThreadGroup>(ThreadGroup::PRIVATE_THREAD, task->getUUID().getShortName(), isPaused());
        groups_.push_back(group);

        assignGeneratorToGroup(task, group.get());
    }
}

void ThreadPool::useDefaultThreadFor(TaskGenerator *task)
{
    assignGeneratorToGroup(task, default_group_.get());
}

void ThreadPool::addToGroup(TaskGenerator *task, int group_id)
{
    if(group_id == ThreadGroup::PRIVATE_THREAD) {
        usePrivateThreadFor(task);

    } else if(group_id == ThreadGroup::DEFAULT_GROUP_ID) {
        useDefaultThreadFor(task);

    } else if(group_id >= ThreadGroup::MINIMUM_THREAD_ID) {
        for(auto g : groups_) {
            if(g->id() == group_id) {
                assignGeneratorToGroup(task, g.get());
                return;
            }
        }
    }
}

int ThreadPool::createNewGroupFor(TaskGenerator* task, const std::string &name)
{
    for(auto group : groups_) {
        if(group->name() == name) {
            assignGeneratorToGroup(task, group.get());
            return group->id();
        }
    }

    ThreadGroupPtr group = std::make_shared<ThreadGroup>(name, isPaused());
    groups_.push_back(group);

    assignGeneratorToGroup(task, group.get());

    return group->id();
}

//void ThreadPool::clearGroup(ThreadGroup* g)
//{
//    for(auto it = groups_.begin(); it != groups_.end(); ++it) {
//        auto group = *it;
//        if(group.get() == g) {
//            if(group->isEmpty()) {
//                group->stop();
////                groups_.erase(it);
//            }
//            return;
//        }
//    }
//    throw std::runtime_error("attempted to delete non-existing thread group");
//}

std::string ThreadPool::nextName()
{
    std::stringstream name;
    name << "Thread " << ThreadGroup::nextId();
    return name.str();
}

void ThreadPool::saveSettings(YAML::Node& node)
{
    YAML::Node threads(YAML::NodeType::Map);

    YAML::Node groups;
    for(std::size_t i = 0, total =  groups_.size(); i < total; ++i) {
        YAML::Node group;
        group["id"] =  groups_[i]->id();
        group["name"] =  groups_[i]->name();
        groups.push_back(group);
    }
    threads["groups"] = groups;

    YAML::Node assignments;
    for(std::map<TaskGenerator*, ThreadGroup*>::const_iterator it = group_assignment_.begin();
        it != group_assignment_.end(); ++it)
    {
        YAML::Node assignment;
        assignment["uuid"] = it->first->getUUID();
        assignment["id"] = it->second->id();
        assignments.push_back(assignment);
    }
    threads["assignments"] = assignments;

    node["threads"] = threads;
}

void ThreadPool::loadSettings(YAML::Node& node)
{
    const YAML::Node& threads = node["threads"];
    if(threads.IsDefined()) {
        const YAML::Node& groups = threads["groups"];
        if(groups.IsDefined()) {
            for(std::size_t i = 0, total = groups.size(); i < total; ++i) {
                const YAML::Node& group = groups[i];

                int group_id = group["id"].as<int>();

                if(group_id >= ThreadGroup::MINIMUM_THREAD_ID) {
                    std::string group_name = group["name"].as<std::string>();
                    groups_.emplace_back(std::make_shared<ThreadGroup>(group_id, group_name, isPaused()));
                }
            }
        }

        std::unordered_map<UUID, int, UUID::Hasher> assignment_map;

        const YAML::Node& assignments = threads["assignments"];
        if(assignments.IsDefined()) {
            for(std::size_t i = 0, total = assignments.size(); i < total; ++i) {
                const YAML::Node& assignment = assignments[i];

                UUID uuid = assignment["uuid"].as<UUID>();
                int id = assignment["id"].as<int>();

                assignment_map[uuid] = id;
            }
        }

        for(auto it = group_assignment_.begin(); it != group_assignment_.end(); ++it) {
            TaskGenerator* task = it->first;
            if(assignment_map.find(task->getUUID()) != assignment_map.end()) {
                int id = assignment_map[task->getUUID()];
                addToGroup(task, id);
            }
        }
    }
}
<commit_msg>bugfix for deserializing thread assignments<commit_after>/// HEADER
#include <csapex/scheduling/thread_pool.h>

/// COMPONENT
#include <csapex/utility/yaml_io.hpp>
#include <csapex/utility/thread.h>
#include <csapex/scheduling/thread_group.h>
#include <csapex/scheduling/task.h>
#include <csapex/scheduling/task_generator.h>

/// SYSTEM
#include <set>
#include <unordered_map>

using namespace csapex;

ThreadPool::ThreadPool(bool enable_threading, bool grouping, bool paused)
    : enable_threading_(enable_threading), grouping_(grouping)
{
    default_group_ = std::make_shared<ThreadGroup>(ThreadGroup::DEFAULT_GROUP_ID, "default", paused);
}

void ThreadPool::stop()
{
    for(auto g : groups_) {
        g->stop();
    }
}

void ThreadPool::clear()
{
    bool p = isPaused();
    setPause(true);
    for(auto g : groups_) {
        g->clear();
    }
    setPause(p);
}

void ThreadPool::pauseChanged(bool pause)
{
    for(auto g : groups_) {
        g->setPause(pause);
    }
}

void ThreadPool::add(TaskGenerator *schedulable)
{
    if(enable_threading_) {
        if(!grouping_) {
            usePrivateThreadFor(schedulable);
        } else {
            // if we use grouping -> wait for structure change
            useDefaultThreadFor(schedulable);
        }
    } else {
        // this is the one thread to use when threading is disabled
        // we need this to make the ui responsive
        useDefaultThreadFor(schedulable);
    }
}

void ThreadPool::remove(TaskGenerator *task)
{
    task->detach();
    group_assignment_.erase(task);
}

std::vector<ThreadGroupPtr> ThreadPool::getGroups()
{
    return groups_;
}

ThreadGroup *ThreadPool::getGroup(int id)
{
    for(auto group : groups_) {
        if(group->id() == id) {
            return group.get();
        }
    }

    throw std::runtime_error("group doesn't exist");
}

ThreadGroup* ThreadPool::getGroupFor(TaskGenerator* generator)
{
    auto pos = group_assignment_.find(generator);
    if(pos == group_assignment_.end()) {
        throw std::runtime_error("group doesn't exist");
    } else {
        return pos->second;
    }
}

void ThreadPool::assignGeneratorToGroup(TaskGenerator *task, ThreadGroup *group)
{
    if(!isInGroup(task, group->id())) {
        auto pos = group_assignment_.find(task);
        if(pos != group_assignment_.end()) {
            group_assignment_.erase(pos);
        }

        task->detach();
        task->assignToScheduler(group);
        group_assignment_[task] = group;
    }
}

bool ThreadPool::isInPrivateThread(TaskGenerator *task) const
{
    return isInGroup(task, ThreadGroup::PRIVATE_THREAD);
}

bool ThreadPool::isInGroup(TaskGenerator *task, int id) const
{
    auto pos = group_assignment_.find(task);
    if(pos != group_assignment_.end()) {
        return pos->second->id() == id;
    }
    return false;
}

void ThreadPool::usePrivateThreadFor(TaskGenerator *task)
{
    if(!isInPrivateThread(task)) {
        auto group = std::make_shared<ThreadGroup>(ThreadGroup::PRIVATE_THREAD, task->getUUID().getShortName(), isPaused());
        groups_.push_back(group);

        assignGeneratorToGroup(task, group.get());
    }
}

void ThreadPool::useDefaultThreadFor(TaskGenerator *task)
{
    assignGeneratorToGroup(task, default_group_.get());
}

void ThreadPool::addToGroup(TaskGenerator *task, int group_id)
{
    if(group_id == ThreadGroup::PRIVATE_THREAD) {
        usePrivateThreadFor(task);

    } else if(group_id == ThreadGroup::DEFAULT_GROUP_ID) {
        useDefaultThreadFor(task);

    } else if(group_id >= ThreadGroup::MINIMUM_THREAD_ID) {
        for(auto g : groups_) {
            if(g->id() == group_id) {
                assignGeneratorToGroup(task, g.get());
                return;
            }
        }
    }
}

int ThreadPool::createNewGroupFor(TaskGenerator* task, const std::string &name)
{
    for(auto group : groups_) {
        if(group->name() == name) {
            assignGeneratorToGroup(task, group.get());
            return group->id();
        }
    }

    ThreadGroupPtr group = std::make_shared<ThreadGroup>(name, isPaused());
    groups_.push_back(group);

    assignGeneratorToGroup(task, group.get());

    return group->id();
}

//void ThreadPool::clearGroup(ThreadGroup* g)
//{
//    for(auto it = groups_.begin(); it != groups_.end(); ++it) {
//        auto group = *it;
//        if(group.get() == g) {
//            if(group->isEmpty()) {
//                group->stop();
////                groups_.erase(it);
//            }
//            return;
//        }
//    }
//    throw std::runtime_error("attempted to delete non-existing thread group");
//}

std::string ThreadPool::nextName()
{
    std::stringstream name;
    name << "Thread " << ThreadGroup::nextId();
    return name.str();
}

void ThreadPool::saveSettings(YAML::Node& node)
{
    YAML::Node threads(YAML::NodeType::Map);

    YAML::Node groups;
    for(std::size_t i = 0, total =  groups_.size(); i < total; ++i) {
        YAML::Node group;
        group["id"] =  groups_[i]->id();
        group["name"] =  groups_[i]->name();
        groups.push_back(group);
    }
    threads["groups"] = groups;

    YAML::Node assignments;
    for(std::map<TaskGenerator*, ThreadGroup*>::const_iterator it = group_assignment_.begin();
        it != group_assignment_.end(); ++it)
    {
        YAML::Node assignment;
        assignment["uuid"] = it->first->getUUID();
        assignment["id"] = it->second->id();
        assignments.push_back(assignment);
    }
    threads["assignments"] = assignments;

    node["threads"] = threads;
}

void ThreadPool::loadSettings(YAML::Node& node)
{
    const YAML::Node& threads = node["threads"];
    if(threads.IsDefined()) {
        const YAML::Node& groups = threads["groups"];
        if(groups.IsDefined()) {
            for(std::size_t i = 0, total = groups.size(); i < total; ++i) {
                const YAML::Node& group = groups[i];

                int group_id = group["id"].as<int>();

                if(group_id >= ThreadGroup::MINIMUM_THREAD_ID) {
                    std::string group_name = group["name"].as<std::string>();
                    groups_.emplace_back(std::make_shared<ThreadGroup>(group_id, group_name, isPaused()));
                }
            }
        }

        std::unordered_map<UUID, int, UUID::Hasher> assignment_map;

        const YAML::Node& assignments = threads["assignments"];
        if(assignments.IsDefined()) {
            for(std::size_t i = 0, total = assignments.size(); i < total; ++i) {
                const YAML::Node& assignment = assignments[i];

                UUID uuid = assignment["uuid"].as<UUID>();
                int id = assignment["id"].as<int>();

                assignment_map[uuid] = id;
            }
        }

        std::vector<TaskGenerator*> tasks;
        for(auto it = group_assignment_.begin(); it != group_assignment_.end(); ++it) {
            tasks.push_back(it->first);
        }
        for(TaskGenerator* task : tasks) {
            if(assignment_map.find(task->getUUID()) != assignment_map.end()) {
                int id = assignment_map[task->getUUID()];
                addToGroup(task, id);
            }
        }
    }
}
<|endoftext|>


<commit_before>#include "TextureLayerDefinition.h"

#include <algorithm>
#include "Zone.h"
#include "SurfaceMaterial.h"
#include "PackStream.h"
#include "Scenery.h"
#include "TerrainDefinition.h"
#include "Color.h"
#include "FractalNoise.h"
#include "NoiseNode.h"

TextureLayerDefinition::TextureLayerDefinition(DefinitionNode *parent, const string &name)
    : DefinitionNode(parent, name, "texturelayer") {
    terrain_zone = new Zone;
    material = new SurfaceMaterial;

    displacement_noise = new NoiseNode(this, "displacement");
    displacement_noise->setConfig(0.0);

    detail_noise = new NoiseNode(this, "detail");
    detail_noise->setConfig(0.01);
}

TextureLayerDefinition::~TextureLayerDefinition() {
    delete terrain_zone;
    delete material;
}

void TextureLayerDefinition::validate() {
    DefinitionNode::validate();

    material->validate();

    // Update zone height range
    if (auto scenery = getScenery()) {
        TerrainDefinition *terrain = scenery->getTerrain();
        HeightInfo height_info = terrain->getHeightInfo();
        terrain_zone->setRelativeHeight(height_info.min_height, height_info.base_height, height_info.max_height);
    }
}

void TextureLayerDefinition::copy(DefinitionNode *destination) const {
    DefinitionNode::copy(destination);

    if (auto tex_destination = static_cast<TextureLayerDefinition *>(destination)) {
        terrain_zone->copy(tex_destination->terrain_zone);

        *tex_destination->material = *material;
    }
}

void TextureLayerDefinition::save(PackStream *stream) const {
    DefinitionNode::save(stream);

    terrain_zone->save(stream);
    material->save(stream);
}

void TextureLayerDefinition::load(PackStream *stream) {
    DefinitionNode::load(stream);

    terrain_zone->load(stream);
    material->load(stream);
}

void TextureLayerDefinition::applyPreset(TextureLayerPreset preset, RandomGenerator &random) {
    displacement_noise->randomize(random);
    detail_noise->randomize(random);

    terrain_zone->clear();

    switch (preset) {
    case TEXTURES_LAYER_PRESET_MUD:
        displacement_noise->setConfig(0.05, 0.1, 0.3);
        detail_noise->setConfig(0.01, 0.03);
        material->setColor(0.015, 0.014, 0.014, 1.0);
        material->reflection = 0.003;
        material->shininess = 4.0;
        break;
    case TEXTURES_LAYER_PRESET_ROCK:
        terrain_zone->addHeightRangeQuick(1.0, 0.6, 0.7, 0.87, 0.95);
        displacement_noise->setConfig(1.0, 0.4, 0.5, 0.85);
        detail_noise->setConfig(0.02, 0.04);
        material->setColor(0.6, 0.55, 0.57, 1.0);
        material->reflection = 0.006;
        material->shininess = 6.0;
        break;
    case TEXTURES_LAYER_PRESET_GRASS:
        terrain_zone->addHeightRangeQuick(1.0, 0.45, 0.5, 0.7, 0.9);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.4);
        displacement_noise->setConfig(0.4, 0.05);
        detail_noise->setConfig(0.01, 0.1);
        material->setColor(0.12, 0.19, 0.035, 1.0);
        material->reflection = 0.001;
        material->shininess = 4.0;
        break;
    case TEXTURES_LAYER_PRESET_SAND:
        terrain_zone->addHeightRangeQuick(1.0, 0.495, 0.505, 0.56, 0.63);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.3);
        displacement_noise->setConfig(0.04, 0.1, 0.5, 0.3);
        detail_noise->setConfig(0.004, 0.08);
        material->setColor(1.2, 1.1, 0.9, 1.0);
        material->reflection = 0.008;
        material->shininess = 1.0;
        break;
    case TEXTURES_LAYER_PRESET_SNOW:
        terrain_zone->addHeightRangeQuick(1.0, 0.87, 0.95, 10.0, 100.0);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.1, 1.0);
        displacement_noise->setConfig(0.4, 0.07);
        detail_noise->setConfig(0.01, 0.03);
        material->setColor(5.0, 5.0, 5.0, 1.0);
        material->reflection = 0.02;
        material->shininess = 0.6;
        break;
    }

    validate();
}

bool TextureLayerDefinition::hasDisplacement() const {
    return displacement_noise->getGenerator()->getHeight() > 0.0;
}

double TextureLayerDefinition::getMaximalDisplacement() const {
    double neg, pos;
    displacement_noise->getGenerator()->estimateRange(&neg, &pos);
    return max(fabs(neg), fabs(pos));
}
<commit_msg>Minor terrain texture tweaking<commit_after>#include "TextureLayerDefinition.h"

#include <algorithm>
#include "Zone.h"
#include "SurfaceMaterial.h"
#include "PackStream.h"
#include "Scenery.h"
#include "TerrainDefinition.h"
#include "Color.h"
#include "FractalNoise.h"
#include "NoiseNode.h"

TextureLayerDefinition::TextureLayerDefinition(DefinitionNode *parent, const string &name)
    : DefinitionNode(parent, name, "texturelayer") {
    terrain_zone = new Zone;
    material = new SurfaceMaterial;

    displacement_noise = new NoiseNode(this, "displacement");
    displacement_noise->setConfig(0.0);

    detail_noise = new NoiseNode(this, "detail");
    detail_noise->setConfig(0.01);
}

TextureLayerDefinition::~TextureLayerDefinition() {
    delete terrain_zone;
    delete material;
}

void TextureLayerDefinition::validate() {
    DefinitionNode::validate();

    material->validate();

    // Update zone height range
    if (auto scenery = getScenery()) {
        TerrainDefinition *terrain = scenery->getTerrain();
        HeightInfo height_info = terrain->getHeightInfo();
        terrain_zone->setRelativeHeight(height_info.min_height, height_info.base_height, height_info.max_height);
    }
}

void TextureLayerDefinition::copy(DefinitionNode *destination) const {
    DefinitionNode::copy(destination);

    if (auto tex_destination = static_cast<TextureLayerDefinition *>(destination)) {
        terrain_zone->copy(tex_destination->terrain_zone);

        *tex_destination->material = *material;
    }
}

void TextureLayerDefinition::save(PackStream *stream) const {
    DefinitionNode::save(stream);

    terrain_zone->save(stream);
    material->save(stream);
}

void TextureLayerDefinition::load(PackStream *stream) {
    DefinitionNode::load(stream);

    terrain_zone->load(stream);
    material->load(stream);
}

void TextureLayerDefinition::applyPreset(TextureLayerPreset preset, RandomGenerator &random) {
    displacement_noise->randomize(random);
    detail_noise->randomize(random);

    terrain_zone->clear();

    switch (preset) {
    case TEXTURES_LAYER_PRESET_MUD:
        displacement_noise->setConfig(0.05, 0.1, 0.3);
        detail_noise->setConfig(0.01, 0.03);
        material->setColor(0.015, 0.014, 0.014, 1.0);
        material->reflection = 0.003;
        material->shininess = 4.0;
        break;
    case TEXTURES_LAYER_PRESET_ROCK:
        terrain_zone->addHeightRangeQuick(1.0, 0.6, 0.7, 0.87, 0.95);
        displacement_noise->setConfig(4.0, 0.3, 0.5, 0.85);
        detail_noise->setConfig(0.02, 0.04);
        material->setColor(0.6, 0.55, 0.57, 1.0);
        material->reflection = 0.006;
        material->shininess = 6.0;
        break;
    case TEXTURES_LAYER_PRESET_GRASS:
        terrain_zone->addHeightRangeQuick(1.0, 0.45, 0.5, 0.7, 0.9);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.4);
        displacement_noise->setConfig(2.0, 0.05);
        detail_noise->setConfig(0.01, 0.1);
        material->setColor(0.12, 0.19, 0.035, 1.0);
        material->reflection = 0.001;
        material->shininess = 4.0;
        break;
    case TEXTURES_LAYER_PRESET_SAND:
        terrain_zone->addHeightRangeQuick(1.0, 0.495, 0.505, 0.56, 0.63);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.05, 0.3);
        displacement_noise->setConfig(0.04, 0.1, 0.5, 0.3);
        detail_noise->setConfig(0.004, 0.08);
        material->setColor(1.2, 1.1, 0.9, 1.0);
        material->reflection = 0.008;
        material->shininess = 1.0;
        break;
    case TEXTURES_LAYER_PRESET_SNOW:
        terrain_zone->addHeightRangeQuick(1.0, 0.87, 0.95, 10.0, 100.0);
        terrain_zone->addSlopeRangeQuick(1.0, 0.0, 0.0, 0.1, 1.0);
        displacement_noise->setConfig(0.4, 0.07);
        detail_noise->setConfig(0.01, 0.03);
        material->setColor(5.0, 5.0, 5.0, 1.0);
        material->reflection = 0.02;
        material->shininess = 0.6;
        break;
    }

    validate();
}

bool TextureLayerDefinition::hasDisplacement() const {
    return displacement_noise->getGenerator()->getHeight() > 0.0;
}

double TextureLayerDefinition::getMaximalDisplacement() const {
    double neg, pos;
    displacement_noise->getGenerator()->estimateRange(&neg, &pos);
    return max(fabs(neg), fabs(pos));
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file SignalFinder.cpp
 */

using namespace std;

#include <map>
#include <string>
#include <vector>
#include <JPetWriter/JPetWriter.h>
#include "SignalFinderTools.h"
#include "SignalFinder.h"

SignalFinder::SignalFinder(const char* name)
	: JPetUserTask(name)
{
  //	fSaveControlHistos = saveControlHistos;
}

SignalFinder::~SignalFinder() {}

//SignalFinder init method
bool SignalFinder::init()
{
	INFO("Signal finding started.");

	fOutputEvents = new JPetTimeWindow("JPetRawSignal");

	if (fParams.getOptions().count(fEdgeMaxTimeParamKey)) {
	  kSigChEdgeMaxTime = boost::any_cast<float>(fParams.getOptions().at(fEdgeMaxTimeParamKey));
	}

	if (fParams.getOptions().count(fLeadTrailMaxTimeParamKey)) {
	  kSigChLeadTrailMaxTime = boost::any_cast<float>(fParams.getOptions().at(fLeadTrailMaxTimeParamKey));
	}

	if (fSaveControlHistos) {
		getStatistics().createHistogram(
			new TH1F("remainig_leading_sig_ch_per_thr",
				"Remainig Leading Signal Channels",
				4, 0.5, 4.5));
		getStatistics().createHistogram(
			new TH1F("remainig_trailing_sig_ch_per_thr",
				"Remainig Trailing Signal Channels",
				4, 0.5, 4.5));
	}
	return true;
}

//SignalFinder execution method
bool SignalFinder::exec()
{

	//getting the data from event in apropriate format
	if(auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {

		//mapping method invocation
		map<int, vector<JPetSigCh>> sigChsPMMap = SignalFinderTools::getSigChsPMMapById(timeWindow);

		//building signals method invocation
		vector<JPetRawSignal> allSignals = SignalFinderTools::buildAllSignals(
    							sigChsPMMap,
    							kNumOfThresholds ,
    							getStatistics(),
    							fSaveControlHistos,
    							kSigChEdgeMaxTime,
    							kSigChLeadTrailMaxTime);

		//saving method invocation
		saveRawSignals(allSignals);

	}else{
	  return false;
	}
	return true;
}

//SignalFinder finish method
bool SignalFinder::terminate()
{
	INFO("Signal finding ended.");
	return true;
}

//saving method
void SignalFinder::saveRawSignals(const vector<JPetRawSignal>& sigChVec)
{
	for (auto & sigCh : sigChVec) {
	  fOutputEvents->add<JPetRawSignal>(sigCh);
	}
}

<commit_msg>Use tools facilitating options access in SignalFinder<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file SignalFinder.cpp
 */

using namespace std;

#include <map>
#include <string>
#include <vector>
#include <JPetWriter/JPetWriter.h>
#include "SignalFinderTools.h"
#include "SignalFinder.h"
#include <JPetOptionsTools/JPetOptionsTools.h>

using namespace jpet_options_tools;

SignalFinder::SignalFinder(const char* name)
	: JPetUserTask(name)
{
  //	fSaveControlHistos = saveControlHistos;
}

SignalFinder::~SignalFinder() {}

//SignalFinder init method
bool SignalFinder::init()
{
	INFO("Signal finding started.");

	fOutputEvents = new JPetTimeWindow("JPetRawSignal");

	if (isOptionSet(fParams.getOptions(), fEdgeMaxTimeParamKey)) {
	  kSigChEdgeMaxTime = getOptionAsFloat(fParams.getOptions(), fEdgeMaxTimeParamKey);
	}

	if (isOptionSet(fParams.getOptions(), fLeadTrailMaxTimeParamKey)) {
	  kSigChLeadTrailMaxTime = getOptionAsFloat(fParams.getOptions(), fLeadTrailMaxTimeParamKey);
	}

	if (fSaveControlHistos) {
		getStatistics().createHistogram(
			new TH1F("remainig_leading_sig_ch_per_thr",
				"Remainig Leading Signal Channels",
				4, 0.5, 4.5));
		getStatistics().createHistogram(
			new TH1F("remainig_trailing_sig_ch_per_thr",
				"Remainig Trailing Signal Channels",
				4, 0.5, 4.5));
	}
	return true;
}

//SignalFinder execution method
bool SignalFinder::exec()
{

	//getting the data from event in apropriate format
	if(auto timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {

		//mapping method invocation
		map<int, vector<JPetSigCh>> sigChsPMMap = SignalFinderTools::getSigChsPMMapById(timeWindow);

		//building signals method invocation
		vector<JPetRawSignal> allSignals = SignalFinderTools::buildAllSignals(
    							sigChsPMMap,
    							kNumOfThresholds ,
    							getStatistics(),
    							fSaveControlHistos,
    							kSigChEdgeMaxTime,
    							kSigChLeadTrailMaxTime);

		//saving method invocation
		saveRawSignals(allSignals);

	}else{
	  return false;
	}
	return true;
}

//SignalFinder finish method
bool SignalFinder::terminate()
{
	INFO("Signal finding ended.");
	return true;
}

//saving method
void SignalFinder::saveRawSignals(const vector<JPetRawSignal>& sigChVec)
{
	for (auto & sigCh : sigChVec) {
	  fOutputEvents->add<JPetRawSignal>(sigCh);
	}
}

<|endoftext|>


<commit_before>#include <iostream>
#if defined(_MSC_VER)
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif

/*
*  Lesson 1: Hello World!
*/
int main(int argc, char** argv){
	//First we need to start up SDL, and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
	SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
	//Make sure creating our window went ok
	if (win == nullptr){
		std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Create a renderer that will draw to the window, -1 specifies that we want to load whichever
	//video driver supports the flags we're passing
	//Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering
	//SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
	//synchornized with the monitor's refresh rate
	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr){
		std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface
	//this lets us choose when to upload or remove textures from the GPU
	SDL_Surface *bmp = SDL_LoadBMP("../res/Lesson1/hello.bmp");
	if (bmp == nullptr){
		std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//To use a hardware accelerated texture for rendering we can create one from
	//the surface we loaded
	SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
	if (tex == nullptr){
		std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
		return 1;
	}
	//We no longer need the surface
	SDL_FreeSurface(bmp);

	//Now lets draw our image
	//First clear the renderer
	SDL_RenderClear(ren);
	//Draw the texture
	SDL_RenderCopy(ren, tex, NULL, NULL);
	//Update the screen
	SDL_RenderPresent(ren);

	//Have the program wait for 2000ms so we get a chance to see the screen
	SDL_Delay(2000);

	//Clean up our objects and quit
	SDL_DestroyTexture(tex);
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	SDL_Quit();

	return 0;
}
<commit_msg>free the surface before checking for errors<commit_after>#include <iostream>
#if defined(_MSC_VER)
#include <SDL.h>
#else
#include <SDL2/SDL.h>
#endif

/*
*  Lesson 1: Hello World!
*/
int main(int argc, char** argv){
	//First we need to start up SDL, and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
	SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
	//Make sure creating our window went ok
	if (win == nullptr){
		std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Create a renderer that will draw to the window, -1 specifies that we want to load whichever
	//video driver supports the flags we're passing
	//Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering
	//SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
	//synchornized with the monitor's refresh rate
	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr){
		std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface
	//this lets us choose when to upload or remove textures from the GPU
	SDL_Surface *bmp = SDL_LoadBMP("../res/Lesson1/hello.bmp");
	if (bmp == nullptr){
		std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//To use a hardware accelerated texture for rendering we can create one from
	//the surface we loaded
	SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
	//We no longer need the surface
	SDL_FreeSurface(bmp);
	if (tex == nullptr){
		std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
		return 1;
	}

	//Now lets draw our image
	//First clear the renderer
	SDL_RenderClear(ren);
	//Draw the texture
	SDL_RenderCopy(ren, tex, NULL, NULL);
	//Update the screen
	SDL_RenderPresent(ren);

	//Have the program wait for 2000ms so we get a chance to see the screen
	SDL_Delay(2000);

	//Clean up our objects and quit
	SDL_DestroyTexture(tex);
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	SDL_Quit();

	return 0;
}
<|endoftext|>