<commit_before>/*************************************************************************
 *
 *  $RCSfile: ctr_pipe.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: jbu $ $Date: 2001-06-22 16:32:56 $
 *
 *  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 EXPRESSED 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): _______________________________________
 *
 *
 ************************************************************************/

#include "connector.hxx"

using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::connection;

namespace stoc_connector {

    PipeConnection::PipeConnection( const OUString &s, const OUString & sConnectionDescription ) :
        m_nStatus( 0 ),
        m_sDescription( sConnectionDescription )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
        // make it unique
        m_sDescription += OUString::createFromAscii( ",uniqueValue=" );
        m_sDescription += OUString::valueOf( (sal_Int64) &m_pipe , 10 );
    }

    PipeConnection::~PipeConnection()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    sal_Int32 PipeConnection::read( Sequence < sal_Int8 > & aReadBytes , sal_Int32 nBytesToRead )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( aReadBytes.getLength() != nBytesToRead )
            {
                aReadBytes.realloc( nBytesToRead );
            }
            return m_pipe.read( aReadBytes.getArray()  , aReadBytes.getLength() );
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::write( const Sequence < sal_Int8 > &seq )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( m_pipe.write( seq.getConstArray() , seq.getLength() ) != seq.getLength() )
            {
                throw IOException();
            }
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::flush( )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {

    }

    void PipeConnection::close()
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        // ensure that close is called only once
        if(1 == osl_incrementInterlockedCount( (&m_nStatus) ) )
        {
            m_pipe.close();
        }
    }

    OUString PipeConnection::getDescription()
            throw( ::com::sun::star::uno::RuntimeException)
    {
        return m_sDescription;
    }

}

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.130); FILE MERGED 2005/09/05 17:14:47 rt 1.3.130.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ctr_pipe.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:29:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "connector.hxx"

using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::connection;

namespace stoc_connector {

    PipeConnection::PipeConnection( const OUString &s, const OUString & sConnectionDescription ) :
        m_nStatus( 0 ),
        m_sDescription( sConnectionDescription )
    {
        g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
        // make it unique
        m_sDescription += OUString::createFromAscii( ",uniqueValue=" );
        m_sDescription += OUString::valueOf( (sal_Int64) &m_pipe , 10 );
    }

    PipeConnection::~PipeConnection()
    {
        g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
    }

    sal_Int32 PipeConnection::read( Sequence < sal_Int8 > & aReadBytes , sal_Int32 nBytesToRead )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( aReadBytes.getLength() != nBytesToRead )
            {
                aReadBytes.realloc( nBytesToRead );
            }
            return m_pipe.read( aReadBytes.getArray()  , aReadBytes.getLength() );
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::write( const Sequence < sal_Int8 > &seq )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        if( ! m_nStatus )
        {
            if( m_pipe.write( seq.getConstArray() , seq.getLength() ) != seq.getLength() )
            {
                throw IOException();
            }
        }
        else {
            throw IOException();
        }
    }

    void PipeConnection::flush( )
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {

    }

    void PipeConnection::close()
            throw(::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException)
    {
        // ensure that close is called only once
        if(1 == osl_incrementInterlockedCount( (&m_nStatus) ) )
        {
            m_pipe.close();
        }
    }

    OUString PipeConnection::getDescription()
            throw( ::com::sun::star::uno::RuntimeException)
    {
        return m_sDescription;
    }

}

<|endoftext|>


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

#include "common/node_bindings.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/base_paths.h"
#include "base/path_service.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"

#if defined(OS_WIN)
#include "base/strings/utf_string_conversions.h"
#endif

#include "common/v8/node_common.h"

using content::BrowserThread;

// Forward declaration of internal node functions.
namespace node {
void Init(int*, const char**, int*, const char***);
void Load(Environment* env);
void SetupProcessObject(Environment*, int, const char* const*, int,
                        const char* const*);
}

namespace atom {

namespace {

// Empty callback for async handle.
void UvNoOp(uv_async_t* handle, int status) {
}

// Convert the given vector to an array of C-strings. The strings in the
// returned vector are only guaranteed valid so long as the vector of strings
// is not modified.
scoped_ptr<const char*[]> StringVectorToArgArray(
    const std::vector<std::string>& vector) {
  scoped_ptr<const char*[]> array(new const char*[vector.size()]);
  for (size_t i = 0; i < vector.size(); ++i)
    array[i] = vector[i].c_str();
  return array.Pass();
}

#if defined(OS_WIN)
std::vector<std::string> String16VectorToStringVector(
    const std::vector<string16>& vector) {
  std::vector<std::string> utf8_vector;
  utf8_vector.reserve(vector.size());
  for (size_t i = 0; i < vector.size(); ++i)
    utf8_vector.push_back(UTF16ToUTF8(vector[i]));
  return utf8_vector;
}
#endif

}  // namespace

node::Environment* global_env = NULL;

NodeBindings::NodeBindings(bool is_browser)
    : is_browser_(is_browser),
      message_loop_(NULL),
      uv_loop_(uv_default_loop()),
      embed_closed_(false) {
}

NodeBindings::~NodeBindings() {
  // Quit the embed thread.
  embed_closed_ = true;
  uv_sem_post(&embed_sem_);
  WakeupEmbedThread();

  // Wait for everything to be done.
  uv_thread_join(&embed_thread_);
  message_loop_->RunUntilIdle();

  // Clear uv.
  uv_sem_destroy(&embed_sem_);
  uv_timer_stop(&idle_timer_);
}

void NodeBindings::Initialize() {
  // Init idle GC for browser.
  if (is_browser_) {
    uv_timer_init(uv_default_loop(), &idle_timer_);
    uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);
  }

  // Open node's error reporting system for browser process.
  node::g_standalone_mode = is_browser_;
  node::g_upstream_node_mode = false;

  // Init node.
  // (we assume it would not node::Init would not modify the parameters under
  // embedded mode).
  node::Init(NULL, NULL, NULL, NULL);
}

node::Environment* NodeBindings::CreateEnvironment(
    v8::Handle<v8::Context> context) {
  std::vector<std::string> args =
#if defined(OS_WIN)
      String16VectorToStringVector(CommandLine::ForCurrentProcess()->argv());
#else
      CommandLine::ForCurrentProcess()->argv();
#endif

  // Feed node the path to initialization script.
  base::FilePath exec_path(CommandLine::ForCurrentProcess()->argv()[0]);
  PathService::Get(base::FILE_EXE, &exec_path);
  base::FilePath resources_path =
#if defined(OS_MACOSX)
      is_browser_ ? exec_path.DirName().DirName().Append("Resources") :
                    exec_path.DirName().DirName().DirName().DirName().DirName()
                             .Append("Resources");
#else
      exec_path.DirName().AppendASCII("resources");
#endif
  base::FilePath script_path =
      resources_path.AppendASCII(is_browser_ ? "browser" : "renderer")
                    .AppendASCII("lib")
                    .AppendASCII("init.js");
  std::string script_path_str = script_path.AsUTF8Unsafe();
  args.insert(args.begin() + 1, script_path_str.c_str());

  // Convert string vector to const char* array.
  scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args);

  // Construct the parameters that passed to node::CreateEnvironment:
  v8::Isolate* isolate = context->GetIsolate();
  int argc = args.size();
  const char** argv = c_argv.get();
  int exec_argc = 0;
  const char** exec_argv = NULL;

  using namespace v8;  // NOLINT
  using namespace node;  // NOLINT

  // Following code are stripped from node::CreateEnvironment in node.cc:
  HandleScope handle_scope(isolate);
  Context::Scope context_scope(context);

  Environment* env = Environment::New(context);

  uv_check_init(env->event_loop(), env->immediate_check_handle());
  uv_unref(
      reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
  uv_idle_init(env->event_loop(), env->immediate_idle_handle());

  uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
  uv_check_init(env->event_loop(), env->idle_check_handle());
  uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
  uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));

  Local<FunctionTemplate> process_template = FunctionTemplate::New();
  process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));

  Local<Object> process_object = process_template->GetFunction()->NewInstance();
  env->set_process_object(process_object);

  SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
  Load(env);

  return env;
}

void NodeBindings::PrepareMessageLoop() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Add dummy handle for libuv, otherwise libuv would quit when there is
  // nothing to do.
  uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);

  // Start worker that will interrupt main loop when having uv events.
  uv_sem_init(&embed_sem_, 0);
  uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
}

void NodeBindings::RunMessageLoop() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // The MessageLoop should have been created, remember the one in main thread.
  message_loop_ = base::MessageLoop::current();

  // Run uv loop for once to give the uv__io_poll a chance to add all events.
  UvRunOnce();
}

void NodeBindings::UvRunOnce() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Enter node context while dealing with uv events.
  v8::HandleScope handle_scope(node_isolate);
  v8::Context::Scope context_scope(global_env->context());

  // Deal with uv events.
  int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));
  if (r == 0 || uv_loop_->stop_flag != 0)
    message_loop_->QuitWhenIdle();  // Quit from uv.

  // Tell the worker thread to continue polling.
  uv_sem_post(&embed_sem_);
}

void NodeBindings::WakeupMainThread() {
  DCHECK(message_loop_);
  message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
                                                base::Unretained(this)));
}

void NodeBindings::WakeupEmbedThread() {
  uv_async_send(&dummy_uv_handle_);
}

// static
void NodeBindings::EmbedThreadRunner(void *arg) {
  NodeBindings* self = static_cast<NodeBindings*>(arg);

  while (!self->embed_closed_) {
    // Wait for the main loop to deal with events.
    uv_sem_wait(&self->embed_sem_);

    self->PollEvents();

    // Deal with event in main thread.
    self->WakeupMainThread();
  }
}

// static
void NodeBindings::IdleCallback(uv_timer_t*, int) {
  v8::V8::IdleNotification();
}

}  // namespace atom
<commit_msg>Fix invoking non-exist method when quiting.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "common/node_bindings.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/base_paths.h"
#include "base/path_service.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"

#if defined(OS_WIN)
#include "base/strings/utf_string_conversions.h"
#endif

#include "common/v8/node_common.h"

using content::BrowserThread;

// Forward declaration of internal node functions.
namespace node {
void Init(int*, const char**, int*, const char***);
void Load(Environment* env);
void SetupProcessObject(Environment*, int, const char* const*, int,
                        const char* const*);
}

namespace atom {

namespace {

// Empty callback for async handle.
void UvNoOp(uv_async_t* handle, int status) {
}

// Convert the given vector to an array of C-strings. The strings in the
// returned vector are only guaranteed valid so long as the vector of strings
// is not modified.
scoped_ptr<const char*[]> StringVectorToArgArray(
    const std::vector<std::string>& vector) {
  scoped_ptr<const char*[]> array(new const char*[vector.size()]);
  for (size_t i = 0; i < vector.size(); ++i)
    array[i] = vector[i].c_str();
  return array.Pass();
}

#if defined(OS_WIN)
std::vector<std::string> String16VectorToStringVector(
    const std::vector<string16>& vector) {
  std::vector<std::string> utf8_vector;
  utf8_vector.reserve(vector.size());
  for (size_t i = 0; i < vector.size(); ++i)
    utf8_vector.push_back(UTF16ToUTF8(vector[i]));
  return utf8_vector;
}
#endif

}  // namespace

node::Environment* global_env = NULL;

NodeBindings::NodeBindings(bool is_browser)
    : is_browser_(is_browser),
      message_loop_(NULL),
      uv_loop_(uv_default_loop()),
      embed_closed_(false) {
}

NodeBindings::~NodeBindings() {
  // Quit the embed thread.
  embed_closed_ = true;
  uv_sem_post(&embed_sem_);
  WakeupEmbedThread();

  // Wait for everything to be done.
  uv_thread_join(&embed_thread_);
  message_loop_->RunUntilIdle();

  // Clear uv.
  uv_sem_destroy(&embed_sem_);
  uv_timer_stop(&idle_timer_);
}

void NodeBindings::Initialize() {
  // Init idle GC for browser.
  if (is_browser_) {
    uv_timer_init(uv_default_loop(), &idle_timer_);
    uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);
  }

  // Open node's error reporting system for browser process.
  node::g_standalone_mode = is_browser_;
  node::g_upstream_node_mode = false;

  // Init node.
  // (we assume it would not node::Init would not modify the parameters under
  // embedded mode).
  node::Init(NULL, NULL, NULL, NULL);
}

node::Environment* NodeBindings::CreateEnvironment(
    v8::Handle<v8::Context> context) {
  std::vector<std::string> args =
#if defined(OS_WIN)
      String16VectorToStringVector(CommandLine::ForCurrentProcess()->argv());
#else
      CommandLine::ForCurrentProcess()->argv();
#endif

  // Feed node the path to initialization script.
  base::FilePath exec_path(CommandLine::ForCurrentProcess()->argv()[0]);
  PathService::Get(base::FILE_EXE, &exec_path);
  base::FilePath resources_path =
#if defined(OS_MACOSX)
      is_browser_ ? exec_path.DirName().DirName().Append("Resources") :
                    exec_path.DirName().DirName().DirName().DirName().DirName()
                             .Append("Resources");
#else
      exec_path.DirName().AppendASCII("resources");
#endif
  base::FilePath script_path =
      resources_path.AppendASCII(is_browser_ ? "browser" : "renderer")
                    .AppendASCII("lib")
                    .AppendASCII("init.js");
  std::string script_path_str = script_path.AsUTF8Unsafe();
  args.insert(args.begin() + 1, script_path_str.c_str());

  // Convert string vector to const char* array.
  scoped_ptr<const char*[]> c_argv = StringVectorToArgArray(args);

  // Construct the parameters that passed to node::CreateEnvironment:
  v8::Isolate* isolate = context->GetIsolate();
  int argc = args.size();
  const char** argv = c_argv.get();
  int exec_argc = 0;
  const char** exec_argv = NULL;

  using namespace v8;  // NOLINT
  using namespace node;  // NOLINT

  // Following code are stripped from node::CreateEnvironment in node.cc:
  HandleScope handle_scope(isolate);
  Context::Scope context_scope(context);

  Environment* env = Environment::New(context);

  uv_check_init(env->event_loop(), env->immediate_check_handle());
  uv_unref(
      reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
  uv_idle_init(env->event_loop(), env->immediate_idle_handle());

  uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
  uv_check_init(env->event_loop(), env->idle_check_handle());
  uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
  uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));

  Local<FunctionTemplate> process_template = FunctionTemplate::New();
  process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));

  Local<Object> process_object = process_template->GetFunction()->NewInstance();
  env->set_process_object(process_object);

  SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
  Load(env);

  return env;
}

void NodeBindings::PrepareMessageLoop() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Add dummy handle for libuv, otherwise libuv would quit when there is
  // nothing to do.
  uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);

  // Start worker that will interrupt main loop when having uv events.
  uv_sem_init(&embed_sem_, 0);
  uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
}

void NodeBindings::RunMessageLoop() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // The MessageLoop should have been created, remember the one in main thread.
  message_loop_ = base::MessageLoop::current();

  // Run uv loop for once to give the uv__io_poll a chance to add all events.
  UvRunOnce();
}

void NodeBindings::UvRunOnce() {
  DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Enter node context while dealing with uv events.
  v8::HandleScope handle_scope(node_isolate);
  v8::Context::Scope context_scope(global_env->context());

  // Deal with uv events.
  int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));
  if (r == 0 || uv_loop_->stop_flag != 0)
    message_loop_->QuitWhenIdle();  // Quit from uv.

  // Tell the worker thread to continue polling.
  uv_sem_post(&embed_sem_);
}

void NodeBindings::WakeupMainThread() {
  DCHECK(message_loop_);
  message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
                                                base::Unretained(this)));
}

void NodeBindings::WakeupEmbedThread() {
  uv_async_send(&dummy_uv_handle_);
}

// static
void NodeBindings::EmbedThreadRunner(void *arg) {
  NodeBindings* self = static_cast<NodeBindings*>(arg);

  while (true) {
    // Wait for the main loop to deal with events.
    uv_sem_wait(&self->embed_sem_);
    if (self->embed_closed_)
      break;

    // Wait for something to happen in uv loop.
    // Note that the PollEvents() is implemented by derived classes, so when
    // this class is being destructed the PollEvents() would not be available
    // anymore. Because of it we must make sure we only invoke PollEvents()
    // when this class is alive.
    self->PollEvents();
    if (self->embed_closed_)
      break;

    // Deal with event in main thread.
    self->WakeupMainThread();
  }
}

// static
void NodeBindings::IdleCallback(uv_timer_t*, int) {
  v8::V8::IdleNotification();
}

}  // namespace atom
<|endoftext|>


<commit_before><commit_msg>Simplify this condition a bit<commit_after><|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <test_common.h>

#include <vistk/utilities/path.h>

#include <iostream>
#include <string>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#include <cstdlib>

int
main(int argc, char* argv[])
{
  if (argc != 3)
  {
    TEST_ERROR("Expected two arguments");

    return EXIT_FAILURE;
  }

#if defined(_WIN32) || defined(_WIN64)
  typedef HMODULE library_t;
  typedef std::wstring module_path_t;
#else
  typedef void* library_t;
  typedef std::string module_path_t;
#endif

  std::string const library = argv[1];
  vistk::path_t const path = argv[2];
  module_path_t const library_path = path.native();

  library_t handle = NULL;

#if defined(_WIN32) || defined(_WIN64)
  handle = LoadLibraryW(library_path.c_str());
#else
  handle = dlopen(library_path.c_str(), RTLD_NOW);
#endif

  if (!handle)
  {
    std::string error;

#if defined(_WIN32) || defined(_WIN64)
    {
      DWORD const err_code = GetLastError();
      LPTSTR* str;

      DWORD const ret = FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        err_code,
        0,
        static_cast<LPTSTR>(&str),
        0,
        NULL);

      if (!ret)
      {
        TEST_ERROR("Could not get error string from system");

        return EXIT_FAILURE;
      }

      error = str;

      LocalFree(str);
    }
#else
    error = dlerror();
#endif

    TEST_ERROR("Failed to open library " << library << ": " << error);
  }
  else
  {
#if defined(_WIN32) || defined(_WIN64)
    int const ret = FreeLibrary(handle);

    if (!ret)
    {
      std::string error;

      {
        DWORD const err_code = GetLastError();
        LPTSTR* str;

        DWORD const ret = FormatMessage(
          FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
          NULL,
          err_code,
          0,
          static_cast<LPTSTR>(&str),
          0,
          NULL);

        if (!ret)
        {
          TEST_ERROR("Could not get error string from system");

          return EXIT_FAILURE;
        }

        error = str;

        LocalFree(str);
      }

      TEST_ERROR("Failed to close library " << library << ": " << error);
    }
#else
    int const ret = dlclose(handle);

    if (ret)
    {
      std::string const error = dlerror();

      TEST_ERROR("Failed to close library " << library << ": " << error);
    }
#endif
  }

  return EXIT_SUCCESS;
}
<commit_msg>Clean up dlopen test for Windows<commit_after>/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <test_common.h>

#include <vistk/utilities/path.h>

#include <iostream>
#include <string>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#include <cstdlib>

#if defined(_WIN32) || defined(_WIN64)
namespace
{

typedef std::basic_string<TCHAR> tstring;

}

static tstring last_windows_error();
#endif

int
main(int argc, char* argv[])
{
  if (argc != 3)
  {
    TEST_ERROR("Expected two arguments");

    return EXIT_FAILURE;
  }

#if defined(_WIN32) || defined(_WIN64)
  typedef HMODULE library_t;
  typedef std::wstring module_path_t;
#else
  typedef void* library_t;
  typedef std::string module_path_t;
#endif

  std::string const library = argv[1];
  vistk::path_t const path = argv[2];
  module_path_t const library_path = path.native();

  library_t handle = NULL;

#if defined(_WIN32) || defined(_WIN64)
  handle = LoadLibraryW(library_path.c_str());
#else
  handle = dlopen(library_path.c_str(), RTLD_NOW);
#endif

  if (!handle)
  {
#if defined(_WIN32) || defined(_WIN64)
    tstring const error = last_windows_error();
#else
    std::string const error = dlerror();
#endif

    TEST_ERROR("Failed to open library " << library << ": " << error);
  }
  else
  {
#if defined(_WIN32) || defined(_WIN64)
    int const ret = FreeLibrary(handle);

    if (!ret)
    {
      tstring const error = last_windows_error();
#else
    int const ret = dlclose(handle);

    if (ret)
    {
      std::string const error = dlerror();
#endif

      TEST_ERROR("Failed to close library " << library << ": " << error);
    }
  }

  return EXIT_SUCCESS;
}

#if defined(_WIN32) || defined(_WIN64)
tstring
last_windows_error()
{
  DWORD const err_code = GetLastError();
  LPTSTR str;

  DWORD const ret = FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
    NULL,
    err_code,
    0,
    reinterpret_cast<LPTSTR>(&str),
    0,
    NULL);

  if (!ret)
  {
    TEST_ERROR("Could not get error string from system");

    exit(EXIT_FAILURE);
  }

  tstring const error = str;

  LocalFree(str);

  return error;
}
#endif
<|endoftext|>


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

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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.

******************************************************************************/
#include "ProgressDialogManager.h"

#include "DataSource.h"
#include "ModuleManager.h"
#include "Operator.h"

#include <QCoreApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QMainWindow>
#include <QMap>
#include <QProgressBar>
#include <QVBoxLayout>

#include <cassert>
#include <iostream>

namespace tomviz {

ProgressDialogManager::ProgressDialogManager(QMainWindow* mw)
  : Superclass(mw), mainWindow(mw)
{
  ModuleManager& mm = ModuleManager::instance();
  QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,
                   SLOT(dataSourceAdded(DataSource*)));
}

ProgressDialogManager::~ProgressDialogManager()
{
}

void ProgressDialogManager::operationStarted()
{
  QDialog* progressDialog = new QDialog(this->mainWindow);
  progressDialog->setAttribute(Qt::WA_DeleteOnClose);

  Operator* op = qobject_cast<Operator*>(this->sender());
  QObject::connect(op, &Operator::transformingDone, progressDialog,
                   &QDialog::accept);

  // We have to check after we have connected to the signal as otherwise we
  // might miss the state transition as its occurring on another thread.
  if (op->isFinished()) {
    progressDialog->deleteLater();
    return;
  }

  QLayout* layout = new QVBoxLayout();
  QWidget* progressWidget = op->getCustomProgressWidget(progressDialog);
  if (progressWidget == nullptr) {
    QProgressBar* progressBar = new QProgressBar(progressDialog);
    progressBar->setMinimum(0);
    progressBar->setMaximum(op->totalProgressSteps());
    progressWidget = progressBar;
    QObject::connect(op, &Operator::updateProgress, progressBar,
                     &QProgressBar::valueChanged);
    QObject::connect(op, &Operator::updateProgress, this,
                     &ProgressDialogManager::operationProgress);
    layout->addWidget(progressBar);
  }
  layout->addWidget(progressWidget);
  if (op->supportsCancelingMidTransform()) {
    // Unless the widget has custom progress handling, you can't cancel it.
    QDialogButtonBox* dialogButtons = new QDialogButtonBox(
      QDialogButtonBox::Cancel, Qt::Horizontal, progressDialog);
    layout->addWidget(dialogButtons);
    QObject::connect(dialogButtons, &QDialogButtonBox::rejected, op,
                     &Operator::cancelTransform);
    QObject::connect(dialogButtons, &QDialogButtonBox::rejected, progressDialog,
                     &QDialog::reject);
  }
  progressDialog->setWindowTitle(QString("%1 Progress").arg(op->label()));
  progressDialog->setLayout(layout);
  progressDialog->adjustSize();
  // Increase size of dialog so we can see title, not sure there is a better
  // way.
  auto height = progressDialog->height();
  progressDialog->resize(300, height);
  progressDialog->show();
  QCoreApplication::processEvents();
}

void ProgressDialogManager::operatorAdded(Operator* op)
{
  QObject::connect(op, &Operator::transformingStarted, this,
                   &ProgressDialogManager::operationStarted);
}

void ProgressDialogManager::dataSourceAdded(DataSource* ds)
{
  QObject::connect(ds, SIGNAL(operatorAdded(Operator*)), this,
                   SLOT(operatorAdded(Operator*)));
}

void ProgressDialogManager::operationProgress(int)
{
  // Probably not strictly neccessary in the long run where we have a background
  // thread, until then we need this call.
  QCoreApplication::processEvents();
}
}
<commit_msg>Fix signal connection<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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.

******************************************************************************/
#include "ProgressDialogManager.h"

#include "DataSource.h"
#include "ModuleManager.h"
#include "Operator.h"

#include <QCoreApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QMainWindow>
#include <QMap>
#include <QProgressBar>
#include <QVBoxLayout>

#include <cassert>
#include <iostream>

namespace tomviz {

ProgressDialogManager::ProgressDialogManager(QMainWindow* mw)
  : Superclass(mw), mainWindow(mw)
{
  ModuleManager& mm = ModuleManager::instance();
  QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,
                   SLOT(dataSourceAdded(DataSource*)));
}

ProgressDialogManager::~ProgressDialogManager()
{
}

void ProgressDialogManager::operationStarted()
{
  QDialog* progressDialog = new QDialog(this->mainWindow);
  progressDialog->setAttribute(Qt::WA_DeleteOnClose);

  Operator* op = qobject_cast<Operator*>(this->sender());
  QObject::connect(op, &Operator::transformingDone, progressDialog,
                   &QDialog::accept);

  // We have to check after we have connected to the signal as otherwise we
  // might miss the state transition as its occurring on another thread.
  if (op->isFinished()) {
    progressDialog->deleteLater();
    return;
  }

  QLayout* layout = new QVBoxLayout();
  QWidget* progressWidget = op->getCustomProgressWidget(progressDialog);
  if (progressWidget == nullptr) {
    QProgressBar* progressBar = new QProgressBar(progressDialog);
    progressBar->setMinimum(0);
    progressBar->setMaximum(op->totalProgressSteps());
    progressWidget = progressBar;
    QObject::connect(op, &Operator::updateProgress, progressBar,
                     &QProgressBar::setValue);
    QObject::connect(op, &Operator::updateProgress, this,
                     &ProgressDialogManager::operationProgress);
    layout->addWidget(progressBar);
  }
  layout->addWidget(progressWidget);
  if (op->supportsCancelingMidTransform()) {
    // Unless the widget has custom progress handling, you can't cancel it.
    QDialogButtonBox* dialogButtons = new QDialogButtonBox(
      QDialogButtonBox::Cancel, Qt::Horizontal, progressDialog);
    layout->addWidget(dialogButtons);
    QObject::connect(dialogButtons, &QDialogButtonBox::rejected, op,
                     &Operator::cancelTransform);
    QObject::connect(dialogButtons, &QDialogButtonBox::rejected, progressDialog,
                     &QDialog::reject);
  }
  progressDialog->setWindowTitle(QString("%1 Progress").arg(op->label()));
  progressDialog->setLayout(layout);
  progressDialog->adjustSize();
  // Increase size of dialog so we can see title, not sure there is a better
  // way.
  auto height = progressDialog->height();
  progressDialog->resize(300, height);
  progressDialog->show();
  QCoreApplication::processEvents();
}

void ProgressDialogManager::operatorAdded(Operator* op)
{
  QObject::connect(op, &Operator::transformingStarted, this,
                   &ProgressDialogManager::operationStarted);
}

void ProgressDialogManager::dataSourceAdded(DataSource* ds)
{
  QObject::connect(ds, SIGNAL(operatorAdded(Operator*)), this,
                   SLOT(operatorAdded(Operator*)));
}

void ProgressDialogManager::operationProgress(int)
{
  // Probably not strictly neccessary in the long run where we have a background
  // thread, until then we need this call.
  QCoreApplication::processEvents();
}
}
<|endoftext|>


<commit_before>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>

#include "BitFunnel/Index/IIndex.h"
#include "BitFunnel/Index/IngestChunks.h"
#include "CmdLineParser/CmdLineParser.h"

static std::vector<std::string> readLines(char const * fileName)
{
    std::ifstream file(fileName);

    std::vector<std::string> lines;
    std::string line;
    while(std::getline(file, line)) {
        lines.push_back(std::move(line));
    }

    return lines;
}

static void loadAndIngestChunkList(char const * chunkListFileName)
{
    std::cout << "Loading chunk list file '" << chunkListFileName << "'"
        << std::endl;
    std::vector<std::string> filePaths = readLines(chunkListFileName);

    BitFunnel::IIndex index;
    BitFunnel::IngestChunks(filePaths, index, 2);
}

int main(int argc, char** argv)
{
    CmdLine::CmdLineParser parser(
        "StatisticsBuilder",
        "Ingest documents and compute statistics about them.");

    CmdLine::RequiredParameter<char const *> chunkListFileName(
        "chunkListFileName",
        "Path to the file to convert to a vector.");

    parser.AddParameter(chunkListFileName);

    if (!parser.TryParse(std::cout, argc, argv))
    {
        return 0;
    }

    loadAndIngestChunkList(chunkListFileName);

    return 0;
}
<commit_msg>Cleaned up main.cpp in StatisticsBuilder.<commit_after>#include <fstream>
#include <iostream>
#include <vector>

#include "BitFunnel/Index/IIndex.h"
#include "BitFunnel/Index/IngestChunks.h"
#include "CmdLineParser/CmdLineParser.h"

// Returns a vector with one entry for each line in the file.
static std::vector<std::string> ReadLines(char const * fileName)
{
    std::ifstream file(fileName);

    std::vector<std::string> lines;
    std::string line;
    while(std::getline(file, line)) {
        lines.push_back(std::move(line));
    }

    return lines;
}

static void LoadAndIngestChunkList(char const * chunkListFileName)
{
    std::cout << "Loading chunk list file '" << chunkListFileName << "'"
        << std::endl;
    std::vector<std::string> filePaths = ReadLines(chunkListFileName);

    BitFunnel::IIndex index;
    BitFunnel::IngestChunks(filePaths, index, 2);
}

int main(int argc, char** argv)
{
    CmdLine::CmdLineParser parser(
        "StatisticsBuilder",
        "Ingest documents and compute statistics about them.");

    CmdLine::RequiredParameter<char const *> chunkListFileName(
        "chunkListFileName",
        "Path to a file containing the paths to the chunk files to be ingested. "
        "One chunk file per line. Paths are relative to working directory.");

    parser.AddParameter(chunkListFileName);

    int returnCode = 0;

    if (parser.TryParse(std::cout, argc, argv))
    {
        try
        {
            LoadAndIngestChunkList(chunkListFileName);
            returnCode = 0;
        }
        catch (...)
        {
            std::cout << "Unexpected error.";
            returnCode = 1;
        }
    }
    else
    {
        parser.Usage(std::cout, argv[0]);
        returnCode = 1;
    }

    return returnCode;
}
<|endoftext|>


<commit_before>// Copyright 2013-2015 Stanford University
//
// 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.

#include <iostream>

#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/io/filterstream.h"
#include "src/ext/cpputil/include/io/column.h"

#define DEFINE_STOKE_ARGS 1
#include "tools/gadgets/cost_function.h"
#include "tools/gadgets/functions.h"
#include "tools/gadgets/rewrite.h"
#include "tools/gadgets/sandbox.h"
#include "tools/gadgets/seed.h"
#include "tools/gadgets/solver.h"
#include "tools/gadgets/target.h"
#include "tools/gadgets/testcases.h"
#include "tools/gadgets/validator.h"
#include "tools/gadgets/verifier.h"
#include "tools/ui/console.h"

using namespace cpputil;
using namespace std;
using namespace stoke;

int main(int argc, char** argv) {
  CommandLineConfig::strict_with_convenience(argc, argv);
  DebugHandler::install_sigsegv();
  DebugHandler::install_sigill();

  FunctionsGadget aux_fxns;
  TargetGadget target(aux_fxns);
  RewriteGadget rewrite(aux_fxns);

  SeedGadget seed;
  TestSetGadget test_set(seed);
  SandboxGadget sb(test_set, aux_fxns);
  CostFunctionGadget fxn(target, &sb);
  SolverGadget smt;
  ValidatorGadget validator(smt);
  VerifierGadget verifier(fxn, validator);

  ofilterstream<Column> os(Console::msg());
  os.filter().padding(3);

  os << "Target" << endl;
  os << endl;
  os << target_arg.value().code << endl;
  os.filter().next();

  os << "Rewrite" << endl;
  os << endl;
  os << rewrite_arg.value().code << endl;
  os.filter().done();

  Console::msg() << endl;

  if (!target.is_sound()) {
    Console::error(1) << "Target reads undefined variables, or leaves live_out undefined: " << target.which_undef_read() << endl;
  }

  if (!rewrite.is_sound()) {
    Console::error(1) << "Rewrite reads undefined variables, or leaves live_out undefined: " << rewrite.which_undef_read() << endl;
  }

  if (strategy_arg.value() == Strategy::NONE) {
    Console::warn() << "'--stragegy none' passed, so no verification is done." << endl;
    return 0;
  }

  const auto res = verifier.verify(target, rewrite);

  if(verifier.has_error()) {
    Console::msg() << "Encountered error: " << endl;
    Console::msg() << verifier.error() << endl;
    return 1;
  }

  Console::msg() << "Equivalent: " << (res ? "yes" : "no") << endl;

  if (!res && verifier.counter_example_available()) {
    Console::msg() << endl;
    Console::msg() << verifier.get_counter_example();
    Console::msg() << endl;
  } else if (!res) {
    Console::msg() << endl << "No counterexample available." << endl;
  }

  return 0;
}
<commit_msg>show diff in debug_verify<commit_after>// Copyright 2013-2015 Stanford University
//
// 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.

#include <iostream>

#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/io/filterstream.h"
#include "src/ext/cpputil/include/io/column.h"

#define DEFINE_STOKE_ARGS 1
#include "tools/gadgets/cost_function.h"
#include "tools/gadgets/functions.h"
#include "tools/gadgets/rewrite.h"
#include "tools/gadgets/sandbox.h"
#include "tools/gadgets/seed.h"
#include "tools/gadgets/solver.h"
#include "tools/gadgets/target.h"
#include "tools/gadgets/testcases.h"
#include "tools/gadgets/validator.h"
#include "tools/gadgets/verifier.h"
#include "tools/io/state_diff.h"
#include "tools/ui/console.h"

using namespace cpputil;
using namespace std;
using namespace stoke;

auto& dbg = Heading::create("Diff Options:");
auto& show_unchanged = FlagArg::create("show_unchanged")
                       .description("Show unchanged lines");

int main(int argc, char** argv) {
  CommandLineConfig::strict_with_convenience(argc, argv);
  DebugHandler::install_sigsegv();
  DebugHandler::install_sigill();

  FunctionsGadget aux_fxns;
  TargetGadget target(aux_fxns);
  RewriteGadget rewrite(aux_fxns);

  SeedGadget seed;
  TestSetGadget test_set(seed);
  SandboxGadget sb(test_set, aux_fxns);
  CostFunctionGadget fxn(target, &sb);
  SolverGadget smt;
  ValidatorGadget validator(smt);
  VerifierGadget verifier(fxn, validator);

  ofilterstream<Column> os(Console::msg());
  os.filter().padding(3);

  os << "Target" << endl;
  os << endl;
  os << target_arg.value().code << endl;
  os.filter().next();

  os << "Rewrite" << endl;
  os << endl;
  os << rewrite_arg.value().code << endl;
  os.filter().done();

  Console::msg() << endl;

  if (!target.is_sound()) {
    Console::error(1) << "Target reads undefined variables, or leaves live_out undefined: " << target.which_undef_read() << endl;
  }

  if (!rewrite.is_sound()) {
    Console::error(1) << "Rewrite reads undefined variables, or leaves live_out undefined: " << rewrite.which_undef_read() << endl;
  }

  if (strategy_arg.value() == Strategy::NONE) {
    Console::warn() << "'--stragegy none' passed, so no verification is done." << endl;
    return 0;
  }

  const auto res = verifier.verify(target, rewrite);

  if(verifier.has_error()) {
    Console::msg() << "Encountered error: " << endl;
    Console::msg() << verifier.error() << endl;
    return 1;
  }

  Console::msg() << "Equivalent: " << (res ? "yes" : "no") << endl;

  if (!res && verifier.counter_example_available()) {
    Console::msg() << endl << "Counterexample:" << endl;
    Console::msg() << endl;
    Console::msg() << verifier.get_counter_example();
    Console::msg() << endl << endl;
    Console::msg() << "Difference of running target and rewrite on the counterexample:";
    Console::msg() << endl << endl;
    CpuStates tcs;
    tcs.push_back(verifier.get_counter_example());
    SandboxGadget sb(tcs, aux_fxns);
    sb.run(target);
    const auto target_result = *(sb.result_begin());
    sb.run(rewrite);
    const auto rewrite_result = *(sb.result_begin());
    Console::msg() << diff_states(target_result, rewrite_result, show_unchanged);
    Console::msg() << endl;
  } else if (!res) {
    Console::msg() << endl << "No counterexample available." << endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
    OpenDeck MIDI platform firmware
    Copyright (C) 2015-2018 Igor Petrovic

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Board.h"
#include "Variables.h"
#include "../../../../interface/digital/output/leds/Variables.h"
#include "../../../../interface/digital/output/leds/Helpers.h"

volatile uint32_t rTime_ms;
static uint8_t midiIn_timeout, midiOut_timeout;

bool MIDIreceived, MIDIsent;

const uint8_t ledRowPinArray[] =
{
    LED_ROW_1_PIN,
    LED_ROW_2_PIN,
    LED_ROW_3_PIN,
    LED_ROW_4_PIN,
    LED_ROW_5_PIN,
    LED_ROW_6_PIN
};

volatile uint8_t *ledRowPortArray[] =
{
    &LED_ROW_1_PORT,
    &LED_ROW_2_PORT,
    &LED_ROW_3_PORT,
    &LED_ROW_4_PORT,
    &LED_ROW_5_PORT,
    &LED_ROW_6_PORT
};

inline void activateInputColumn()
{
    BIT_READ(dmColumnArray[activeInColumn], 0) ? setHigh(DEC_DM_A0_PORT, DEC_DM_A0_PIN) : setLow(DEC_DM_A0_PORT, DEC_DM_A0_PIN);
    BIT_READ(dmColumnArray[activeInColumn], 1) ? setHigh(DEC_DM_A1_PORT, DEC_DM_A1_PIN) : setLow(DEC_DM_A1_PORT, DEC_DM_A1_PIN);
    BIT_READ(dmColumnArray[activeInColumn], 2) ? setHigh(DEC_DM_A2_PORT, DEC_DM_A2_PIN) : setLow(DEC_DM_A2_PORT, DEC_DM_A2_PIN);
}

inline void activateOutputColumn()
{
    BIT_READ(activeOutColumn, 0) ? setHigh(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : setLow(DEC_LM_A0_PORT, DEC_LM_A0_PIN);
    BIT_READ(activeOutColumn, 1) ? setHigh(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : setLow(DEC_LM_A1_PORT, DEC_LM_A1_PIN);
    BIT_READ(activeOutColumn, 2) ? setHigh(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : setLow(DEC_LM_A2_PORT, DEC_LM_A2_PIN);
}

inline void storeDigitalIn()
{
    setLow(SR_CLOCK_PORT, SR_CLOCK_PIN);
    setLow(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN);
    _NOP();

    digitalInBuffer[activeInColumn] = 0;

    setHigh(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN);

    for (int i=0; i<8; i++)
    {
        setLow(SR_CLOCK_PORT, SR_CLOCK_PIN);
        _NOP();
        BIT_WRITE(digitalInBuffer[activeInColumn], dmRowBitArray[i], !readPin(SR_DIN_PORT, SR_DIN_PIN));
        setHigh(SR_CLOCK_PORT, SR_CLOCK_PIN);
    }
}

inline void ledRowsOff()
{
    //turn off PWM
    TCCR1A &= ~(1<<COM1C1);
    TCCR4C &= ~(1<<COM4D1);
    TCCR1A &= ~(1<<COM1A1);
    TCCR4A &= ~(1<<COM4A1);
    TCCR3A &= ~(1<<COM3A1);
    TCCR1A &= ~(1<<COM1B1);

    for (int i=0; i<NUMBER_OF_LED_ROWS; i++)
    {
        #ifdef LED_INVERT
        setHigh(*(ledRowPortArray[i]), ledRowPinArray[i]);
        #else
        setLow(*(ledRowPortArray[i]), ledRowPinArray[i]);
        #endif
    }
}

inline void ledRowOn(uint8_t rowNumber, uint8_t intensity)
{
    if (intensity == 255)
    {
        //max value, don't use pwm
        #ifdef LED_INVERT
        setLow(*(ledRowPortArray[rowNumber]), ledRowPinArray[rowNumber]);
        #else
        setHigh(*(ledRowPortArray[rowNumber]), ledRowPinArray[rowNumber]);
        #endif
    }
    else
    {
        #ifdef LED_INVERT
        intensity = 255 - intensity;
        #endif

        switch (rowNumber)
        {
            //turn off pwm if intensity is max
            case 0:
            OCR1C = intensity;
            TCCR1A |= (1<<COM1C1);
            break;

            case 1:
            OCR4D = intensity;
            TCCR4C |= (1<<COM4D1);
            break;

            case 2:
            OCR1A = intensity;
            TCCR1A |= (1<<COM1A1);
            break;

            case 3:
            OCR4A = intensity;
            TCCR4A |= (1<<COM4A1);
            break;

            case 4:
            OCR3A = intensity;
            TCCR3A |= (1<<COM3A1);
            break;

            case 5:
            OCR1B = intensity;
            TCCR1A |= (1<<COM1B1);
            break;

            default:
            break;
        }
    }
}

inline void checkLEDs()
{
    //if there is an active LED in current column, turn on LED row
    //do fancy transitions here
    for (int i=0; i<NUMBER_OF_LED_ROWS; i++)
    {
        uint8_t ledNumber = activeOutColumn+i*NUMBER_OF_LED_COLUMNS;
        uint8_t ledStateSingle = LED_ON(ledState[ledNumber]);

        ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS-1);

        //don't bother with pwm if it's disabled
        if (!pwmSteps && ledStateSingle)
        {
            ledRowOn(i, 255);
        }
        else
        {
            if (ledTransitionScale[transitionCounter[ledNumber]])
                ledRowOn(i, ledTransitionScale[transitionCounter[ledNumber]]);

            if (transitionCounter[ledNumber] != ledStateSingle)
            {
                //fade up
                if (transitionCounter[ledNumber] < ledStateSingle)
                {
                    transitionCounter[ledNumber] += pwmSteps;

                    if (transitionCounter[ledNumber] > ledStateSingle)
                        transitionCounter[ledNumber] = ledStateSingle;
                }
                else
                {
                    //fade down
                    transitionCounter[ledNumber] -= pwmSteps;

                    if (transitionCounter[ledNumber] < 0)
                        transitionCounter[ledNumber] = 0;
                }
            }
        }
    }
}

ISR(TIMER0_COMPA_vect)
{
    //update blink every 1ms
    //update led matrix every 1ms
    //update button matrix each time

    static uint8_t updateStuff = 0;
    updateStuff++;

    if (analogSampleCounter != NUMBER_OF_ANALOG_SAMPLES)
        startADCconversion();

    if (updateStuff == 4)
    {
        ledRowsOff();

        if (activeOutColumn == NUMBER_OF_LED_COLUMNS)
            activeOutColumn = 0;

        activateOutputColumn();
        checkLEDs();

        activeOutColumn++;
        rTime_ms++;

        //read input matrix
        if (activeInColumn < NUMBER_OF_BUTTON_COLUMNS)
        {
            for (int i=0; i<NUMBER_OF_BUTTON_COLUMNS; i++)
            {
                activeInColumn = i;
                activateInputColumn();
                storeDigitalIn();
            }

            activeInColumn = NUMBER_OF_BUTTON_COLUMNS;
        }

        if (MIDIreceived)
        {
            MIDI_LED_ON(LED_IN_PORT, LED_IN_PIN);
            MIDIreceived = false;
            midiIn_timeout = MIDI_INDICATOR_TIMEOUT;
        }

        if (MIDIsent)
        {
            MIDI_LED_ON(LED_OUT_PORT, LED_OUT_PIN);
            MIDIsent = false;
            midiOut_timeout = MIDI_INDICATOR_TIMEOUT;
        }

        if (midiIn_timeout)
            midiIn_timeout--;
        else
            MIDI_LED_OFF(LED_IN_PORT, LED_IN_PIN);

        if (midiOut_timeout)
            midiOut_timeout--;
        else
            MIDI_LED_OFF(LED_OUT_PORT, LED_OUT_PIN);

        updateStuff = 0;
    }
}
<commit_msg>fix pin names<commit_after>/*
    OpenDeck MIDI platform firmware
    Copyright (C) 2015-2018 Igor Petrovic

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Board.h"
#include "Variables.h"
#include "../../../../interface/digital/output/leds/Variables.h"
#include "../../../../interface/digital/output/leds/Helpers.h"

volatile uint32_t rTime_ms;
static uint8_t midiIn_timeout, midiOut_timeout;

bool MIDIreceived, MIDIsent;

const uint8_t ledRowPinArray[] =
{
    LED_ROW_1_PIN,
    LED_ROW_2_PIN,
    LED_ROW_3_PIN,
    LED_ROW_4_PIN,
    LED_ROW_5_PIN,
    LED_ROW_6_PIN
};

volatile uint8_t *ledRowPortArray[] =
{
    &LED_ROW_1_PORT,
    &LED_ROW_2_PORT,
    &LED_ROW_3_PORT,
    &LED_ROW_4_PORT,
    &LED_ROW_5_PORT,
    &LED_ROW_6_PORT
};

inline void activateInputColumn()
{
    BIT_READ(dmColumnArray[activeInColumn], 0) ? setHigh(DEC_DM_A0_PORT, DEC_DM_A0_PIN) : setLow(DEC_DM_A0_PORT, DEC_DM_A0_PIN);
    BIT_READ(dmColumnArray[activeInColumn], 1) ? setHigh(DEC_DM_A1_PORT, DEC_DM_A1_PIN) : setLow(DEC_DM_A1_PORT, DEC_DM_A1_PIN);
    BIT_READ(dmColumnArray[activeInColumn], 2) ? setHigh(DEC_DM_A2_PORT, DEC_DM_A2_PIN) : setLow(DEC_DM_A2_PORT, DEC_DM_A2_PIN);
}

inline void activateOutputColumn()
{
    BIT_READ(activeOutColumn, 0) ? setHigh(DEC_LM_A0_PORT, DEC_LM_A0_PIN) : setLow(DEC_LM_A0_PORT, DEC_LM_A0_PIN);
    BIT_READ(activeOutColumn, 1) ? setHigh(DEC_LM_A1_PORT, DEC_LM_A1_PIN) : setLow(DEC_LM_A1_PORT, DEC_LM_A1_PIN);
    BIT_READ(activeOutColumn, 2) ? setHigh(DEC_LM_A2_PORT, DEC_LM_A2_PIN) : setLow(DEC_LM_A2_PORT, DEC_LM_A2_PIN);
}

inline void storeDigitalIn()
{
    setLow(SR_CLK_PORT, SR_CLK_PIN);
    setLow(SR_LATCH_PORT, SR_LATCH_PIN);
    _NOP();

    digitalInBuffer[activeInColumn] = 0;

    setHigh(SR_LATCH_PORT, SR_LATCH_PIN);

    for (int i=0; i<8; i++)
    {
        setLow(SR_CLK_PORT, SR_CLK_PIN);
        _NOP();
        BIT_WRITE(digitalInBuffer[activeInColumn], dmRowBitArray[i], !readPin(SR_DIN_PORT, SR_DIN_PIN));
        setHigh(SR_CLK_PORT, SR_CLK_PIN);
    }
}

inline void ledRowsOff()
{
    //turn off PWM
    TCCR1A &= ~(1<<COM1C1);
    TCCR4C &= ~(1<<COM4D1);
    TCCR1A &= ~(1<<COM1A1);
    TCCR4A &= ~(1<<COM4A1);
    TCCR3A &= ~(1<<COM3A1);
    TCCR1A &= ~(1<<COM1B1);

    for (int i=0; i<NUMBER_OF_LED_ROWS; i++)
    {
        #ifdef LED_INVERT
        setHigh(*(ledRowPortArray[i]), ledRowPinArray[i]);
        #else
        setLow(*(ledRowPortArray[i]), ledRowPinArray[i]);
        #endif
    }
}

inline void ledRowOn(uint8_t rowNumber, uint8_t intensity)
{
    if (intensity == 255)
    {
        //max value, don't use pwm
        #ifdef LED_INVERT
        setLow(*(ledRowPortArray[rowNumber]), ledRowPinArray[rowNumber]);
        #else
        setHigh(*(ledRowPortArray[rowNumber]), ledRowPinArray[rowNumber]);
        #endif
    }
    else
    {
        #ifdef LED_INVERT
        intensity = 255 - intensity;
        #endif

        switch (rowNumber)
        {
            //turn off pwm if intensity is max
            case 0:
            OCR1C = intensity;
            TCCR1A |= (1<<COM1C1);
            break;

            case 1:
            OCR4D = intensity;
            TCCR4C |= (1<<COM4D1);
            break;

            case 2:
            OCR1A = intensity;
            TCCR1A |= (1<<COM1A1);
            break;

            case 3:
            OCR4A = intensity;
            TCCR4A |= (1<<COM4A1);
            break;

            case 4:
            OCR3A = intensity;
            TCCR3A |= (1<<COM3A1);
            break;

            case 5:
            OCR1B = intensity;
            TCCR1A |= (1<<COM1B1);
            break;

            default:
            break;
        }
    }
}

inline void checkLEDs()
{
    //if there is an active LED in current column, turn on LED row
    //do fancy transitions here
    for (int i=0; i<NUMBER_OF_LED_ROWS; i++)
    {
        uint8_t ledNumber = activeOutColumn+i*NUMBER_OF_LED_COLUMNS;
        uint8_t ledStateSingle = LED_ON(ledState[ledNumber]);

        ledStateSingle *= (NUMBER_OF_LED_TRANSITIONS-1);

        //don't bother with pwm if it's disabled
        if (!pwmSteps && ledStateSingle)
        {
            ledRowOn(i, 255);
        }
        else
        {
            if (ledTransitionScale[transitionCounter[ledNumber]])
                ledRowOn(i, ledTransitionScale[transitionCounter[ledNumber]]);

            if (transitionCounter[ledNumber] != ledStateSingle)
            {
                //fade up
                if (transitionCounter[ledNumber] < ledStateSingle)
                {
                    transitionCounter[ledNumber] += pwmSteps;

                    if (transitionCounter[ledNumber] > ledStateSingle)
                        transitionCounter[ledNumber] = ledStateSingle;
                }
                else
                {
                    //fade down
                    transitionCounter[ledNumber] -= pwmSteps;

                    if (transitionCounter[ledNumber] < 0)
                        transitionCounter[ledNumber] = 0;
                }
            }
        }
    }
}

ISR(TIMER0_COMPA_vect)
{
    //update blink every 1ms
    //update led matrix every 1ms
    //update button matrix each time

    static uint8_t updateStuff = 0;
    updateStuff++;

    if (analogSampleCounter != NUMBER_OF_ANALOG_SAMPLES)
        startADCconversion();

    if (updateStuff == 4)
    {
        ledRowsOff();

        if (activeOutColumn == NUMBER_OF_LED_COLUMNS)
            activeOutColumn = 0;

        activateOutputColumn();
        checkLEDs();

        activeOutColumn++;
        rTime_ms++;

        //read input matrix
        if (activeInColumn < NUMBER_OF_BUTTON_COLUMNS)
        {
            for (int i=0; i<NUMBER_OF_BUTTON_COLUMNS; i++)
            {
                activeInColumn = i;
                activateInputColumn();
                storeDigitalIn();
            }

            activeInColumn = NUMBER_OF_BUTTON_COLUMNS;
        }

        if (MIDIreceived)
        {
            MIDI_LED_ON(LED_IN_PORT, LED_IN_PIN);
            MIDIreceived = false;
            midiIn_timeout = MIDI_INDICATOR_TIMEOUT;
        }

        if (MIDIsent)
        {
            MIDI_LED_ON(LED_OUT_PORT, LED_OUT_PIN);
            MIDIsent = false;
            midiOut_timeout = MIDI_INDICATOR_TIMEOUT;
        }

        if (midiIn_timeout)
            midiIn_timeout--;
        else
            MIDI_LED_OFF(LED_IN_PORT, LED_IN_PIN);

        if (midiOut_timeout)
            midiOut_timeout--;
        else
            MIDI_LED_OFF(LED_OUT_PORT, LED_OUT_PIN);

        updateStuff = 0;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MutableAttrList.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 12:36:59 $
 *
 *  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 EXPRESSED 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 _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#include <rtl/uuid.h>
#include <rtl/memory.h>

#ifndef _XMLOFF_ATTRLIST_HXX
#include "attrlist.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif

using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;

SvXMLAttributeList *XMLMutableAttributeList::GetMutableAttrList()
{
    if( !m_pMutableAttrList )
    {
        m_pMutableAttrList = new SvXMLAttributeList( m_xAttrList );
        m_xAttrList = m_pMutableAttrList;
    }

    return m_pMutableAttrList;
}

XMLMutableAttributeList::XMLMutableAttributeList() :
    m_pMutableAttrList( new SvXMLAttributeList )
{
    m_xAttrList = m_pMutableAttrList;
}

XMLMutableAttributeList::XMLMutableAttributeList( const Reference<
        XAttributeList> & rAttrList, sal_Bool bClone ) :
    m_xAttrList( rAttrList ),
    m_pMutableAttrList( 0 )
{
    if( bClone )
        GetMutableAttrList();
}

XMLMutableAttributeList::~XMLMutableAttributeList()
{
    m_xAttrList = 0;
}

// XUnoTunnel & co
const Sequence< sal_Int8 > & XMLMutableAttributeList::getUnoTunnelId() throw()
{
    static Sequence< sal_Int8 > * pSeq = 0;
    if( !pSeq )
    {
        Guard< Mutex > aGuard( Mutex::getGlobalMutex() );
        if( !pSeq )
        {
            static Sequence< sal_Int8 > aSeq( 16 );
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True );
            pSeq = &aSeq;
        }
    }
    return *pSeq;
}

XMLMutableAttributeList* XMLMutableAttributeList::getImplementation(
        Reference< XInterface > xInt ) throw()
{
    Reference< XUnoTunnel > xUT( xInt, UNO_QUERY );
    if( xUT.is() )
        return (XMLMutableAttributeList*)xUT->getSomething(
                                XMLMutableAttributeList::getUnoTunnelId() );
    else
        return NULL;
}

// XUnoTunnel
sal_Int64 SAL_CALL XMLMutableAttributeList::getSomething(
        const Sequence< sal_Int8 >& rId )
    throw( RuntimeException )
{
    if( rId.getLength() == 16 &&
        0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
                                rId.getConstArray(), 16 ) )
    {
        return (sal_Int64)this;
    }
    return 0;
}

sal_Int16 SAL_CALL XMLMutableAttributeList::getLength(void)
        throw( RuntimeException )
{
    return m_xAttrList->getLength();
}

OUString SAL_CALL XMLMutableAttributeList::getNameByIndex(sal_Int16 i)
        throw( RuntimeException )
{
    return m_xAttrList->getNameByIndex( i );
}

OUString SAL_CALL XMLMutableAttributeList::getTypeByIndex(sal_Int16 i)
        throw( RuntimeException )
{
    return m_xAttrList->getTypeByIndex( i );
}

OUString SAL_CALL  XMLMutableAttributeList::getValueByIndex(sal_Int16 i)
    throw( RuntimeException )
{
    return m_xAttrList->getValueByIndex( i );
}

OUString SAL_CALL XMLMutableAttributeList::getTypeByName(
        const OUString& rName )
        throw( RuntimeException )
{
    return m_xAttrList->getTypeByName( rName );
}

OUString SAL_CALL XMLMutableAttributeList::getValueByName(
        const OUString& rName)
        throw( RuntimeException )
{
    return m_xAttrList->getValueByName( rName );
}

Reference< XCloneable > XMLMutableAttributeList::createClone()
        throw( RuntimeException )
{
    // A cloned list will be a read only list!
    Reference< XCloneable >  r = new SvXMLAttributeList( m_xAttrList );
    return r;
}

void XMLMutableAttributeList::SetValueByIndex( sal_Int16 i,
                                               const ::rtl::OUString& rValue )
{
    GetMutableAttrList()->SetValueByIndex( i, rValue );
}

void XMLMutableAttributeList::AddAttribute( const OUString &rName ,
                                            const OUString &rValue )
{
    GetMutableAttrList()->AddAttribute( rName, rValue );
}

void XMLMutableAttributeList::RemoveAttributeByIndex( sal_Int16 i )
{
    GetMutableAttrList()->RemoveAttributeByIndex( i );
}

void XMLMutableAttributeList::RenameAttributeByIndex( sal_Int16 i,
                                                      const OUString& rNewName )
{
    GetMutableAttrList()->RenameAttributeByIndex( i, rNewName );
}

void XMLMutableAttributeList::AppendAttributeList(
        const Reference< ::com::sun::star::xml::sax::XAttributeList >& r )
{
    GetMutableAttrList()->AppendAttributeList( r );
}

sal_Int16 XMLMutableAttributeList::GetIndexByName( const OUString& rName ) const
{
    sal_Int16 nIndex = -1;
    if( m_pMutableAttrList )
    {
        nIndex = m_pMutableAttrList->GetIndexByName( rName );
    }
    else
    {
        sal_Int16 nCount = m_xAttrList->getLength();
        for( sal_Int16 i=0; nIndex==-1 && i<nCount ; ++i )
        {
            if( m_xAttrList->getNameByIndex(i) == rName )
                nIndex = i;
        }
    }
    return nIndex;
}
<commit_msg>INTEGRATION: CWS oasisbf2 (1.2.82); FILE MERGED 2004/10/22 13:52:48 dvo 1.2.82.1: #i35286# don't crash when using copy constructor on an empty reference Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  $RCSfile: MutableAttrList.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 13:09:32 $
 *
 *  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 EXPRESSED 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 _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#include <rtl/uuid.h>
#include <rtl/memory.h>

#ifndef _XMLOFF_ATTRLIST_HXX
#include "attrlist.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif

using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;

SvXMLAttributeList *XMLMutableAttributeList::GetMutableAttrList()
{
    if( !m_pMutableAttrList )
    {
        m_pMutableAttrList = new SvXMLAttributeList( m_xAttrList );
        m_xAttrList = m_pMutableAttrList;
    }

    return m_pMutableAttrList;
}

XMLMutableAttributeList::XMLMutableAttributeList() :
    m_pMutableAttrList( new SvXMLAttributeList )
{
    m_xAttrList = m_pMutableAttrList;
}

XMLMutableAttributeList::XMLMutableAttributeList( const Reference<
        XAttributeList> & rAttrList, sal_Bool bClone ) :
    m_xAttrList( rAttrList.is() ? rAttrList : new SvXMLAttributeList ),
    m_pMutableAttrList( 0 )
{
    if( bClone )
        GetMutableAttrList();
}

XMLMutableAttributeList::~XMLMutableAttributeList()
{
    m_xAttrList = 0;
}

// XUnoTunnel & co
const Sequence< sal_Int8 > & XMLMutableAttributeList::getUnoTunnelId() throw()
{
    static Sequence< sal_Int8 > * pSeq = 0;
    if( !pSeq )
    {
        Guard< Mutex > aGuard( Mutex::getGlobalMutex() );
        if( !pSeq )
        {
            static Sequence< sal_Int8 > aSeq( 16 );
            rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True );
            pSeq = &aSeq;
        }
    }
    return *pSeq;
}

XMLMutableAttributeList* XMLMutableAttributeList::getImplementation(
        Reference< XInterface > xInt ) throw()
{
    Reference< XUnoTunnel > xUT( xInt, UNO_QUERY );
    if( xUT.is() )
        return (XMLMutableAttributeList*)xUT->getSomething(
                                XMLMutableAttributeList::getUnoTunnelId() );
    else
        return NULL;
}

// XUnoTunnel
sal_Int64 SAL_CALL XMLMutableAttributeList::getSomething(
        const Sequence< sal_Int8 >& rId )
    throw( RuntimeException )
{
    if( rId.getLength() == 16 &&
        0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
                                rId.getConstArray(), 16 ) )
    {
        return (sal_Int64)this;
    }
    return 0;
}

sal_Int16 SAL_CALL XMLMutableAttributeList::getLength(void)
        throw( RuntimeException )
{
    return m_xAttrList->getLength();
}

OUString SAL_CALL XMLMutableAttributeList::getNameByIndex(sal_Int16 i)
        throw( RuntimeException )
{
    return m_xAttrList->getNameByIndex( i );
}

OUString SAL_CALL XMLMutableAttributeList::getTypeByIndex(sal_Int16 i)
        throw( RuntimeException )
{
    return m_xAttrList->getTypeByIndex( i );
}

OUString SAL_CALL  XMLMutableAttributeList::getValueByIndex(sal_Int16 i)
    throw( RuntimeException )
{
    return m_xAttrList->getValueByIndex( i );
}

OUString SAL_CALL XMLMutableAttributeList::getTypeByName(
        const OUString& rName )
        throw( RuntimeException )
{
    return m_xAttrList->getTypeByName( rName );
}

OUString SAL_CALL XMLMutableAttributeList::getValueByName(
        const OUString& rName)
        throw( RuntimeException )
{
    return m_xAttrList->getValueByName( rName );
}

Reference< XCloneable > XMLMutableAttributeList::createClone()
        throw( RuntimeException )
{
    // A cloned list will be a read only list!
    Reference< XCloneable >  r = new SvXMLAttributeList( m_xAttrList );
    return r;
}

void XMLMutableAttributeList::SetValueByIndex( sal_Int16 i,
                                               const ::rtl::OUString& rValue )
{
    GetMutableAttrList()->SetValueByIndex( i, rValue );
}

void XMLMutableAttributeList::AddAttribute( const OUString &rName ,
                                            const OUString &rValue )
{
    GetMutableAttrList()->AddAttribute( rName, rValue );
}

void XMLMutableAttributeList::RemoveAttributeByIndex( sal_Int16 i )
{
    GetMutableAttrList()->RemoveAttributeByIndex( i );
}

void XMLMutableAttributeList::RenameAttributeByIndex( sal_Int16 i,
                                                      const OUString& rNewName )
{
    GetMutableAttrList()->RenameAttributeByIndex( i, rNewName );
}

void XMLMutableAttributeList::AppendAttributeList(
        const Reference< ::com::sun::star::xml::sax::XAttributeList >& r )
{
    GetMutableAttrList()->AppendAttributeList( r );
}

sal_Int16 XMLMutableAttributeList::GetIndexByName( const OUString& rName ) const
{
    sal_Int16 nIndex = -1;
    if( m_pMutableAttrList )
    {
        nIndex = m_pMutableAttrList->GetIndexByName( rName );
    }
    else
    {
        sal_Int16 nCount = m_xAttrList->getLength();
        for( sal_Int16 i=0; nIndex==-1 && i<nCount ; ++i )
        {
            if( m_xAttrList->getNameByIndex(i) == rName )
                nIndex = i;
        }
    }
    return nIndex;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer                    //
//                                                                            //
// This software may be modified and distributed under the terms              //
// of the MIT license.  See the LICENSE file for details.                     //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

// includes  -------------------------------------------------------------------
#include <swift2d/settings/SettingsWrapper.hpp>

#include <swift2d/objects/SavableObjectVisitor.hpp>
#include <swift2d/steam/Steam.hpp>

namespace swift {

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

void SettingsWrapper::set_settings_type(std::string const& type) {
  settings_type_ = type;
}

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

SettingsWrapper::SettingsWrapper()
  : settings_type_("EngineSettings") {
}

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

SettingsWrapper::~SettingsWrapper() {}

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

void SettingsWrapper::load_from_file(std::string const& file_name) {
  auto d(EngineSettings::create_from_file(file_name));
  if (d) {
    Settings = std::dynamic_pointer_cast<EngineSettings>(d);
  } else {
    Settings = std::dynamic_pointer_cast<EngineSettings>(Object::create(settings_type_));
  }
}

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

void SettingsWrapper::save_to_file(std::string const& file_name) {
  Settings->save_to_file(file_name);
}

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

void SettingsWrapper::load_from_steam_file(std::string const& file_name) {
  auto buffer = Steam::get().load_file_from_cloud(file_name);
  auto d(EngineSettings::create_from_buffer(buffer));
  if (d) {
    Settings = std::dynamic_pointer_cast<EngineSettings>(d);
  } else {
    Settings = std::dynamic_pointer_cast<EngineSettings>(Object::create(settings_type_));
  }
}

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

void SettingsWrapper::save_to_steam_file(std::string const& file_name) {

  Steam::get().save_file_to_cloud(file_name, Settings->save_to_buffer());
}

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

}
<commit_msg>fixed segfault with standard settings type<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer                    //
//                                                                            //
// This software may be modified and distributed under the terms              //
// of the MIT license.  See the LICENSE file for details.                     //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

// includes  -------------------------------------------------------------------
#include <swift2d/settings/SettingsWrapper.hpp>

#include <swift2d/objects/SavableObjectVisitor.hpp>
#include <swift2d/steam/Steam.hpp>

namespace swift {

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

void SettingsWrapper::set_settings_type(std::string const& type) {
  settings_type_ = type;

  Settings = std::dynamic_pointer_cast<EngineSettings>(Object::create(settings_type_));
}

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

SettingsWrapper::SettingsWrapper()
  : settings_type_("EngineSettings") {

  Settings = EngineSettings::create();
}

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

SettingsWrapper::~SettingsWrapper() {}

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

void SettingsWrapper::load_from_file(std::string const& file_name) {
  auto d(EngineSettings::create_from_file(file_name));
  if (d) {
    Settings = std::dynamic_pointer_cast<EngineSettings>(d);
  } else {
    Settings = std::dynamic_pointer_cast<EngineSettings>(Object::create(settings_type_));
  }
}

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

void SettingsWrapper::save_to_file(std::string const& file_name) {
  Settings->save_to_file(file_name);
}

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

void SettingsWrapper::load_from_steam_file(std::string const& file_name) {
  auto buffer = Steam::get().load_file_from_cloud(file_name);
  auto d(EngineSettings::create_from_buffer(buffer));
  if (d) {
    Settings = std::dynamic_pointer_cast<EngineSettings>(d);
  } else {
    Settings = std::dynamic_pointer_cast<EngineSettings>(Object::create(settings_type_));
  }
}

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

void SettingsWrapper::save_to_steam_file(std::string const& file_name) {

  Steam::get().save_file_to_cloud(file_name, Settings->save_to_buffer());
}

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

}
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "libmesh/system_subset_by_subdomain.h"
#include "libmesh/system.h"
#include "libmesh/dof_map.h"
#include "libmesh/parallel.h"
#include "libmesh/elem.h"

namespace libMesh
{
// ------------------------------------------------------------
// SubdomainSelection implementation
SystemSubsetBySubdomain::SubdomainSelection::
SubdomainSelection (void)
{
}

SystemSubsetBySubdomain::SubdomainSelection::
~SubdomainSelection (void)
{
}

SystemSubsetBySubdomain::SubdomainSelectionByList::
SubdomainSelectionByList (const std::set<subdomain_id_type> & list):
  _list(list)
{
}

bool
SystemSubsetBySubdomain::SubdomainSelectionByList::
operator()(const subdomain_id_type & subdomain_id)const
{
  return _list.find(subdomain_id)!=_list.end();
}

// ------------------------------------------------------------
// SystemSubsetBySubdomain implementation

SystemSubsetBySubdomain::
SystemSubsetBySubdomain (const System & system,
                         const SubdomainSelection & subdomain_selection,
                         const std::set<unsigned int> * const var_nums):
  SystemSubset(system),
  ParallelObject(system),
  _var_nums(),
  _dof_ids()
{
  this->set_var_nums(var_nums);
  this->init(subdomain_selection);
}

SystemSubsetBySubdomain::
SystemSubsetBySubdomain (const System & system,
                         const std::set<subdomain_id_type> & subdomain_ids,
                         const std::set<unsigned int> * const var_nums):
  SystemSubset(system),
  ParallelObject(system),
  _var_nums(),
  _dof_ids()
{
  this->set_var_nums(var_nums);
  this->init(subdomain_ids);
}

SystemSubsetBySubdomain::
~SystemSubsetBySubdomain (void)
{
}

const std::vector<unsigned int> &
SystemSubsetBySubdomain::dof_ids() const
{
  return _dof_ids;
}

void
SystemSubsetBySubdomain::
set_var_nums (const std::set<unsigned int> * const var_nums)
{
  _var_nums.clear();

  if (var_nums != libmesh_nullptr)
    _var_nums = *var_nums;

  else
    {
      for (unsigned int i=0; i<_system.n_vars(); i++)
        _var_nums.insert(i);
    }
}

void
SystemSubsetBySubdomain::
init (const SubdomainSelection & subdomain_selection)
{
  _dof_ids.clear();

  std::vector<std::vector<dof_id_type>> dof_ids_per_processor(this->n_processors());

  const DofMap & dof_map = _system.get_dof_map();
  std::vector<dof_id_type> dof_indices;

  const MeshBase & mesh = _system.get_mesh();
  MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();
  for ( ; el != end_el; ++el)
    {
      const Elem * elem = *el;
      if (subdomain_selection(elem->subdomain_id()))
        {
          std::set<unsigned int>::const_iterator it = _var_nums.begin();
          const std::set<unsigned int>::const_iterator itEnd = _var_nums.end();
          for (; it!=itEnd; ++it)
            {
              dof_map.dof_indices (elem, dof_indices, *it);
              for (std::size_t i=0; i<dof_indices.size(); i++)
                {
                  const dof_id_type dof = dof_indices[i];
                  for (processor_id_type proc=0; proc<this->n_processors(); proc++)
                    {
                      if ((dof>=dof_map.first_dof(proc)) && (dof<dof_map.end_dof(proc)))
                        {
                          dof_ids_per_processor[proc].push_back(dof);
                        }
                    }
                }
            }
        }
    }

  /* Distribute information among processors.  */
  std::vector<Parallel::Request> request_per_processor(this->n_processors());
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      if (proc!=this->processor_id())
        {
          this->comm().send(proc,dof_ids_per_processor[proc],request_per_processor[proc]);
        }
    }
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      std::vector<dof_id_type> received_dofs;
      if (proc==this->processor_id())
        {
          received_dofs = dof_ids_per_processor[proc];
        }
      else
        {
          this->comm().receive(proc,received_dofs);
        }
      for (std::size_t i=0; i<received_dofs.size(); i++)
        _dof_ids.push_back(received_dofs[i]);
    }

  /* Sort and unique the vector (using the same mechanism as in \p
     DofMap::prepare_send_list()).  */
  std::sort(_dof_ids.begin(), _dof_ids.end());
  std::vector<unsigned int>::iterator new_end = std::unique (_dof_ids.begin(), _dof_ids.end());
  std::vector<unsigned int> (_dof_ids.begin(), new_end).swap (_dof_ids);

  /* Wait for sends to be complete.  */
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      if (proc!=this->processor_id())
        {
          request_per_processor[proc].wait();
        }
    }
}

void
SystemSubsetBySubdomain::
init (const std::set<subdomain_id_type> & subdomain_ids)
{
  SubdomainSelectionByList selection(subdomain_ids);
  this->init(selection);
}

} // namespace libMesh
<commit_msg>Use rangefor in SystemSubsetBySubdomain::init().<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "libmesh/system_subset_by_subdomain.h"
#include "libmesh/system.h"
#include "libmesh/dof_map.h"
#include "libmesh/parallel.h"
#include "libmesh/elem.h"

namespace libMesh
{
// ------------------------------------------------------------
// SubdomainSelection implementation
SystemSubsetBySubdomain::SubdomainSelection::
SubdomainSelection (void)
{
}

SystemSubsetBySubdomain::SubdomainSelection::
~SubdomainSelection (void)
{
}

SystemSubsetBySubdomain::SubdomainSelectionByList::
SubdomainSelectionByList (const std::set<subdomain_id_type> & list):
  _list(list)
{
}

bool
SystemSubsetBySubdomain::SubdomainSelectionByList::
operator()(const subdomain_id_type & subdomain_id)const
{
  return _list.find(subdomain_id)!=_list.end();
}

// ------------------------------------------------------------
// SystemSubsetBySubdomain implementation

SystemSubsetBySubdomain::
SystemSubsetBySubdomain (const System & system,
                         const SubdomainSelection & subdomain_selection,
                         const std::set<unsigned int> * const var_nums):
  SystemSubset(system),
  ParallelObject(system),
  _var_nums(),
  _dof_ids()
{
  this->set_var_nums(var_nums);
  this->init(subdomain_selection);
}

SystemSubsetBySubdomain::
SystemSubsetBySubdomain (const System & system,
                         const std::set<subdomain_id_type> & subdomain_ids,
                         const std::set<unsigned int> * const var_nums):
  SystemSubset(system),
  ParallelObject(system),
  _var_nums(),
  _dof_ids()
{
  this->set_var_nums(var_nums);
  this->init(subdomain_ids);
}

SystemSubsetBySubdomain::
~SystemSubsetBySubdomain (void)
{
}

const std::vector<unsigned int> &
SystemSubsetBySubdomain::dof_ids() const
{
  return _dof_ids;
}

void
SystemSubsetBySubdomain::
set_var_nums (const std::set<unsigned int> * const var_nums)
{
  _var_nums.clear();

  if (var_nums != libmesh_nullptr)
    _var_nums = *var_nums;

  else
    {
      for (unsigned int i=0; i<_system.n_vars(); i++)
        _var_nums.insert(i);
    }
}

void
SystemSubsetBySubdomain::
init (const SubdomainSelection & subdomain_selection)
{
  _dof_ids.clear();

  std::vector<std::vector<dof_id_type>> dof_ids_per_processor(this->n_processors());

  const DofMap & dof_map = _system.get_dof_map();
  std::vector<dof_id_type> dof_indices;

  const MeshBase & mesh = _system.get_mesh();
  for (const auto & elem : mesh.active_local_element_ptr_range())
    if (subdomain_selection(elem->subdomain_id()))
      {
        std::set<unsigned int>::const_iterator it = _var_nums.begin();
        const std::set<unsigned int>::const_iterator itEnd = _var_nums.end();
        for (; it!=itEnd; ++it)
          {
            dof_map.dof_indices (elem, dof_indices, *it);
            for (std::size_t i=0; i<dof_indices.size(); i++)
              {
                const dof_id_type dof = dof_indices[i];
                for (processor_id_type proc=0; proc<this->n_processors(); proc++)
                  if ((dof>=dof_map.first_dof(proc)) && (dof<dof_map.end_dof(proc)))
                    dof_ids_per_processor[proc].push_back(dof);
              }
          }
      }

  /* Distribute information among processors.  */
  std::vector<Parallel::Request> request_per_processor(this->n_processors());
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      if (proc!=this->processor_id())
        {
          this->comm().send(proc,dof_ids_per_processor[proc],request_per_processor[proc]);
        }
    }
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      std::vector<dof_id_type> received_dofs;
      if (proc==this->processor_id())
        {
          received_dofs = dof_ids_per_processor[proc];
        }
      else
        {
          this->comm().receive(proc,received_dofs);
        }
      for (std::size_t i=0; i<received_dofs.size(); i++)
        _dof_ids.push_back(received_dofs[i]);
    }

  /* Sort and unique the vector (using the same mechanism as in \p
     DofMap::prepare_send_list()).  */
  std::sort(_dof_ids.begin(), _dof_ids.end());
  std::vector<unsigned int>::iterator new_end = std::unique (_dof_ids.begin(), _dof_ids.end());
  std::vector<unsigned int> (_dof_ids.begin(), new_end).swap (_dof_ids);

  /* Wait for sends to be complete.  */
  for (unsigned int proc=0; proc<this->n_processors(); proc++)
    {
      if (proc!=this->processor_id())
        {
          request_per_processor[proc].wait();
        }
    }
}

void
SystemSubsetBySubdomain::
init (const std::set<subdomain_id_type> & subdomain_ids)
{
  SubdomainSelectionByList selection(subdomain_ids);
  this->init(selection);
}

} // namespace libMesh
<|endoftext|>