<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER 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.
#include <assert.h>
#include <errno.h>
#include "../../basic/TTypes.h"
#include "../../basic/TLogging.h"
#include "../TChannel.h"
#include "TSelectPollerWindows.h"

namespace tyr { namespace net {

struct _FdSet_t {
  u_int fd_count;
  int fd_array[1];
};

static inline void WINFD_CLR(int fd, _FdSet_t* set) {
  FD_CLR(fd, set);
}

static inline void WINFD_ZERO(_FdSet_t* set) {
  FD_ZERO(set);
}

static inline bool WINFD_ISSET(int fd, _FdSet_t* set) {
  return FD_ISSET(fd, set) != 0;
}

static inline void WINFD_SET(int fd, _FdSet_t* set)  {
  u_int i;
  for (i = 0; i < set->fd_count; ++i) {
    if (fd == set->fd_array[i])
      break;
  }

  if (i == set->fd_count) {
    set->fd_array[i] = fd;
    ++set->fd_count;
  }
}

static inline void WINFD_COPY(_FdSet_t* d_set, _FdSet_t* s_set) {
  d_set->fd_count = s_set->fd_count;
  memcpy(d_set->fd_array, s_set->fd_array, s_set->fd_count * sizeof(int));
}

SelectPoller::SelectPoller(EventLoop* loop)
  : Poller(loop) {
  sets_alloc();
}

SelectPoller::~SelectPoller(void) {
  sets_dealloc();
}

basic::Timestamp SelectPoller::poll(int timeout, std::vector<Channel*>* active_channels) {
  struct timeval tv = {timeout / 1000, timeout % 1000 * 1000};
  WINFD_COPY(rsets_out_, rsets_in_);
  WINFD_COPY(wsets_out_, wsets_in_);

  int num_events = select(0, (struct fd_set*)rsets_out_, (struct fd_set*)wsets_out_, nullptr, &tv);
  int saved_errno = errno;
  if (num_events > 0) {
    TYRLOG_TRACE << "SelectPoller::poll - " << num_events << " events happened";
    fill_active_channels(num_events, active_channels);
  }
  else if (num_events == 0) {
    TYRLOG_TRACE << "SelectPoller::poll - nothing happened";
  }
  else {
    if (saved_errno != EINTR) {
      errno = saved_errno;
      TYRLOG_SYSERR << "SelectPoller::poll";
    }
  }
  return basic::Timestamp::now();
}

void SelectPoller::update_channel(Channel* channel) {
  assert_in_loopthread();
  TYRLOG_TRACE << "SelectPoller::update_channel - fd=" << channel->get_fd() << " events=" << channel->get_events();
  if (channel->get_index() < 0) {
    // add new fd events listening into channels_
    assert(channels_.find(channel->get_fd()) == channels_.end());
    if (channels_.size() >= static_cast<size_t>(fd_storage_))
      sets_realloc();

    if (channel->is_reading())
      WINFD_SET(channel->get_fd(), rsets_in_);
    if (channel->is_writing())
      WINFD_SET(channel->get_fd(), wsets_in_);
    channel->set_index(channel->get_fd());
    channels_[channel->get_fd()] = channel;
  }
  else {
    // updated the events of an existing channel
    assert(channels_.find(channel->get_fd()) != channels_.end());
    assert(channels_[channel->get_fd()] == channel);
    assert(channel->get_index() > 0);
    if (!channel->is_reading())
      WINFD_CLR(channel->get_fd(), rsets_in_);
    if (!channel->is_writing())
      WINFD_CLR(channel->get_fd(), wsets_in_);
  }
}

void SelectPoller::remove_channel(Channel* channel) {
  assert_in_loopthread();
  TYRLOG_TRACE << "SelectPoller::remove_channel - fd=" << channel->get_fd();
  assert(channels_.find(channel->get_fd()) != channels_.end());
  assert(channels_[channel->get_fd()] == channel);
  assert(channel->is_none_event());
}

void SelectPoller::fill_active_channels(int nevents, std::vector<Channel*>* active_channels) const {
  for (auto& ch : channels_) {
    if (nevents <= 0)
      break;

    int revents = 0;
    Channel* channel = ch.second;
    if (WINFD_ISSET(channel->get_fd(), rsets_out_))
      revents |= POLLIN;
    if (WINFD_ISSET(channel->get_fd(), wsets_out_))
      revents |= POLLOUT;

    if (revents == 0)
      continue;

    --nevents;
    channel->set_revents(revents);
    active_channels->push_back(channel);
  }
}

void SelectPoller::sets_alloc(void) {
  fd_storage_ = FD_SETSIZE;
  size_t size = sizeof(_FdSet_t) + (fd_storage_ - 1) * sizeof(int);

  if (nullptr == (rsets_in_ = (_FdSet_t*)malloc(size)))
    return;

  do {
    if (nullptr == (wsets_in_ = (_FdSet_t*)malloc(size)))
      break;
    if (nullptr == (rsets_out_ = (_FdSet_t*)malloc(size)))
      break;
    if (nullptr == (wsets_out_ = (_FdSet_t*)malloc(size)))
      break;

    WINFD_ZERO(rsets_in_);
    WINFD_ZERO(wsets_in_);
    return;
  } while (false);

  sets_dealloc();
}

void SelectPoller::sets_dealloc(void) {
  if (nullptr != rsets_in_) {
    free(rsets_in_);
    rsets_in_ = nullptr;
  }
  if (nullptr != wsets_in_) {
    free(wsets_in_);
    wsets_in_ = nullptr;
  }
  if (nullptr != rsets_out_) {
    free(rsets_out_);
    rsets_out_ = nullptr;
  }
  if (nullptr != wsets_out_) {
    free(wsets_out_);
    wsets_out_ = nullptr;
  }
  fd_storage_ = FD_SETSIZE;
}

void SelectPoller::sets_realloc(void) {
  int new_fd_storage = (0 != fd_storage_ ? static_cast<int>(1.5 * fd_storage_) : FD_SETSIZE);
  size_t size = sizeof(_FdSet_t) + (new_fd_storage - 1) * sizeof(int);

  if (nullptr == (rsets_in_ = (_FdSet_t*)realloc(rsets_in_, size)))
    return;

  do {
    if (nullptr == (wsets_in_ = (_FdSet_t*)realloc(wsets_in_, size)))
      break;
    if (nullptr == (rsets_out_ = (_FdSet_t*)realloc(rsets_out_, size)))
      break;
    if (nullptr == (wsets_out_ = (_FdSet_t*)realloc(wsets_out_, size)))
      break;

    fd_storage_ = new_fd_storage;
    return;
  } while (false);

  sets_dealloc();
}

}}
<commit_msg>:construction: chore(win.select): updated the remove channel functional of select poller<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER 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.
#include <assert.h>
#include <errno.h>
#include "../../basic/TTypes.h"
#include "../../basic/TLogging.h"
#include "../TChannel.h"
#include "TSelectPollerWindows.h"

namespace tyr { namespace net {

struct _FdSet_t {
  u_int fd_count;
  int fd_array[1];
};

static inline void WINFD_CLR(int fd, _FdSet_t* set) {
  FD_CLR(fd, set);
}

static inline void WINFD_ZERO(_FdSet_t* set) {
  FD_ZERO(set);
}

static inline bool WINFD_ISSET(int fd, _FdSet_t* set) {
  return FD_ISSET(fd, set) != 0;
}

static inline void WINFD_SET(int fd, _FdSet_t* set)  {
  u_int i;
  for (i = 0; i < set->fd_count; ++i) {
    if (fd == set->fd_array[i])
      break;
  }

  if (i == set->fd_count) {
    set->fd_array[i] = fd;
    ++set->fd_count;
  }
}

static inline void WINFD_COPY(_FdSet_t* d_set, _FdSet_t* s_set) {
  d_set->fd_count = s_set->fd_count;
  memcpy(d_set->fd_array, s_set->fd_array, s_set->fd_count * sizeof(int));
}

SelectPoller::SelectPoller(EventLoop* loop)
  : Poller(loop) {
  sets_alloc();
}

SelectPoller::~SelectPoller(void) {
  sets_dealloc();
}

basic::Timestamp SelectPoller::poll(int timeout, std::vector<Channel*>* active_channels) {
  struct timeval tv = {timeout / 1000, timeout % 1000 * 1000};
  WINFD_COPY(rsets_out_, rsets_in_);
  WINFD_COPY(wsets_out_, wsets_in_);

  int num_events = select(0, (struct fd_set*)rsets_out_, (struct fd_set*)wsets_out_, nullptr, &tv);
  int saved_errno = errno;
  if (num_events > 0) {
    TYRLOG_TRACE << "SelectPoller::poll - " << num_events << " events happened";
    fill_active_channels(num_events, active_channels);
  }
  else if (num_events == 0) {
    TYRLOG_TRACE << "SelectPoller::poll - nothing happened";
  }
  else {
    if (saved_errno != EINTR) {
      errno = saved_errno;
      TYRLOG_SYSERR << "SelectPoller::poll";
    }
  }
  return basic::Timestamp::now();
}

void SelectPoller::update_channel(Channel* channel) {
  assert_in_loopthread();
  TYRLOG_TRACE << "SelectPoller::update_channel - fd=" << channel->get_fd() << " events=" << channel->get_events();
  if (channel->get_index() < 0) {
    // add new fd events listening into channels_
    assert(channels_.find(channel->get_fd()) == channels_.end());
    if (channels_.size() >= static_cast<size_t>(fd_storage_))
      sets_realloc();

    if (channel->is_reading())
      WINFD_SET(channel->get_fd(), rsets_in_);
    if (channel->is_writing())
      WINFD_SET(channel->get_fd(), wsets_in_);
    channel->set_index(channel->get_fd());
    channels_[channel->get_fd()] = channel;
  }
  else {
    // updated the events of an existing channel
    assert(channels_.find(channel->get_fd()) != channels_.end());
    assert(channels_[channel->get_fd()] == channel);
    assert(channel->get_index() > 0);
    if (!channel->is_reading())
      WINFD_CLR(channel->get_fd(), rsets_in_);
    if (!channel->is_writing())
      WINFD_CLR(channel->get_fd(), wsets_in_);
  }
}

void SelectPoller::remove_channel(Channel* channel) {
  assert_in_loopthread();
  TYRLOG_TRACE << "SelectPoller::remove_channel - fd=" << channel->get_fd();
  assert(channels_.find(channel->get_fd()) != channels_.end());
  assert(channels_[channel->get_fd()] == channel);
  assert(channel->is_none_event());

  int fd = channel->get_fd();
  WINFD_CLR(fd, rsets_in_);
  WINFD_CLR(fd, wsets_in_);
  WINFD_CLR(fd, rsets_out_);
  WINFD_CLR(fd, wsets_out_);
}

void SelectPoller::fill_active_channels(int nevents, std::vector<Channel*>* active_channels) const {
  for (auto& ch : channels_) {
    if (nevents <= 0)
      break;

    int revents = 0;
    Channel* channel = ch.second;
    if (WINFD_ISSET(channel->get_fd(), rsets_out_))
      revents |= POLLIN;
    if (WINFD_ISSET(channel->get_fd(), wsets_out_))
      revents |= POLLOUT;

    if (revents == 0)
      continue;

    --nevents;
    channel->set_revents(revents);
    active_channels->push_back(channel);
  }
}

void SelectPoller::sets_alloc(void) {
  fd_storage_ = FD_SETSIZE;
  size_t size = sizeof(_FdSet_t) + (fd_storage_ - 1) * sizeof(int);

  if (nullptr == (rsets_in_ = (_FdSet_t*)malloc(size)))
    return;

  do {
    if (nullptr == (wsets_in_ = (_FdSet_t*)malloc(size)))
      break;
    if (nullptr == (rsets_out_ = (_FdSet_t*)malloc(size)))
      break;
    if (nullptr == (wsets_out_ = (_FdSet_t*)malloc(size)))
      break;

    WINFD_ZERO(rsets_in_);
    WINFD_ZERO(wsets_in_);
    return;
  } while (false);

  sets_dealloc();
}

void SelectPoller::sets_dealloc(void) {
  if (nullptr != rsets_in_) {
    free(rsets_in_);
    rsets_in_ = nullptr;
  }
  if (nullptr != wsets_in_) {
    free(wsets_in_);
    wsets_in_ = nullptr;
  }
  if (nullptr != rsets_out_) {
    free(rsets_out_);
    rsets_out_ = nullptr;
  }
  if (nullptr != wsets_out_) {
    free(wsets_out_);
    wsets_out_ = nullptr;
  }
  fd_storage_ = FD_SETSIZE;
}

void SelectPoller::sets_realloc(void) {
  int new_fd_storage = (0 != fd_storage_ ? static_cast<int>(1.5 * fd_storage_) : FD_SETSIZE);
  size_t size = sizeof(_FdSet_t) + (new_fd_storage - 1) * sizeof(int);

  if (nullptr == (rsets_in_ = (_FdSet_t*)realloc(rsets_in_, size)))
    return;

  do {
    if (nullptr == (wsets_in_ = (_FdSet_t*)realloc(wsets_in_, size)))
      break;
    if (nullptr == (rsets_out_ = (_FdSet_t*)realloc(rsets_out_, size)))
      break;
    if (nullptr == (wsets_out_ = (_FdSet_t*)realloc(wsets_out_, size)))
      break;

    fd_storage_ = new_fd_storage;
    return;
  } while (false);

  sets_dealloc();
}

}}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: formcontrolcontainer.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 16:03:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef EXTENSIONS_BIB_FORMCONTROLCONTAINER_HXX
#include "formcontrolcontainer.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include <algorithm>

//.........................................................................
namespace bib
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::awt;

    //=====================================================================
    //= FormControlContainer
    //=====================================================================
    //---------------------------------------------------------------------
    FormControlContainer::FormControlContainer( )
        :OLoadListener( m_aMutex )
        ,m_pFormAdapter( NULL )
    {
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:54:57 -----------------------------------------------
    FormControlContainer::~FormControlContainer( )
    {
        DBG_ASSERT( !isFormConnected(), "FormControlContainer::~FormControlContainer: you should disconnect in your derived class!" );
        if ( isFormConnected() )
            disconnectForm();
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 17:03:14 -----------------------------------------------
    void FormControlContainer::disconnectForm()
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        DBG_ASSERT( isFormConnected(), "FormControlContainer::connectForm: not connected!" );
        if ( isFormConnected() )
        {
            m_pFormAdapter->dispose();
            m_pFormAdapter->release();
            m_pFormAdapter = NULL;
        }
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:56:01 -----------------------------------------------
    void FormControlContainer::connectForm( const Reference< XLoadable >& _rxForm )
    {
        DBG_ASSERT( !isFormConnected(), "FormControlContainer::connectForm: already connected!" );

        DBG_ASSERT( _rxForm.is(), "FormControlContainer::connectForm: invalid form!" );
        if ( !isFormConnected() && _rxForm.is() )
        {
            m_pFormAdapter = new OLoadListenerAdapter( _rxForm );
            m_pFormAdapter->acquire();
            m_pFormAdapter->Init( this );

            ensureDesignMode();
        }

        m_xForm = _rxForm;
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:50:14 -----------------------------------------------
    struct ControlModeSwitch : public ::std::unary_function< Reference< XControl >, void >
    {
        sal_Bool bDesign;
        ControlModeSwitch( sal_Bool _bDesign ) : bDesign( _bDesign ) { }

        void operator() ( const Reference< XControl >& _rxControl ) const
        {
            if ( _rxControl.is() )
                _rxControl->setDesignMode( bDesign );
        }
    };

    //---------------------------------------------------------------------
    //--- 18.10.01 18:49:57 -----------------------------------------------
    void FormControlContainer::implSetDesignMode( sal_Bool _bDesign )
    {
        try
        {
            Reference< XControlContainer > xControlCont = getControlContainer();
            Sequence< Reference< XControl > > aControls;
            if ( xControlCont.is() )
                aControls = xControlCont->getControls();

            ::std::for_each(
                aControls.getConstArray(),
                aControls.getConstArray() + aControls.getLength(),
                ControlModeSwitch( _bDesign )
            );
        }
        catch( const Exception& e)
        {
            e;  // make compiler happy
            DBG_ERROR( "FormControlContainer::implSetDesignMode: caught an exception!" );
        }
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:16:54 -----------------------------------------------
    void FormControlContainer::ensureDesignMode()
    {
        implSetDesignMode( !m_xForm.is() || !m_xForm->isLoaded() );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:33 -----------------------------------------------
    void FormControlContainer::_loaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_False );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:35 -----------------------------------------------
    void FormControlContainer::_unloading( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_True );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:36 -----------------------------------------------
    void FormControlContainer::_unloaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:36 -----------------------------------------------
    void FormControlContainer::_reloading( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_True );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:37 -----------------------------------------------
    void FormControlContainer::_reloaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_False );
    }

//.........................................................................
}   // namespace bib
//.........................................................................

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.504); FILE MERGED 2005/09/05 12:58:46 rt 1.3.504.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formcontrolcontainer.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:17:06 $
 *
 *  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 EXTENSIONS_BIB_FORMCONTROLCONTAINER_HXX
#include "formcontrolcontainer.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include <algorithm>

//.........................................................................
namespace bib
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::form;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::awt;

    //=====================================================================
    //= FormControlContainer
    //=====================================================================
    //---------------------------------------------------------------------
    FormControlContainer::FormControlContainer( )
        :OLoadListener( m_aMutex )
        ,m_pFormAdapter( NULL )
    {
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:54:57 -----------------------------------------------
    FormControlContainer::~FormControlContainer( )
    {
        DBG_ASSERT( !isFormConnected(), "FormControlContainer::~FormControlContainer: you should disconnect in your derived class!" );
        if ( isFormConnected() )
            disconnectForm();
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 17:03:14 -----------------------------------------------
    void FormControlContainer::disconnectForm()
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        DBG_ASSERT( isFormConnected(), "FormControlContainer::connectForm: not connected!" );
        if ( isFormConnected() )
        {
            m_pFormAdapter->dispose();
            m_pFormAdapter->release();
            m_pFormAdapter = NULL;
        }
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:56:01 -----------------------------------------------
    void FormControlContainer::connectForm( const Reference< XLoadable >& _rxForm )
    {
        DBG_ASSERT( !isFormConnected(), "FormControlContainer::connectForm: already connected!" );

        DBG_ASSERT( _rxForm.is(), "FormControlContainer::connectForm: invalid form!" );
        if ( !isFormConnected() && _rxForm.is() )
        {
            m_pFormAdapter = new OLoadListenerAdapter( _rxForm );
            m_pFormAdapter->acquire();
            m_pFormAdapter->Init( this );

            ensureDesignMode();
        }

        m_xForm = _rxForm;
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:50:14 -----------------------------------------------
    struct ControlModeSwitch : public ::std::unary_function< Reference< XControl >, void >
    {
        sal_Bool bDesign;
        ControlModeSwitch( sal_Bool _bDesign ) : bDesign( _bDesign ) { }

        void operator() ( const Reference< XControl >& _rxControl ) const
        {
            if ( _rxControl.is() )
                _rxControl->setDesignMode( bDesign );
        }
    };

    //---------------------------------------------------------------------
    //--- 18.10.01 18:49:57 -----------------------------------------------
    void FormControlContainer::implSetDesignMode( sal_Bool _bDesign )
    {
        try
        {
            Reference< XControlContainer > xControlCont = getControlContainer();
            Sequence< Reference< XControl > > aControls;
            if ( xControlCont.is() )
                aControls = xControlCont->getControls();

            ::std::for_each(
                aControls.getConstArray(),
                aControls.getConstArray() + aControls.getLength(),
                ControlModeSwitch( _bDesign )
            );
        }
        catch( const Exception& e)
        {
            e;  // make compiler happy
            DBG_ERROR( "FormControlContainer::implSetDesignMode: caught an exception!" );
        }
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 18:16:54 -----------------------------------------------
    void FormControlContainer::ensureDesignMode()
    {
        implSetDesignMode( !m_xForm.is() || !m_xForm->isLoaded() );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:33 -----------------------------------------------
    void FormControlContainer::_loaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_False );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:35 -----------------------------------------------
    void FormControlContainer::_unloading( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_True );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:36 -----------------------------------------------
    void FormControlContainer::_unloaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:36 -----------------------------------------------
    void FormControlContainer::_reloading( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_True );
    }

    //---------------------------------------------------------------------
    //--- 18.10.01 16:45:37 -----------------------------------------------
    void FormControlContainer::_reloaded( const ::com::sun::star::lang::EventObject& _rEvent )
    {
        implSetDesignMode( sal_False );
    }

//.........................................................................
}   // namespace bib
//.........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acceleratorconfigurationwriter.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:02:38 $
 *
 *  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 _FRAMEWORK_XML_ACCELERATORCONFIGURATIONWRITER_HXX_
#include <xml/acceleratorconfigurationwriter.hxx>
#endif

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_XML_ATTRIBUTELIST_HXX
#include <xml/attributelist.hxx>
#endif

#ifndef __FRAMEWORK_ACCELERATORCONST_H_
#include <acceleratorconst.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_KEYMODIFIER_HPP_
#include <com/sun/star/awt/KeyModifier.hpp>
#endif

//_______________________________________________
// other includes

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//-----------------------------------------------
AcceleratorConfigurationWriter::AcceleratorConfigurationWriter(const AcceleratorCache&                                       rContainer,
                                                               const css::uno::Reference< css::xml::sax::XDocumentHandler >& xConfig   )
    : ThreadHelpBase(&Application::GetSolarMutex())
    , m_rContainer  (rContainer                   )
    , m_xConfig     (xConfig                      )
{
}

//-----------------------------------------------
AcceleratorConfigurationWriter::~AcceleratorConfigurationWriter()
{
}

//-----------------------------------------------
void AcceleratorConfigurationWriter::flush()
{
    // SAFE -> ----------------------------------
    ReadGuard aReadLock(m_aLock);

    css::uno::Reference< css::xml::sax::XDocumentHandler >         xCFG        = m_xConfig;
    css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > xExtendedCFG(m_xConfig, css::uno::UNO_QUERY_THROW);

    aReadLock.unlock();
    // <- SAFE ----------------------------------

    // prepare attribute list
    AttributeListImpl*                                   pAttribs = new AttributeListImpl;
    css::uno::Reference< css::xml::sax::XAttributeList > xAttribs(static_cast< css::xml::sax::XAttributeList* >(pAttribs), css::uno::UNO_QUERY);

    pAttribs->addAttribute(AL_XMLNS_ACCEL, ATTRIBUTE_TYPE_CDATA, NS_XMLNS_ACCEL);
    pAttribs->addAttribute(AL_XMLNS_XLINK, ATTRIBUTE_TYPE_CDATA, NS_XMLNS_XLINK);

    // generate xml
    xCFG->startDocument();

    xExtendedCFG->unknown(DOCTYPE_ACCELERATORS);
    xCFG->ignorableWhitespace(::rtl::OUString());

    xCFG->startElement(AL_ELEMENT_ACCELERATORLIST, xAttribs);
    xCFG->ignorableWhitespace(::rtl::OUString());

    // TODO think about threadsafe using of cache
    AcceleratorCache::TKeyList                 lKeys = m_rContainer.getAllKeys();
    AcceleratorCache::TKeyList::const_iterator pKey  ;
    for (  pKey  = lKeys.begin();
           pKey != lKeys.end()  ;
         ++pKey                 )
    {
        const css::awt::KeyEvent& rKey     = *pKey;
        const ::rtl::OUString&    rCommand = m_rContainer.getCommandByKey(rKey);
        impl_ts_writeKeyCommandPair(rKey, rCommand, xCFG);
    }

    /* TODO write key-command list
    std::vector< SfxAcceleratorConfigItem>::const_iterator p;
    for ( p = m_aWriteAcceleratorList.begin(); p != m_aWriteAcceleratorList.end(); p++ )
        WriteAcceleratorItem( *p );
    */

    xCFG->ignorableWhitespace(::rtl::OUString());
    xCFG->endElement(AL_ELEMENT_ACCELERATORLIST);
    xCFG->ignorableWhitespace(::rtl::OUString());
    xCFG->endDocument();
}

//-----------------------------------------------
void AcceleratorConfigurationWriter::impl_ts_writeKeyCommandPair(const css::awt::KeyEvent&                                     aKey    ,
                                                                 const ::rtl::OUString&                                        sCommand,
                                                                 const css::uno::Reference< css::xml::sax::XDocumentHandler >& xConfig )
{
    AttributeListImpl*                                   pAttribs = new AttributeListImpl;
    css::uno::Reference< css::xml::sax::XAttributeList > xAttribs (static_cast< css::xml::sax::XAttributeList* >(pAttribs) , css::uno::UNO_QUERY_THROW);

    ::rtl::OUString sKey = m_rKeyMapping->mapCodeToIdentifier(aKey.KeyCode);
    // TODO check if key is empty!

    pAttribs->addAttribute(AL_ATTRIBUTE_KEYCODE, ATTRIBUTE_TYPE_CDATA, sKey    );
    pAttribs->addAttribute(AL_ATTRIBUTE_URL    , ATTRIBUTE_TYPE_CDATA, sCommand);

    if ((aKey.Modifiers & css::awt::KeyModifier::SHIFT) == css::awt::KeyModifier::SHIFT)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_SHIFT, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    if ((aKey.Modifiers & css::awt::KeyModifier::MOD1) == css::awt::KeyModifier::MOD1)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_MOD1, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    if ((aKey.Modifiers & css::awt::KeyModifier::MOD2) == css::awt::KeyModifier::MOD2)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_MOD2, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    xConfig->ignorableWhitespace(::rtl::OUString());
    xConfig->startElement(AL_ELEMENT_ITEM, xAttribs);
    xConfig->ignorableWhitespace(::rtl::OUString());
    xConfig->endElement(AL_ELEMENT_ITEM);
    xConfig->ignorableWhitespace(::rtl::OUString());
}

} // namespace framework
<commit_msg>INTEGRATION: CWS warnings01 (1.3.32); FILE MERGED 2005/10/28 14:48:48 cd 1.3.32.1: #i55991# Warning free code changes for gcc<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: acceleratorconfigurationwriter.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:44:47 $
 *
 *  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 _FRAMEWORK_XML_ACCELERATORCONFIGURATIONWRITER_HXX_
#include <xml/acceleratorconfigurationwriter.hxx>
#endif

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_XML_ATTRIBUTELIST_HXX
#include <xml/attributelist.hxx>
#endif

#ifndef __FRAMEWORK_ACCELERATORCONST_H_
#include <acceleratorconst.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif

#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_KEYMODIFIER_HPP_
#include <com/sun/star/awt/KeyModifier.hpp>
#endif

//_______________________________________________
// other includes

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//-----------------------------------------------
AcceleratorConfigurationWriter::AcceleratorConfigurationWriter(const AcceleratorCache&                                       rContainer,
                                                               const css::uno::Reference< css::xml::sax::XDocumentHandler >& xConfig   )
    : ThreadHelpBase(&Application::GetSolarMutex())
    , m_xConfig     (xConfig                      )
    , m_rContainer  (rContainer                   )
{
}

//-----------------------------------------------
AcceleratorConfigurationWriter::~AcceleratorConfigurationWriter()
{
}

//-----------------------------------------------
void AcceleratorConfigurationWriter::flush()
{
    // SAFE -> ----------------------------------
    ReadGuard aReadLock(m_aLock);

    css::uno::Reference< css::xml::sax::XDocumentHandler >         xCFG        = m_xConfig;
    css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > xExtendedCFG(m_xConfig, css::uno::UNO_QUERY_THROW);

    aReadLock.unlock();
    // <- SAFE ----------------------------------

    // prepare attribute list
    AttributeListImpl*                                   pAttribs = new AttributeListImpl;
    css::uno::Reference< css::xml::sax::XAttributeList > xAttribs(static_cast< css::xml::sax::XAttributeList* >(pAttribs), css::uno::UNO_QUERY);

    pAttribs->addAttribute(AL_XMLNS_ACCEL, ATTRIBUTE_TYPE_CDATA, NS_XMLNS_ACCEL);
    pAttribs->addAttribute(AL_XMLNS_XLINK, ATTRIBUTE_TYPE_CDATA, NS_XMLNS_XLINK);

    // generate xml
    xCFG->startDocument();

    xExtendedCFG->unknown(DOCTYPE_ACCELERATORS);
    xCFG->ignorableWhitespace(::rtl::OUString());

    xCFG->startElement(AL_ELEMENT_ACCELERATORLIST, xAttribs);
    xCFG->ignorableWhitespace(::rtl::OUString());

    // TODO think about threadsafe using of cache
    AcceleratorCache::TKeyList                 lKeys = m_rContainer.getAllKeys();
    AcceleratorCache::TKeyList::const_iterator pKey  ;
    for (  pKey  = lKeys.begin();
           pKey != lKeys.end()  ;
         ++pKey                 )
    {
        const css::awt::KeyEvent& rKey     = *pKey;
        const ::rtl::OUString&    rCommand = m_rContainer.getCommandByKey(rKey);
        impl_ts_writeKeyCommandPair(rKey, rCommand, xCFG);
    }

    /* TODO write key-command list
    std::vector< SfxAcceleratorConfigItem>::const_iterator p;
    for ( p = m_aWriteAcceleratorList.begin(); p != m_aWriteAcceleratorList.end(); p++ )
        WriteAcceleratorItem( *p );
    */

    xCFG->ignorableWhitespace(::rtl::OUString());
    xCFG->endElement(AL_ELEMENT_ACCELERATORLIST);
    xCFG->ignorableWhitespace(::rtl::OUString());
    xCFG->endDocument();
}

//-----------------------------------------------
void AcceleratorConfigurationWriter::impl_ts_writeKeyCommandPair(const css::awt::KeyEvent&                                     aKey    ,
                                                                 const ::rtl::OUString&                                        sCommand,
                                                                 const css::uno::Reference< css::xml::sax::XDocumentHandler >& xConfig )
{
    AttributeListImpl*                                   pAttribs = new AttributeListImpl;
    css::uno::Reference< css::xml::sax::XAttributeList > xAttribs (static_cast< css::xml::sax::XAttributeList* >(pAttribs) , css::uno::UNO_QUERY_THROW);

    ::rtl::OUString sKey = m_rKeyMapping->mapCodeToIdentifier(aKey.KeyCode);
    // TODO check if key is empty!

    pAttribs->addAttribute(AL_ATTRIBUTE_KEYCODE, ATTRIBUTE_TYPE_CDATA, sKey    );
    pAttribs->addAttribute(AL_ATTRIBUTE_URL    , ATTRIBUTE_TYPE_CDATA, sCommand);

    if ((aKey.Modifiers & css::awt::KeyModifier::SHIFT) == css::awt::KeyModifier::SHIFT)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_SHIFT, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    if ((aKey.Modifiers & css::awt::KeyModifier::MOD1) == css::awt::KeyModifier::MOD1)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_MOD1, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    if ((aKey.Modifiers & css::awt::KeyModifier::MOD2) == css::awt::KeyModifier::MOD2)
        pAttribs->addAttribute(AL_ATTRIBUTE_MOD_MOD2, ATTRIBUTE_TYPE_CDATA, ::rtl::OUString::createFromAscii("true"));

    xConfig->ignorableWhitespace(::rtl::OUString());
    xConfig->startElement(AL_ELEMENT_ITEM, xAttribs);
    xConfig->ignorableWhitespace(::rtl::OUString());
    xConfig->endElement(AL_ELEMENT_ITEM);
    xConfig->ignorableWhitespace(::rtl::OUString());
}

} // namespace framework
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2019 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 *
 */

// CLASS HEADER

// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <iostream>
#include <unordered_map>

// INTERNAL INCLUDES
#include <dali/internal/accessibility/bridge/bridge-accessible.h>
#include <dali/internal/accessibility/bridge/bridge-action.h>
#include <dali/internal/accessibility/bridge/bridge-collection.h>
#include <dali/internal/accessibility/bridge/bridge-component.h>
#include <dali/internal/accessibility/bridge/bridge-object.h>
#include <dali/internal/accessibility/bridge/bridge-value.h>
#include <dali/internal/accessibility/bridge/bridge-text.h>
#include <dali/internal/accessibility/bridge/bridge-editable-text.h>

using namespace Dali::Accessibility;

class BridgeImpl : public virtual BridgeBase,
                   public BridgeAccessible,
                   public BridgeObject,
                   public BridgeComponent,
                   public BridgeCollection,
                   public BridgeAction,
                   public BridgeValue,
                   public BridgeText,
                   public BridgeEditableText
{
  DBus::DBusClient listenOnAtspiEnabledSignalClient;
  DBus::DBusClient registryClient, directReadingClient;
  bool screenReaderEnabled = false;
  bool isEnabled = false;
  bool isShown = false;
  std::unordered_map <int32_t, std::function<void(std::string)>> directReadingCallbacks;
  Dali::Actor highlightedActor;
  std::function<void(Dali::Actor)> highlightClearAction;

public:
  BridgeImpl()
  {
    listenOnAtspiEnabledSignalClient = DBus::DBusClient{ A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION };

    listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "ScreenReaderEnabled", [this]( bool res )
      {
        screenReaderEnabled = res;
        if( screenReaderEnabled || isEnabled )
        {
          ForceUp();
        }
        else
        {
          ForceDown();
        }
      }
    );

    listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "IsEnabled", [this]( bool res )
      {
        isEnabled = res;
        if( screenReaderEnabled || isEnabled )
        {
          ForceUp();
        }
        else
        {
          ForceDown();
        }
      }
    );
  }

  Consumed Emit( KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText ) override
  {
    if (!IsUp())
    {
      return Consumed::NO;
    }

    unsigned int evType = 0;

    switch( type )
    {
      case KeyEventType::KEY_PRESSED:
      {
        evType = 0;
        break;
      }
      case KeyEventType::KEY_RELEASED:
      {
        evType = 1;
        break;
      }
      default:
      {
        return Consumed::NO;
      }
    }
    auto m = registryClient.method< bool( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool > ) >( "NotifyListenersSync" );
    auto result = m.call( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool >{evType, 0, static_cast< int32_t >( keyCode ), 0, static_cast< int32_t >( timeStamp ), keyName, isText ? 1 : 0} );
    if( !result )
    {
      LOG() << result.getError().message;
      return Consumed::NO;
    }
    return std::get< 0 >( result ) ? Consumed::YES : Consumed::NO;
  }

  void Pause() override
  {
    auto r = directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).call( true );
    if (!r)
    {
      LOG() << "Direct reading command failed (" << r.getError().message << ")";
    }
  }

  void Resume() override
  {
    auto r = directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).call( false );
    if (!r)
    {
      LOG() << "Direct reading command failed (" << r.getError().message << ")";
    }
  }

  void Say( const std::string& text, bool discardable, std::function< void(std::string) > callback ) override
  {
    auto commandId = directReadingClient.method< DBus::ValueOrError< std::string, bool, int32_t >( std::string, bool ) > ( "ReadCommand" ).call( text, discardable );
    if ( !commandId )
    {
      LOG() << "Direct reading command failed (" << commandId.getError().message << ")";
    }
    else if( callback )
    {
      directReadingCallbacks.emplace( std::get< 2 >( commandId ), callback);
    }
  }

  void ForceDown() override
  {
    if (data)
    {
      if (data->currentlyHighlightedActor && data->highlightActor)
      {
        data->currentlyHighlightedActor.Remove(data->highlightActor);
      }
      data->currentlyHighlightedActor = {};
      data->highlightActor = {};
    }
    highlightedActor = {};
    highlightClearAction = {};
    BridgeAccessible::ForceDown();
    registryClient = {};
    directReadingClient = {};
    directReadingCallbacks.clear();
  }

  void Terminate() override
  {
    if (data)
    {
      data->currentlyHighlightedActor = {};
      data->highlightActor = {};
    }
    ForceDown();
    listenOnAtspiEnabledSignalClient = {};
    dbusServer = {};
    con = {};
  }

  ForceUpResult ForceUp() override
  {
    if( BridgeAccessible::ForceUp() == ForceUpResult::ALREADY_UP )
    {
      return ForceUpResult::ALREADY_UP;
    }

    BridgeObject::RegisterInterfaces();
    BridgeAccessible::RegisterInterfaces();
    BridgeComponent::RegisterInterfaces();
    BridgeCollection::RegisterInterfaces();
    BridgeAction::RegisterInterfaces();
    BridgeValue::RegisterInterfaces();
    BridgeText::RegisterInterfaces();
    BridgeEditableText::RegisterInterfaces();

    RegisterOnBridge( &application );

    registryClient = { AtspiDbusNameRegistry, AtspiDbusPathDec, AtspiDbusInterfaceDec, con };
    directReadingClient = DBus::DBusClient{ DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, con };
    directReadingClient.addSignal< void(int32_t, std::string) >( "ReadingStateChanged", [=]( int32_t id, std::string readingState )
      {
        auto it = directReadingCallbacks.find( id );
        if (it != directReadingCallbacks.end())
        {
          it->second( readingState );
          if (readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted")
            directReadingCallbacks.erase( it );
        }
      }
    );

    auto proxy = DBus::DBusClient{AtspiDbusNameRegistry, AtspiDbusPathRoot, AtspiDbusInterfaceSocket, con};
    Address root{"", "root"};
    auto res = proxy.method< Address( Address ) >( "Embed" ).call( root );
    if (!res)
    {
      LOG() << "Call to Embed failed: " << res.getError().message;
    }
    assert( res );
    application.parent.SetAddress( std::move( std::get< 0 >( res ) ) );
    if (isShown)
    {
      EmitActivate();
    }
    return ForceUpResult::JUST_STARTED;
  }

  void EmitActivate()
  {
    auto win = application.getActiveWindow();
    if (win)
    {
      win->Emit( WindowEvent::ACTIVATE, 0 );
    }
  }

  void EmitDeactivate()
  {
    auto win = application.getActiveWindow();
    if (win)
    {
      win->Emit( WindowEvent::DEACTIVATE, 0 );
    }
  }

  void ApplicationHidden() override
  {
    if ( isShown && IsUp() )
    {
      EmitDeactivate();
    }
    isShown = false;
  }

  void ApplicationShown() override
  {
    if ( !isShown && IsUp() )
    {
      EmitActivate();
    }
    isShown = true;
  }

  void Initialize() override
  {
    auto req = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION};
    auto p = req.property< bool >( "ScreenReaderEnabled" ).get();
    if( p )
    {
      screenReaderEnabled = std::get< 0 >( p );
    }
    p = req.property< bool >( "IsEnabled" ).get();
    if( p )
    {
      isEnabled = std::get< 0 >( p );
    }
    if( screenReaderEnabled || isEnabled )
    {
      ForceUp();
    }
  }

  bool GetScreenReaderEnabled()
  {
    return screenReaderEnabled;
  }

  bool GetIsEnabled()
  {
    return isEnabled;
  }

};

Bridge* Bridge::GetCurrentBridge()
{
  static BridgeImpl *bridge = new BridgeImpl;
  return bridge;
}

<commit_msg>[AT-SPI] Prevent crashing Say method when s-r is turned off<commit_after>/*
 * Copyright (c) 2019 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 *
 */

// CLASS HEADER

// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <iostream>
#include <unordered_map>

// INTERNAL INCLUDES
#include <dali/internal/accessibility/bridge/bridge-accessible.h>
#include <dali/internal/accessibility/bridge/bridge-action.h>
#include <dali/internal/accessibility/bridge/bridge-collection.h>
#include <dali/internal/accessibility/bridge/bridge-component.h>
#include <dali/internal/accessibility/bridge/bridge-object.h>
#include <dali/internal/accessibility/bridge/bridge-value.h>
#include <dali/internal/accessibility/bridge/bridge-text.h>
#include <dali/internal/accessibility/bridge/bridge-editable-text.h>

using namespace Dali::Accessibility;

class BridgeImpl : public virtual BridgeBase,
                   public BridgeAccessible,
                   public BridgeObject,
                   public BridgeComponent,
                   public BridgeCollection,
                   public BridgeAction,
                   public BridgeValue,
                   public BridgeText,
                   public BridgeEditableText
{
  DBus::DBusClient listenOnAtspiEnabledSignalClient;
  DBus::DBusClient registryClient, directReadingClient;
  bool screenReaderEnabled = false;
  bool isEnabled = false;
  bool isShown = false;
  std::unordered_map <int32_t, std::function<void(std::string)>> directReadingCallbacks;
  Dali::Actor highlightedActor;
  std::function<void(Dali::Actor)> highlightClearAction;

public:
  BridgeImpl()
  {
    listenOnAtspiEnabledSignalClient = DBus::DBusClient{ A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION };

    listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "ScreenReaderEnabled", [this]( bool res )
      {
        screenReaderEnabled = res;
        if( screenReaderEnabled || isEnabled )
        {
          ForceUp();
        }
        else
        {
          ForceDown();
        }
      }
    );

    listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "IsEnabled", [this]( bool res )
      {
        isEnabled = res;
        if( screenReaderEnabled || isEnabled )
        {
          ForceUp();
        }
        else
        {
          ForceDown();
        }
      }
    );
  }

  Consumed Emit( KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText ) override
  {
    if (!IsUp())
    {
      return Consumed::NO;
    }

    unsigned int evType = 0;

    switch( type )
    {
      case KeyEventType::KEY_PRESSED:
      {
        evType = 0;
        break;
      }
      case KeyEventType::KEY_RELEASED:
      {
        evType = 1;
        break;
      }
      default:
      {
        return Consumed::NO;
      }
    }
    auto m = registryClient.method< bool( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool > ) >( "NotifyListenersSync" );
    auto result = m.call( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool >{evType, 0, static_cast< int32_t >( keyCode ), 0, static_cast< int32_t >( timeStamp ), keyName, isText ? 1 : 0} );
    if( !result )
    {
      LOG() << result.getError().message;
      return Consumed::NO;
    }
    return std::get< 0 >( result ) ? Consumed::YES : Consumed::NO;
  }

  void Pause() override
  {
    if (!IsUp())
    {
      return;
    }

    auto r = directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).call( true );
    if (!r)
    {
      LOG() << "Direct reading command failed (" << r.getError().message << ")";
    }
  }

  void Resume() override
  {
    if (!IsUp())
    {
      return;
    }

    auto r = directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).call( false );
    if (!r)
    {
      LOG() << "Direct reading command failed (" << r.getError().message << ")";
    }
  }

  void Say( const std::string& text, bool discardable, std::function< void(std::string) > callback ) override
  {
    if (!IsUp())
    {
      return;
    }

    auto commandId = directReadingClient.method< DBus::ValueOrError< std::string, bool, int32_t >( std::string, bool ) > ( "ReadCommand" ).call( text, discardable );
    if ( !commandId )
    {
      LOG() << "Direct reading command failed (" << commandId.getError().message << ")";
    }
    else if( callback )
    {
      directReadingCallbacks.emplace( std::get< 2 >( commandId ), callback);
    }
  }

  void ForceDown() override
  {
    if (data)
    {
      if (data->currentlyHighlightedActor && data->highlightActor)
      {
        data->currentlyHighlightedActor.Remove(data->highlightActor);
      }
      data->currentlyHighlightedActor = {};
      data->highlightActor = {};
    }
    highlightedActor = {};
    highlightClearAction = {};
    BridgeAccessible::ForceDown();
    registryClient = {};
    directReadingClient = {};
    directReadingCallbacks.clear();
  }

  void Terminate() override
  {
    if (data)
    {
      data->currentlyHighlightedActor = {};
      data->highlightActor = {};
    }
    ForceDown();
    listenOnAtspiEnabledSignalClient = {};
    dbusServer = {};
    con = {};
  }

  ForceUpResult ForceUp() override
  {
    if( BridgeAccessible::ForceUp() == ForceUpResult::ALREADY_UP )
    {
      return ForceUpResult::ALREADY_UP;
    }

    BridgeObject::RegisterInterfaces();
    BridgeAccessible::RegisterInterfaces();
    BridgeComponent::RegisterInterfaces();
    BridgeCollection::RegisterInterfaces();
    BridgeAction::RegisterInterfaces();
    BridgeValue::RegisterInterfaces();
    BridgeText::RegisterInterfaces();
    BridgeEditableText::RegisterInterfaces();

    RegisterOnBridge( &application );

    registryClient = { AtspiDbusNameRegistry, AtspiDbusPathDec, AtspiDbusInterfaceDec, con };
    directReadingClient = DBus::DBusClient{ DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, con };
    directReadingClient.addSignal< void(int32_t, std::string) >( "ReadingStateChanged", [=]( int32_t id, std::string readingState )
      {
        auto it = directReadingCallbacks.find( id );
        if (it != directReadingCallbacks.end())
        {
          it->second( readingState );
          if (readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted")
            directReadingCallbacks.erase( it );
        }
      }
    );

    auto proxy = DBus::DBusClient{AtspiDbusNameRegistry, AtspiDbusPathRoot, AtspiDbusInterfaceSocket, con};
    Address root{"", "root"};
    auto res = proxy.method< Address( Address ) >( "Embed" ).call( root );
    if (!res)
    {
      LOG() << "Call to Embed failed: " << res.getError().message;
    }
    assert( res );
    application.parent.SetAddress( std::move( std::get< 0 >( res ) ) );
    if (isShown)
    {
      EmitActivate();
    }
    return ForceUpResult::JUST_STARTED;
  }

  void EmitActivate()
  {
    auto win = application.getActiveWindow();
    if (win)
    {
      win->Emit( WindowEvent::ACTIVATE, 0 );
    }
  }

  void EmitDeactivate()
  {
    auto win = application.getActiveWindow();
    if (win)
    {
      win->Emit( WindowEvent::DEACTIVATE, 0 );
    }
  }

  void ApplicationHidden() override
  {
    if ( isShown && IsUp() )
    {
      EmitDeactivate();
    }
    isShown = false;
  }

  void ApplicationShown() override
  {
    if ( !isShown && IsUp() )
    {
      EmitActivate();
    }
    isShown = true;
  }

  void Initialize() override
  {
    auto req = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION};
    auto p = req.property< bool >( "ScreenReaderEnabled" ).get();
    if( p )
    {
      screenReaderEnabled = std::get< 0 >( p );
    }
    p = req.property< bool >( "IsEnabled" ).get();
    if( p )
    {
      isEnabled = std::get< 0 >( p );
    }
    if( screenReaderEnabled || isEnabled )
    {
      ForceUp();
    }
  }

  bool GetScreenReaderEnabled()
  {
    return screenReaderEnabled;
  }

  bool GetIsEnabled()
  {
    return isEnabled;
  }

};

Bridge* Bridge::GetCurrentBridge()
{
  static BridgeImpl *bridge = new BridgeImpl;
  return bridge;
}

<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
#include "StarControl.h"
#include "RayControl.h"
#include "CameraBase.h"
#include "ActorBase.h"
#include "sys/SysControl.h"
#include "FileSystem.h"
#include "RenderManager.h"
#include "Texture.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//设置角色初始位置。以门处作为原点，三维坐标系vec3是向量
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//关闭游戏进程
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
			pAction->SetupSkillBulletPosition(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('9'))
	{
		CAction* pAction = m_pRole->OrceAction("skill08");
		if (pAction)
		{
			m_pRole->StopMove();
			pAction->SetupSkillBulletDirection(1);
		}

	}
	else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
	{
		g_Engine.pApp->Exit();
	}
	if(g_Engine.pInput->IsLBDown())
	{
		vec3 p0,p1;
		BlueRay::GetPlayerMouseDirection(p0,p1);
		vec3 vRetPoint,vRetNormal;
		int nS = -1;
		g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);

		if(-1 != nS)
		{
			m_pRole->MoveToPath(vRetPoint);
		}
	}
	for(int i = 0;i < 20;i++)
	{
		if(!m_vAIList[i]->IsMoveing())
		{
			vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);
			m_vAIList[i]->MoveToPath(vPos);
		}

		m_vAIList[i]->Update(ifps);
	}
	if (g_Engine.pInput->IsLBDown())	//shubiaozuojian
	{
		g_pSysControl->SetMouseGrab(1);
		m_pStarControl->Click();
	}
	if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC))
	{
		g_pSysControl->SetMouseGrab(0);
	}
	m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab());
	m_pCameraBase->Update(ifps);

	m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection());
	m_pRole->UpdateActor(ifps);
	m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset());

	vec3 x = m_pCameraBase->GetModelview().getRow3(0);
	vec3 y = m_pCameraBase->GetModelview().getRow3(1);
	vec3 z = m_pCameraBase->GetModelview().getRow3(2);

	mat4 r = mat4_identity;

	r.setColumn3(0, -x);	//
	r.setColumn3(1, z);		//
	r.setColumn3(2, y);		//

	m_pRole->UpdateTransform(r);

	m_pRole->Update(ifps);
	m_pSkillSystem->Update(ifps);

	m_pStarControl->Update(m_pCameraBase->GetPosition(), m_pCameraBase->GetDirection());

	return 1;
}

int CGameProcess::Render()
{
	////test
	//m_pTestHero->Render();
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(10.0f,0.0f,1.0f), vec4(1.0f,0.0f,0.0f,1.0f));
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,10.0f,1.0f), vec4(0.0f,1.0f,0.0f,1.0f));
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,0.0f,11.0f), vec4(0.0f,0.0f,1.0f,1.0f));
	////~test

	return 1;
}

int CGameProcess::KeyPress(unsigned int nKey)
{
	if (nKey == 'w')
	{
		//g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_FORWARD, 1);
	}
	else if (nKey == 's')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 1);
	}
	else if (nKey == 'a')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 1);
	}
	else if (nKey == 'd')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_MOVE_RIGHT, 1);
	}
	else if (nKey == 'q')
	{
		g_Engine.pControls->SetState(CControls::STATE_JUMP, 1);
	}
	else if (nKey == 'e')
	{
		g_Engine.pControls->SetState(CControls::STATE_CROUCH, 1);
	}
	else if (nKey == CApp::KEY_SHIFT)
	{
		g_Engine.pControls->SetState(CControls::STATE_RUN, 1);
	}
	return 0;
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
#include "StarControl.h"
#include "RayControl.h"
#include "CameraBase.h"
#include "ActorBase.h"
#include "sys/SysControl.h"
#include "FileSystem.h"
#include "RenderManager.h"
#include "Texture.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//设置角色初始位置。以门处作为原点，三维坐标系vec3是向量
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//关闭游戏进程
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{
	float ifps = g_Engine.pGame->GetIFps();

	if (g_Engine.pInput->IsKeyDown('1'))
	{
		CAction* pAction = m_pRole->OrceAction("attack02");
		if (pAction)
		{
			pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('2'))
	{
		CAction* pAction = m_pRole->OrceAction("skill01");
		if (pAction)
		{
			m_pRole->StopMove();
		}
	}
	else if (g_Engine.pInput->IsKeyDown('3'))
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CRoleBase* pTarget = NULL;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 15.0f)
				{
					pTarget = m_vAIList[i];
					break;
				}
			}
			if (pTarget)
			{
				CVector<int> vTarget;
				vTarget.Append(pTarget->GetRoleID());
				pAction->SetupSkillBulletTarget(vTarget);
				m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹
	{
		CAction* pAction = m_pRole->OrceAction("skill02");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
				{
					vTarget.Append(m_vAIList[i]->GetRoleID());
				}
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('5'))
	{
		CAction* pAction = m_pRole->OrceAction("skill03");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('6'))
	{
		CAction* pAction = m_pRole->OrceAction("skill06");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());

			}
			pAction->SetupSkillTargetPoint(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('7'))
	{
		CAction* pAction = m_pRole->OrceAction("skill05");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<int> vTarget;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vTarget.Append(m_vAIList[i]->GetRoleID());
			}
			if (!vTarget.Empty())
			{
				pAction->SetupSkillBulletTarget(vTarget);
			}
		}
	}
	else if (g_Engine.pInput->IsKeyDown('8'))
	{
		CAction* pAction = m_pRole->OrceAction("skill07");
		if (pAction)
		{
			m_pRole->StopMove();
			CVector<vec3> vPos;
			for (int i = 0; i < 20; i++)
			{
				float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
				if (l > 5.0f && l < 20.0f)
					vPos.Append(m_vAIList[i]->GetPosition());
			}
			pAction->SetupSkillBulletPosition(vPos);
		}
	}
	else if (g_Engine.pInput->IsKeyDown('9'))
	{
		CAction* pAction = m_pRole->OrceAction("skill08");
		if (pAction)
		{
			m_pRole->StopMove();
			pAction->SetupSkillBulletDirection(1);
		}

	}
	else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))
	{
		g_Engine.pApp->Exit();
	}
	if(g_Engine.pInput->IsLBDown())
	{
		vec3 p0,p1;
		BlueRay::GetPlayerMouseDirection(p0,p1);
		vec3 vRetPoint,vRetNormal;
		int nS = -1;
		g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);

		if(-1 != nS)
		{
			m_pRole->MoveToPath(vRetPoint);
		}
	}
	for(int i = 0;i < 20;i++)
	{
		if(!m_vAIList[i]->IsMoveing())
		{
			vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);
			m_vAIList[i]->MoveToPath(vPos);
		}

		m_vAIList[i]->Update(ifps);
	}
	if (g_Engine.pInput->IsLBDown())	//shubiaozuojian
	{
		g_pSysControl->SetMouseGrab(1);
		m_pStarControl->Click();
	}
	if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC))
	{
		g_pSysControl->SetMouseGrab(0);
	}
	m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab());
	m_pCameraBase->Update(ifps);

	m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection());
	m_pRole->UpdateActor(ifps);
	m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset());

	vec3 x = m_pCameraBase->GetModelview().getRow3(0);
	vec3 y = m_pCameraBase->GetModelview().getRow3(1);
	vec3 z = m_pCameraBase->GetModelview().getRow3(2);

	mat4 r = mat4_identity;

	r.setColumn3(0, -x);	//
	r.setColumn3(1, z);		//
	r.setColumn3(2, y);		//

	m_pRole->UpdateTransform(r);

	m_pRole->Update(ifps);
	m_pSkillSystem->Update(ifps);

	m_pStarControl->Update(m_pCameraBase->GetPosition(), m_pCameraBase->GetDirection());

	return 1;
}

int CGameProcess::Render()
{
	////test
	//m_pTestHero->Render();
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(10.0f,0.0f,1.0f), vec4(1.0f,0.0f,0.0f,1.0f));
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,10.0f,1.0f), vec4(0.0f,1.0f,0.0f,1.0f));
	//g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,0.0f,11.0f), vec4(0.0f,0.0f,1.0f,1.0f));
	////~test

	return 1;
}

int CGameProcess::KeyPress(unsigned int nKey)
{
	if (nKey == 'w')
	{
		//g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_FORWARD, 1);
	}
	else if (nKey == 's')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 1);
	}
	else if (nKey == 'a')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 1);
	}
	else if (nKey == 'd')
	{
		g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1);
		g_Engine.pControls->SetState(CControls::STATE_MOVE_RIGHT, 1);
	}
	else if (nKey == 'q')
	{
		g_Engine.pControls->SetState(CControls::STATE_JUMP, 1);
	}
	else if (nKey == 'e')
	{
		g_Engine.pControls->SetState(CControls::STATE_CROUCH, 1);
	}
	else if (nKey == CApp::KEY_SHIFT)
	{
		g_Engine.pControls->SetState(CControls::STATE_RUN, 1);
	}
	return 1;

}
<|endoftext|>


<commit_before>#include "KeyGrabber.h"

#include <string>

KeyGrabber *KeyGrabber::instance = NULL;

KeyGrabber *KeyGrabber::Instance() {
    if (instance == NULL) {
        instance = new KeyGrabber();
    }

    return instance;
}

bool KeyGrabber::Hook() {
    _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,
        LowLevelMouseProc, NULL, NULL);

    _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,
        LowLevelKeyboardProc, NULL, NULL);

    return _mouseHook && _keyHook;
}

bool KeyGrabber::Unhook() {
    BOOL unMouse = UnhookWindowsHookEx(_mouseHook);
    BOOL unKey = UnhookWindowsHookEx(_keyHook);
    return unMouse && unKey;
}

void KeyGrabber::Grab(HWND hwnd) {
    _updateHwnd = hwnd;
    Hook();
}

bool KeyGrabber::IsModifier(DWORD vk) {
    switch (vk) {
    case VK_MENU:
    case VK_LMENU:
    case VK_RMENU:
    case VK_CONTROL:
    case VK_LCONTROL:
    case VK_RCONTROL:
    case VK_SHIFT:
    case VK_LSHIFT:
    case VK_RSHIFT:
    case VK_LWIN:
    case VK_RWIN:
        return true;
    }
    return false;
}

int KeyGrabber::Modifiers() {
    int mods = 0;
    mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;
    mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;
    mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;
    mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;
    mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;
    return mods;
}

std::wstring KeyGrabber::ModString(int modifiers) {
    std::wstring str = L"";
    if (modifiers & HKM_MOD_ALT) {
        str += VKToString(VK_MENU) + L" + ";
    }
    if (modifiers & HKM_MOD_CTRL) {
        str += VKToString(VK_CONTROL) + L" + ";
    }
    if (modifiers & HKM_MOD_SHF) {
        str += VKToString(VK_SHIFT) + L" + ";
    }
    if (modifiers & HKM_MOD_WIN) {
        str += L"Win + ";
    }

    return str;
}

std::wstring KeyGrabber::VKToString(
    unsigned int vk, bool extendedKey, bool distinguishLeftRight) {

    BOOL dontCare = distinguishLeftRight ? FALSE : TRUE;
    int extended = extendedKey ? 0x1 : 0x0;

    unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
    scanCode = scanCode << 16;
    scanCode |= extended << 24;
    scanCode |= dontCare << 25;
    wchar_t buf[256] = {};
    GetKeyNameText(scanCode, buf, 256);
    return std::wstring(buf);
}

LRESULT CALLBACK
KeyGrabber::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0) {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
        KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam;

        DWORD vk = kbInfo->vkCode;
        if (IsModifier(kbInfo->vkCode)) {
            /* Ignore modifier keys */
            return CallNextHookEx(NULL, nCode, wParam, lParam);
        }

        /* GetKeyNameText expects the following:
         * 16-23: scan code
         *    24: extended key flag
         *    25: 'do not care' bit (don't distinguish between L/R keys) */
        BOOL dontCare = TRUE;
        LONG newlParam;
        newlParam = (kbInfo->scanCode << 16);
        newlParam |= (kbInfo->flags & 0x1) << 24;
        newlParam |= dontCare << 25;
        if (kbInfo->vkCode == VK_RSHIFT) {
            /* For some reason, the right shift key ends up having its extended
             * key flag set and then prints the wrong thing. This doesn't matter
             * here, but we'll fix it in case we need this info later. */
            newlParam ^= 0x1000000;
        }

        wchar_t buf[256] = {};
        GetKeyNameText(newlParam, buf, 256);
        int mods = Modifiers();
        std::wstring modStr = ModString(mods) + buf;
        SetWindowText(_updateHwnd, modStr.c_str());

        /* Prevent other applications from receiving this event */
        return (LRESULT) 1;
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0) {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    return KeyGrabber::instance->MouseProc(nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    return KeyGrabber::instance->KeyProc(nCode, wParam, lParam);
}<commit_msg>Handle esc key<commit_after>#include "KeyGrabber.h"

#include <string>

KeyGrabber *KeyGrabber::instance = NULL;

KeyGrabber *KeyGrabber::Instance() {
    if (instance == NULL) {
        instance = new KeyGrabber();
    }

    return instance;
}

bool KeyGrabber::Hook() {
    _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,
        LowLevelMouseProc, NULL, NULL);

    _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,
        LowLevelKeyboardProc, NULL, NULL);

    return _mouseHook && _keyHook;
}

bool KeyGrabber::Unhook() {
    BOOL unMouse = UnhookWindowsHookEx(_mouseHook);
    BOOL unKey = UnhookWindowsHookEx(_keyHook);
    return unMouse && unKey;
}

void KeyGrabber::Grab(HWND hwnd) {
    _updateHwnd = hwnd;
    Hook();
}

bool KeyGrabber::IsModifier(DWORD vk) {
    switch (vk) {
    case VK_MENU:
    case VK_LMENU:
    case VK_RMENU:
    case VK_CONTROL:
    case VK_LCONTROL:
    case VK_RCONTROL:
    case VK_SHIFT:
    case VK_LSHIFT:
    case VK_RSHIFT:
    case VK_LWIN:
    case VK_RWIN:
        return true;
    }
    return false;
}

int KeyGrabber::Modifiers() {
    int mods = 0;
    mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;
    mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;
    mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;
    mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;
    mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;
    return mods;
}

std::wstring KeyGrabber::ModString(int modifiers) {
    std::wstring str = L"";
    if (modifiers & HKM_MOD_ALT) {
        str += VKToString(VK_MENU) + L" + ";
    }
    if (modifiers & HKM_MOD_CTRL) {
        str += VKToString(VK_CONTROL) + L" + ";
    }
    if (modifiers & HKM_MOD_SHF) {
        str += VKToString(VK_SHIFT) + L" + ";
    }
    if (modifiers & HKM_MOD_WIN) {
        str += L"Win + ";
    }

    return str;
}

std::wstring KeyGrabber::VKToString(
    unsigned int vk, bool extendedKey, bool distinguishLeftRight) {

    BOOL dontCare = distinguishLeftRight ? FALSE : TRUE;
    int extended = extendedKey ? 0x1 : 0x0;

    unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
    scanCode = scanCode << 16;
    scanCode |= extended << 24;
    scanCode |= dontCare << 25;
    wchar_t buf[256] = {};
    GetKeyNameText(scanCode, buf, 256);
    return std::wstring(buf);
}

LRESULT CALLBACK
KeyGrabber::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0) {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
        KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam;

        DWORD vk = kbInfo->vkCode;
        if (IsModifier(kbInfo->vkCode)) {
            /* Ignore modifier keys */
            return CallNextHookEx(NULL, nCode, wParam, lParam);
        }

        /* GetKeyNameText expects the following:
         * 16-23: scan code
         *    24: extended key flag
         *    25: 'do not care' bit (don't distinguish between L/R keys) */
        BOOL dontCare = TRUE;
        LONG newlParam;
        newlParam = (kbInfo->scanCode << 16);
        newlParam |= (kbInfo->flags & 0x1) << 24;
        newlParam |= dontCare << 25;
        if (kbInfo->vkCode == VK_RSHIFT) {
            /* For some reason, the right shift key ends up having its extended
             * key flag set and then prints the wrong thing. This doesn't matter
             * here, but we'll fix it in case we need this info later. */
            newlParam ^= 0x1000000;
        }

        wchar_t buf[256] = {};
        GetKeyNameText(newlParam, buf, 256);
        int mods = Modifiers();
        std::wstring modStr = ModString(mods) + buf;

        if (vk == VK_ESCAPE && mods == 0) {
            /* Pass escape through to let the user cancel the operation */
            return CallNextHookEx(NULL, nCode, wParam, lParam);
        }

        SetWindowText(_updateHwnd, modStr.c_str());

        /* Prevent other applications from receiving this event */
        return (LRESULT) 1;
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0) {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    return KeyGrabber::instance->MouseProc(nCode, wParam, lParam);
}

LRESULT CALLBACK
KeyGrabber::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    return KeyGrabber::instance->KeyProc(nCode, wParam, lParam);
}<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_CONTAINER_HH
#define DUNE_STUFF_LA_CONTAINER_HH

#include "container/interfaces.hh"
#include "container/common.hh"
#include "container/eigen.hh"
#include "container/istl.hh"

namespace Dune {
namespace Stuff {
namespace LA {

template< class ScalarType, ChooseBackend backend = default_backend >
struct Container;

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::common_dense >
{
  typedef CommonDenseVector< ScalarType > VectorType;
  typedef CommonDenseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., common_dense >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::eigen_dense >
{
  typedef EigenDenseVector< ScalarType > VectorType;
  typedef EigenDenseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., eigen_dense >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::eigen_sparse >
{
  typedef EigenDenseVector< ScalarType >          VectorType;
  typedef EigenRowMajorSparseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., eigen_sparse >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::istl_sparse >
{
  typedef IstlDenseVector< ScalarType >           VectorType;
  typedef IstlRowMajorSparseMatrix< ScalarType >  MatrixType;
}; // struct Container< ..., istl_sparse >

//template< class Traits, size_t domainDim, size_t rangeDim, size_t rangeDimCols > class SpaceInterface
template < class Space >
typename Space::RangeFieldType communicated_dot(const Dune::Stuff::LA::IstlDenseVector<typename Space::RangeFieldType>& vector,
                                            const Dune::Stuff::LA::IstlDenseVector<typename Space::RangeFieldType>& source,
                                            const Space& space) {
  typename Space::RangeFieldType result = typename Space::RangeFieldType(0);
  space.communicator().dot(vector.backend(), source.backend(), result);
  return result;
}

template < template <class> class VectorImp, class Space >
typename Space::RangeFieldType communicated_dot(const VectorImp<typename Space::RangeFieldType>& vector,
                                            const VectorImp<typename Space::RangeFieldType>& source,
                                            const Space& /*space*/) {
  auto result = vector.dot(source);
  DSC_LOG_DEBUG_0 << "communicated_dot does not account for overlapping dofs with non-ISTL vector types atm\n";
  return MPIHelper::getCollectiveCommunication().sum(result);
}

} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_LA_CONTAINER_HH
<commit_msg>[la.container] adds ensure_parallel_dof_consistency method<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_CONTAINER_HH
#define DUNE_STUFF_LA_CONTAINER_HH

#include "container/interfaces.hh"
#include "container/common.hh"
#include "container/eigen.hh"
#include "container/istl.hh"

namespace Dune {
namespace Stuff {
namespace LA {

template< class ScalarType, ChooseBackend backend = default_backend >
struct Container;

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::common_dense >
{
  typedef CommonDenseVector< ScalarType > VectorType;
  typedef CommonDenseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., common_dense >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::eigen_dense >
{
  typedef EigenDenseVector< ScalarType > VectorType;
  typedef EigenDenseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., eigen_dense >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::eigen_sparse >
{
  typedef EigenDenseVector< ScalarType >          VectorType;
  typedef EigenRowMajorSparseMatrix< ScalarType > MatrixType;
}; // struct Container< ..., eigen_sparse >

template< class ScalarType >
struct Container< ScalarType, ChooseBackend::istl_sparse >
{
  typedef IstlDenseVector< ScalarType >           VectorType;
  typedef IstlRowMajorSparseMatrix< ScalarType >  MatrixType;
}; // struct Container< ..., istl_sparse >

//template< class Traits, size_t domainDim, size_t rangeDim, size_t rangeDimCols > class SpaceInterface
template < class Space >
typename Space::RangeFieldType communicated_dot(const Dune::Stuff::LA::IstlDenseVector<typename Space::RangeFieldType>& vector,
                                            const Dune::Stuff::LA::IstlDenseVector<typename Space::RangeFieldType>& source,
                                            const Space& space) {
  typename Space::RangeFieldType result = typename Space::RangeFieldType(0);
  space.communicator().dot(vector.backend(), source.backend(), result);
  return result;
}

template < template <class> class VectorImp, class Space >
typename Space::RangeFieldType communicated_dot(const VectorImp<typename Space::RangeFieldType>& vector,
                                            const VectorImp<typename Space::RangeFieldType>& source,
                                            const Space& /*space*/) {
  auto result = vector.dot(source);
  DSC_LOG_DEBUG_0 << "communicated_dot does not account for overlapping dofs with non-ISTL vector types atm\n";
  return MPIHelper::getCollectiveCommunication().sum(result);
}

template < class Space >
void ensure_parallel_dof_consistency(Dune::Stuff::LA::IstlDenseVector<typename Space::RangeFieldType>& vector,
                                     const Space& space) {
  space.communicator().copyOwnerToAll(vector.backend(), vector.backend());
}

template < template <class> class VectorImp, class Space >
void ensure_parallel_dof_consistency(VectorImp<typename Space::RangeFieldType>& /*vector*/,
                                     const Space& /*space*/) {
  DSC_LOG_DEBUG_0 << "parallel dof consistency can only be ensured for ISTL vectors atm\n";
}

} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_LA_CONTAINER_HH
<|endoftext|>