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

#ifndef DUNE_STUFF_GRID_WALK_HH
#define DUNE_STUFF_GRID_WALK_HH

#include <vector>

#include <boost/format.hpp>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/grid/common/geometry.hh>

#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>

namespace Dune {
namespace Stuff {
namespace Grid {

/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
 **/
struct GridWalkDummyFunctor {
  GridWalkDummyFunctor(){}

  template < class Entity >
  void operator() ( const Entity&, const int) const
  {}
  template < class Entity, class Intersection >
  void operator() ( const Entity&, const Intersection&) const
  {}
};

namespace {
  /** \brief global \ref GridWalkDummyFunctor instance
   **/
  const GridWalkDummyFunctor gridWalkDummyFunctor;
}

/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
 *  \todo allow stacking of functor to save gridwalks?
 *  \tparam GridViewImp any \ref GridView interface compliant type
 *  \tparam codim determines the codim of the Entities that are iterated on
 **/
template < class GridViewImp, size_t codim = 0 >
class GridWalk {
  typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
  GridWalk ( GridViewType gp )
    : gridView_( gp )
  {}

  /** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
   *  \param intersectionFunctor is applied on all Intersections of all codim 0 entities
   *        presented by \var gridView_
   *  \note only instantiable for codim == 0
   */
  template < class EntityFunctor, class IntersectionFunctor >
  void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
  {
    static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
    for (const auto& entity : DSC::entityRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
      for (const auto& intersection : DSC::intersectionRange(gridView_, entity)) {
        intersectionFunctor( entity, intersection);
      }
    }
  }

  /** \param entityFunctor is applied on all codim entities presented by \var gridView_
   *  \note only instantiable for codim < GridView::dimension
   */
  template < class EntityFunctor >
  void operator () ( EntityFunctor& entityFunctor ) const
  {
    static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
    for (const auto& entity : DSC::entityRange(gridView_)) {
      const int entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
    }
  }

private:
  const GridViewType gridView_;
};

//!
template <class ViewImp, size_t codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
    return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_WALK_HH
<commit_msg>[grid.walk] refs #10<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_GRID_WALK_HH
#define DUNE_STUFF_GRID_WALK_HH

#include <vector>

#include <boost/format.hpp>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/grid/common/geometry.hh>

#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/aliases.hh>

namespace Dune {
namespace Stuff {
namespace Grid {

/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
 **/
struct GridWalkDummyFunctor {
  GridWalkDummyFunctor(){}

  template < class Entity >
  void operator() ( const Entity&, const int) const
  {}
  template < class Entity, class Intersection >
  void operator() ( const Entity&, const Intersection&) const
  {}
};

namespace {
  /** \brief global \ref GridWalkDummyFunctor instance
   **/
  const GridWalkDummyFunctor gridWalkDummyFunctor;
}

/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
 *  \todo allow stacking of functor to save gridwalks?
 *  \tparam GridViewImp any \ref GridView interface compliant type
 *  \tparam codim determines the codim of the Entities that are iterated on
 **/
template < class GridViewImp, size_t codim = 0 >
class GridWalk {
  typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
  GridWalk ( GridViewType gp )
    : gridView_( gp )
  {}

  /** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
   *  \param intersectionFunctor is applied on all Intersections of all codim 0 entities
   *        presented by \var gridView_
   *  \note only instantiable for codim == 0
   */
  template < class EntityFunctor, class IntersectionFunctor >
  void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
  {
    static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
    for (const auto& entity : DSC::entityRange(gridView_)) {
      const auto entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
      for (const auto& intersection : DSC::intersectionRange(gridView_, entity)) {
        intersectionFunctor( entity, intersection);
      }
    }
  }

  /** \param entityFunctor is applied on all codim entities presented by \var gridView_
   *  \note only instantiable for codim < GridView::dimension
   */
  template < class EntityFunctor >
  void operator () ( EntityFunctor& entityFunctor ) const
  {
    static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
    for (const auto& entity : DSC::entityRange(gridView_)) {
      const auto entityIndex = gridView_.indexSet().index(entity);
      entityFunctor( entity, entityIndex);
    }
  }

private:
  const GridViewType gridView_;
};

//!
template <class ViewImp, size_t codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
    return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_WALK_HH
<|endoftext|>


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

#include <exotica/TaskMap.h>
#include <exotica/PlanningProblem.h>
#include <boost/algorithm/string.hpp>
#include <exotica/TaskMapInitializer.h>
#include <exotica/FrameInitializer.h>

namespace exotica
{

  TaskMap::TaskMap()
  {

  }

  std::string TaskMap::print(std::string prepend)
  {
    std::string ret = Object::print(prepend);
    return ret;
  }

  void TaskMap::InstantiateBase(const Initializer& init)
  {
    Object::InstatiateObject(init);
    TaskMapInitializer MapInitializer(init);

    Frames.clear();

    for(Initializer& eff : MapInitializer.EndEffector)
    {
        FrameInitializer frame(eff);
        Frames.push_back(KinematicFrameRequest(frame.Link, getFrame(frame.LinkOffset), frame.Base, getFrame(frame.BaseOffset)));
    }
  }

  std::vector<KinematicFrameRequest> TaskMap::GetFrames()
  {
      return Frames;
  }

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

#include <exotica/TaskMap.h>
#include <exotica/PlanningProblem.h>
#include <exotica/TaskMapInitializer.h>
#include <exotica/FrameInitializer.h>

namespace exotica
{

  TaskMap::TaskMap()
  {

  }

  std::string TaskMap::print(std::string prepend)
  {
    std::string ret = Object::print(prepend);
    return ret;
  }

  void TaskMap::InstantiateBase(const Initializer& init)
  {
    Object::InstatiateObject(init);
    TaskMapInitializer MapInitializer(init);

    Frames.clear();

    for(Initializer& eff : MapInitializer.EndEffector)
    {
        FrameInitializer frame(eff);
        Frames.push_back(KinematicFrameRequest(frame.Link, getFrame(frame.LinkOffset), frame.Base, getFrame(frame.BaseOffset)));
    }
  }

  std::vector<KinematicFrameRequest> TaskMap::GetFrames()
  {
      return Frames;
  }

  void TaskMap::taskSpaceDim(int & task_dim)
  {
      task_dim = taskSpaceDim();
  }
}
<|endoftext|>


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

#include "chrome/browser/automation/automation_tab_helper.h"

#include <algorithm>

#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/common/automation_messages.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"

TabEventObserver::TabEventObserver() { }

TabEventObserver::~TabEventObserver() {
  for (size_t i = 0; i < event_sources_.size(); ++i) {
    if (event_sources_[i])
      event_sources_[i]->RemoveObserver(this);
  }
}

void TabEventObserver::StartObserving(AutomationTabHelper* tab_helper) {
  tab_helper->AddObserver(this);
  event_sources_.push_back(tab_helper->AsWeakPtr());
}

void TabEventObserver::StopObserving(AutomationTabHelper* tab_helper) {
  tab_helper->RemoveObserver(this);
  EventSourceVector::iterator iter =
      std::find(event_sources_.begin(), event_sources_.end(), tab_helper);
  if (iter != event_sources_.end())
    event_sources_.erase(iter);
}

AutomationTabHelper::AutomationTabHelper(TabContents* tab_contents)
    : TabContentsObserver(tab_contents),
      is_loading_(false) {
}

AutomationTabHelper::~AutomationTabHelper() { }

void AutomationTabHelper::AddObserver(TabEventObserver* observer) {
  observers_.AddObserver(observer);
}

void AutomationTabHelper::RemoveObserver(TabEventObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool AutomationTabHelper::has_pending_loads() const {
  return is_loading_ || !pending_client_redirects_.empty();
}

void AutomationTabHelper::DidStartLoading() {
  if (is_loading_) {
    // DidStartLoading is often called twice. Once when the renderer sends a
    // load start message, and once when the browser calls it directly as a
    // result of some user-initiated navigation.
    VLOG(1) << "Received DidStartLoading while loading already started.";
    return;
  }
  bool had_pending_loads = has_pending_loads();
  is_loading_ = true;
  if (!had_pending_loads) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnFirstPendingLoad(tab_contents()));
  }
}

void AutomationTabHelper::DidStopLoading() {
  if (!is_loading_) {
    LOG(WARNING) << "Received DidStopLoading while loading already stopped.";
    return;
  }
  is_loading_ = false;
  if (!has_pending_loads()) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnNoMorePendingLoads(tab_contents()));
  }
}

void AutomationTabHelper::RenderViewGone() {
  OnTabOrRenderViewDestroyed(tab_contents());
}

void AutomationTabHelper::TabContentsDestroyed(TabContents* tab_contents) {
  OnTabOrRenderViewDestroyed(tab_contents);
}

void AutomationTabHelper::OnTabOrRenderViewDestroyed(
    TabContents* tab_contents) {
  if (has_pending_loads()) {
    is_loading_ = false;
    pending_client_redirects_.clear();
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnNoMorePendingLoads(tab_contents));
  }
}

bool AutomationTabHelper::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  bool msg_is_good = true;
  IPC_BEGIN_MESSAGE_MAP_EX(AutomationTabHelper, message, msg_is_good)
    IPC_MESSAGE_HANDLER(AutomationMsg_WillPerformClientRedirect,
                        OnWillPerformClientRedirect)
    IPC_MESSAGE_HANDLER(AutomationMsg_DidCompleteOrCancelClientRedirect,
                        OnDidCompleteOrCancelClientRedirect)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()
  if (!msg_is_good) {
    LOG(ERROR) << "Failed to deserialize an IPC message";
  }
  return handled;
}

void AutomationTabHelper::OnWillPerformClientRedirect(
    int64 frame_id, double delay_seconds) {
  // Ignore all non-zero delays.
  // TODO(kkania): Handle timed redirects.
  if (delay_seconds > 0) {
    LOG(WARNING) << "Ignoring timed redirect scheduled for " << delay_seconds
                 << " seconds later. Will not wait for the redirect to occur";
    return;
  }

  bool first_pending_load = !has_pending_loads();
  pending_client_redirects_.insert(frame_id);
  if (first_pending_load) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnFirstPendingLoad(tab_contents()));
  }
}

void AutomationTabHelper::OnDidCompleteOrCancelClientRedirect(int64 frame_id) {
  std::set<int64>::const_iterator iter =
      pending_client_redirects_.find(frame_id);
  // It is possible that we did not track the redirect becasue it had a non-zero
  // delay. See the comment in |OnWillPerformClientRedirect|.
  if (iter != pending_client_redirects_.end()) {
    pending_client_redirects_.erase(iter);
    if (!has_pending_loads()) {
      FOR_EACH_OBSERVER(TabEventObserver, observers_,
                        OnNoMorePendingLoads(tab_contents()));
    }
  }
}
<commit_msg>Make it compile under VS2005.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/automation/automation_tab_helper.h"

#include <algorithm>

#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/common/automation_messages.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"

TabEventObserver::TabEventObserver() { }

TabEventObserver::~TabEventObserver() {
  for (size_t i = 0; i < event_sources_.size(); ++i) {
    if (event_sources_[i])
      event_sources_[i]->RemoveObserver(this);
  }
}

void TabEventObserver::StartObserving(AutomationTabHelper* tab_helper) {
  tab_helper->AddObserver(this);
  event_sources_.push_back(tab_helper->AsWeakPtr());
}

void TabEventObserver::StopObserving(AutomationTabHelper* tab_helper) {
  tab_helper->RemoveObserver(this);
  EventSourceVector::iterator iter =
      std::find(event_sources_.begin(), event_sources_.end(), tab_helper);
  if (iter != event_sources_.end())
    event_sources_.erase(iter);
}

AutomationTabHelper::AutomationTabHelper(TabContents* tab_contents)
    : TabContentsObserver(tab_contents),
      is_loading_(false) {
}

AutomationTabHelper::~AutomationTabHelper() { }

void AutomationTabHelper::AddObserver(TabEventObserver* observer) {
  observers_.AddObserver(observer);
}

void AutomationTabHelper::RemoveObserver(TabEventObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool AutomationTabHelper::has_pending_loads() const {
  return is_loading_ || !pending_client_redirects_.empty();
}

void AutomationTabHelper::DidStartLoading() {
  if (is_loading_) {
    // DidStartLoading is often called twice. Once when the renderer sends a
    // load start message, and once when the browser calls it directly as a
    // result of some user-initiated navigation.
    VLOG(1) << "Received DidStartLoading while loading already started.";
    return;
  }
  bool had_pending_loads = has_pending_loads();
  is_loading_ = true;
  if (!had_pending_loads) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnFirstPendingLoad(tab_contents()));
  }
}

void AutomationTabHelper::DidStopLoading() {
  if (!is_loading_) {
    LOG(WARNING) << "Received DidStopLoading while loading already stopped.";
    return;
  }
  is_loading_ = false;
  if (!has_pending_loads()) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnNoMorePendingLoads(tab_contents()));
  }
}

void AutomationTabHelper::RenderViewGone() {
  OnTabOrRenderViewDestroyed(tab_contents());
}

void AutomationTabHelper::TabContentsDestroyed(TabContents* tab_contents) {
  OnTabOrRenderViewDestroyed(tab_contents);
}

void AutomationTabHelper::OnTabOrRenderViewDestroyed(
    TabContents* tab_contents) {
  if (has_pending_loads()) {
    is_loading_ = false;
    pending_client_redirects_.clear();
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnNoMorePendingLoads(tab_contents));
  }
}

bool AutomationTabHelper::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  bool msg_is_good = true;
  IPC_BEGIN_MESSAGE_MAP_EX(AutomationTabHelper, message, msg_is_good)
    IPC_MESSAGE_HANDLER(AutomationMsg_WillPerformClientRedirect,
                        OnWillPerformClientRedirect)
    IPC_MESSAGE_HANDLER(AutomationMsg_DidCompleteOrCancelClientRedirect,
                        OnDidCompleteOrCancelClientRedirect)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()
  if (!msg_is_good) {
    LOG(ERROR) << "Failed to deserialize an IPC message";
  }
  return handled;
}

void AutomationTabHelper::OnWillPerformClientRedirect(
    int64 frame_id, double delay_seconds) {
  // Ignore all non-zero delays.
  // TODO(kkania): Handle timed redirects.
  if (delay_seconds > 0) {
    LOG(WARNING) << "Ignoring timed redirect scheduled for " << delay_seconds
                 << " seconds later. Will not wait for the redirect to occur";
    return;
  }

  bool first_pending_load = !has_pending_loads();
  pending_client_redirects_.insert(frame_id);
  if (first_pending_load) {
    FOR_EACH_OBSERVER(TabEventObserver, observers_,
                      OnFirstPendingLoad(tab_contents()));
  }
}

void AutomationTabHelper::OnDidCompleteOrCancelClientRedirect(int64 frame_id) {
  std::set<int64>::iterator iter =
      pending_client_redirects_.find(frame_id);
  // It is possible that we did not track the redirect becasue it had a non-zero
  // delay. See the comment in |OnWillPerformClientRedirect|.
  if (iter != pending_client_redirects_.end()) {
    pending_client_redirects_.erase(iter);
    if (!has_pending_loads()) {
      FOR_EACH_OBSERVER(TabEventObserver, observers_,
                        OnNoMorePendingLoads(tab_contents()));
    }
  }
}
<|endoftext|>


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

#include "ash/shell.h"
#include "base/command_line.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/login/login_wizard.h"
#include "chrome/browser/chromeos/login/ui/login_display_host_impl.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/login/user_names.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_system.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Return;

namespace {

class LoginUserTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitchASCII(
        chromeos::switches::kLoginUser, "TestUser@gmail.com");
    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
                                    "hash");
  }
};

class LoginGuestTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kGuestSession);
    command_line->AppendSwitch(::switches::kIncognito);
    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
                                    "hash");
    command_line->AppendSwitchASCII(chromeos::switches::kLoginUser,
                                    chromeos::login::kGuestUserName);
  }
};

class LoginCursorTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kLoginManager);
  }
};

class LoginSigninTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kLoginManager);
    command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(tracing::BeginTracingWithWatch(
        "ui", "ui", "ShowLoginWebUI", 1));
  }
};

// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
  Profile* profile = browser()->profile();
  std::string profile_base_path("hash");
  profile_base_path.insert(0, chrome::kProfileDirPrefix);
  EXPECT_EQ(profile_base_path, profile->GetPath().BaseName().value());
  EXPECT_FALSE(profile->IsOffTheRecord());
}

// Verifies the cursor is not hidden at startup when user is logged in.
IN_PROC_BROWSER_TEST_F(LoginUserTest, CursorShown) {
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());
}

// After a guest login, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginGuestTest, GuestIsOTR) {
  Profile* profile = browser()->profile();
  EXPECT_TRUE(profile->IsOffTheRecord());
  // Ensure there's extension service for this profile.
  EXPECT_TRUE(extensions::ExtensionSystem::Get(profile)->extension_service());
}

// Verifies the cursor is not hidden at startup when running guest session.
IN_PROC_BROWSER_TEST_F(LoginGuestTest, CursorShown) {
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());
}

// Verifies the cursor is hidden at startup on login screen.
IN_PROC_BROWSER_TEST_F(LoginCursorTest, CursorHidden) {
  // Login screen needs to be shown explicitly when running test.
  chromeos::ShowLoginWizard(chromeos::WizardController::kLoginScreenName);

  // Cursor should be hidden at startup
  EXPECT_FALSE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  // Cursor should be shown after cursor is moved.
  EXPECT_TRUE(ui_test_utils::SendMouseMoveSync(gfx::Point()));
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  base::MessageLoop::current()->DeleteSoon(
      FROM_HERE, chromeos::LoginDisplayHostImpl::default_host());
}

// Verifies that the webui for login comes up successfully.
IN_PROC_BROWSER_TEST_F(LoginSigninTest, WebUIVisible) {
  base::TimeDelta no_timeout;
  EXPECT_TRUE(tracing::WaitForWatchEvent(no_timeout));
  std::string json_events;
  ASSERT_TRUE(tracing::EndTracing(&json_events));
}

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

#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "base/command_line.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/login/login_wizard.h"
#include "chrome/browser/chromeos/login/ui/login_display_host_impl.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/login/user_names.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_system.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Return;

namespace {

class LoginUserTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitchASCII(
        chromeos::switches::kLoginUser, "TestUser@gmail.com");
    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
                                    "hash");
  }
};

class LoginGuestTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kGuestSession);
    command_line->AppendSwitch(::switches::kIncognito);
    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
                                    "hash");
    command_line->AppendSwitchASCII(chromeos::switches::kLoginUser,
                                    chromeos::login::kGuestUserName);
  }
};

class LoginCursorTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kLoginManager);
  }
};

class LoginSigninTest : public InProcessBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(chromeos::switches::kLoginManager);
    command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(tracing::BeginTracingWithWatch(
        "ui", "ui", "ShowLoginWebUI", 1));
  }
};

// Used to make sure that the system tray is visible and within the screen
// bounds after login.
void TestSystemTrayIsVisible() {
  ash::SystemTray* tray = ash::Shell::GetInstance()->GetPrimarySystemTray();
  aura::Window* primary_win = ash::Shell::GetPrimaryRootWindow();
  EXPECT_TRUE(tray->visible());
  EXPECT_TRUE(primary_win->bounds().Contains(tray->GetBoundsInScreen()));
}

// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
  Profile* profile = browser()->profile();
  std::string profile_base_path("hash");
  profile_base_path.insert(0, chrome::kProfileDirPrefix);
  EXPECT_EQ(profile_base_path, profile->GetPath().BaseName().value());
  EXPECT_FALSE(profile->IsOffTheRecord());

  TestSystemTrayIsVisible();
}

// Verifies the cursor is not hidden at startup when user is logged in.
IN_PROC_BROWSER_TEST_F(LoginUserTest, CursorShown) {
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  TestSystemTrayIsVisible();
}

// After a guest login, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginGuestTest, GuestIsOTR) {
  Profile* profile = browser()->profile();
  EXPECT_TRUE(profile->IsOffTheRecord());
  // Ensure there's extension service for this profile.
  EXPECT_TRUE(extensions::ExtensionSystem::Get(profile)->extension_service());

  TestSystemTrayIsVisible();
}

// Verifies the cursor is not hidden at startup when running guest session.
IN_PROC_BROWSER_TEST_F(LoginGuestTest, CursorShown) {
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  TestSystemTrayIsVisible();
}

// Verifies the cursor is hidden at startup on login screen.
IN_PROC_BROWSER_TEST_F(LoginCursorTest, CursorHidden) {
  // Login screen needs to be shown explicitly when running test.
  chromeos::ShowLoginWizard(chromeos::WizardController::kLoginScreenName);

  // Cursor should be hidden at startup
  EXPECT_FALSE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  // Cursor should be shown after cursor is moved.
  EXPECT_TRUE(ui_test_utils::SendMouseMoveSync(gfx::Point()));
  EXPECT_TRUE(ash::Shell::GetInstance()->cursor_manager()->IsCursorVisible());

  base::MessageLoop::current()->DeleteSoon(
      FROM_HERE, chromeos::LoginDisplayHostImpl::default_host());

  TestSystemTrayIsVisible();
}

// Verifies that the webui for login comes up successfully.
IN_PROC_BROWSER_TEST_F(LoginSigninTest, WebUIVisible) {
  base::TimeDelta no_timeout;
  EXPECT_TRUE(tracing::WaitForWatchEvent(no_timeout));
  std::string json_events;
  ASSERT_TRUE(tracing::EndTracing(&json_events));

  TestSystemTrayIsVisible();
}

}  // namespace
<|endoftext|>


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

#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/test_extension_loader.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/site_instance.h"
#include "chrome/browser/views/extensions/extension_shelf.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 20000;

// The extensions we're using as our test case.
const char* kGoodExtension1Id = "00123456789abcdef0123456789abcdef0123456";
const char* kGoodCrxId        = "00123456789abcdef0123456789abcdef0123456";

};  // namespace

// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionHost : public ExtensionHost {
 public:
  MockExtensionHost(Extension* extension, const GURL& url,
                    SiteInstance* instance)
      : ExtensionHost(extension, instance, url, NULL),
        got_message_(false) {
    CreateRenderView(NULL);
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kAlertTimeoutMs);
    ui_test_utils::RunMessageLoop();
  }

  virtual ExtensionFunctionDispatcher* CreateExtensionFunctionDispatcher(
      RenderViewHost* render_view_host) {
    NOTREACHED();
    return NULL;
  }

  bool got_message() { return got_message_; }
 private:
  virtual void RunJavaScriptMessage(
      const std::wstring& message,
      const std::wstring& default_prompt,
      const GURL& frame_url,
      const int flags,
      IPC::Message* reply_msg,
      bool* did_suppress_message) {
    got_message_ = true;
    MessageLoopForUI::current()->Quit();

    // Call super, otherwise we'll leak reply_msg.
    ExtensionHost::RunJavaScriptMessage(
        message, default_prompt, frame_url, flags,
        reply_msg, did_suppress_message);
  }

  bool got_message_;
};

class ExtensionViewTest : public InProcessBrowserTest {
 public:
  virtual void SetUp() {
    // Initialize the error reporter here, otherwise BrowserMain will create it
    // with the wrong MessageLoop.
    ExtensionErrorReporter::Init(false);

    // Use single-process in an attempt to speed it up and make it less flaky.
    //EnableSingleProcess();

    InProcessBrowserTest::SetUp();
  }
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kEnableExtensions);
  }
};

// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's toolstrip.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Toolstrip) {
  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Load(kGoodExtension1Id, path);
  ASSERT_TRUE(extension);
  GURL url = Extension::GetResourceURL(extension->url(), "toolstrip1.html");

  // Start the extension process and wait for it to show a javascript alert.
  MockExtensionHost host(extension, url,
      browser()->profile()->GetExtensionProcessManager()->
          GetSiteInstanceForURL(url));
  EXPECT_TRUE(host.got_message());
}

// Tests that the ExtensionShelf initializes properly, notices that
// an extension loaded and has a view available, and then sets that up
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Shelf) {
  // When initialized, there are no extension views and the preferred height
  // should be zero.
  scoped_ptr<ExtensionShelf> shelf(new ExtensionShelf(browser()));
  EXPECT_EQ(shelf->GetChildViewCount(), 0);
  EXPECT_EQ(shelf->GetPreferredSize().height(), 0);

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Load(kGoodExtension1Id, path);
  ASSERT_TRUE(extension);

  // There should now be two extension views and preferred height of the view
  // should be non-zero.
  EXPECT_EQ(shelf->GetChildViewCount(), 2);
  EXPECT_NE(shelf->GetPreferredSize().height(), 0);
}

// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Incognito) {
  // Open an incognito window to the extensions management page.  We just
  // want to make sure that we don't crash while playing with extensions when
  // this guy is around.
  Browser::OpenURLOffTheRecord(browser()->profile(),
                               GURL(chrome::kChromeUIExtensionsURL));

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").AppendASCII("good.crx");
  ASSERT_TRUE(file_util::PathExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Install(kGoodCrxId, path);
  ASSERT_TRUE(extension);

  // TODO(mpcomplete): wait for uninstall to complete?
  browser()->profile()->GetExtensionsService()->UninstallExtension(kGoodCrxId);
}
<commit_msg>Disabling a test (bug filed) that is crashing (I am not sure what the correct fix is).<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/test_extension_loader.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/site_instance.h"
#include "chrome/browser/views/extensions/extension_shelf.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 20000;

// The extensions we're using as our test case.
const char* kGoodExtension1Id = "00123456789abcdef0123456789abcdef0123456";
const char* kGoodCrxId        = "00123456789abcdef0123456789abcdef0123456";

};  // namespace

// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionHost : public ExtensionHost {
 public:
  MockExtensionHost(Extension* extension, const GURL& url,
                    SiteInstance* instance)
      : ExtensionHost(extension, instance, url, NULL),
        got_message_(false) {
    CreateRenderView(NULL);
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kAlertTimeoutMs);
    ui_test_utils::RunMessageLoop();
  }

  virtual ExtensionFunctionDispatcher* CreateExtensionFunctionDispatcher(
      RenderViewHost* render_view_host) {
    NOTREACHED();
    return NULL;
  }

  bool got_message() { return got_message_; }
 private:
  virtual void RunJavaScriptMessage(
      const std::wstring& message,
      const std::wstring& default_prompt,
      const GURL& frame_url,
      const int flags,
      IPC::Message* reply_msg,
      bool* did_suppress_message) {
    got_message_ = true;
    MessageLoopForUI::current()->Quit();

    // Call super, otherwise we'll leak reply_msg.
    ExtensionHost::RunJavaScriptMessage(
        message, default_prompt, frame_url, flags,
        reply_msg, did_suppress_message);
  }

  bool got_message_;
};

class ExtensionViewTest : public InProcessBrowserTest {
 public:
  virtual void SetUp() {
    // Initialize the error reporter here, otherwise BrowserMain will create it
    // with the wrong MessageLoop.
    ExtensionErrorReporter::Init(false);

    // Use single-process in an attempt to speed it up and make it less flaky.
    //EnableSingleProcess();

    InProcessBrowserTest::SetUp();
  }
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kEnableExtensions);
  }
};

// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's toolstrip.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Toolstrip) {
  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Load(kGoodExtension1Id, path);
  ASSERT_TRUE(extension);
  GURL url = Extension::GetResourceURL(extension->url(), "toolstrip1.html");

  // Start the extension process and wait for it to show a javascript alert.
  MockExtensionHost host(extension, url,
      browser()->profile()->GetExtensionProcessManager()->
          GetSiteInstanceForURL(url));
  EXPECT_TRUE(host.got_message());
}

// Tests that the ExtensionShelf initializes properly, notices that
// an extension loaded and has a view available, and then sets that up
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Shelf) {
  // When initialized, there are no extension views and the preferred height
  // should be zero.
  scoped_ptr<ExtensionShelf> shelf(new ExtensionShelf(browser()));
  EXPECT_EQ(shelf->GetChildViewCount(), 0);
  EXPECT_EQ(shelf->GetPreferredSize().height(), 0);

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Load(kGoodExtension1Id, path);
  ASSERT_TRUE(extension);

  // There should now be two extension views and preferred height of the view
  // should be non-zero.
  EXPECT_EQ(shelf->GetChildViewCount(), 2);
  EXPECT_NE(shelf->GetPreferredSize().height(), 0);
}

// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
// TODO(mpcomplete): http://crbug.com/14947 disabled because it crashes.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, DISABLED_Incognito) {
  // Open an incognito window to the extensions management page.  We just
  // want to make sure that we don't crash while playing with extensions when
  // this guy is around.
  Browser::OpenURLOffTheRecord(browser()->profile(),
                               GURL(chrome::kChromeUIExtensionsURL));

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").AppendASCII("good.crx");
  ASSERT_TRUE(file_util::PathExists(path));  // sanity check

  // Wait for the extension to load and grab a pointer to it.
  TestExtensionLoader loader(browser()->profile());
  Extension* extension = loader.Install(kGoodCrxId, path);
  ASSERT_TRUE(extension);

  // TODO(mpcomplete): wait for uninstall to complete?
  browser()->profile()->GetExtensionsService()->UninstallExtension(kGoodCrxId);
}
<|endoftext|>


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

#include "chrome/common/extensions/extension_switch_utils.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

namespace extensions {

namespace switch_utils {

bool IsOffStoreInstallEnabled() {
  // Disabling off-store installation is not yet implemented for Aura. Not sure
  // what the Aura equivalent for this UI is.
#if defined(USE_AURA)
  return true;
#else
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableOffStoreExtensionInstall);
#endif
}

bool IsActionBoxEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableActionBox);
}

}  // switch_utils

}  // extensions
<commit_msg>Re-enable off-store installation temporarily.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/extension_switch_utils.h"

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

namespace extensions {

namespace switch_utils {

bool IsOffStoreInstallEnabled() {
  // Disabling off-store installation is not yet implemented for Aura. Not sure
  // what the Aura equivalent for this UI is.
#if defined(USE_AURA)
  return true;
#else
  // Currently, we default to enabling off-store install.
  std::string switch_value =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kEnableOffStoreExtensionInstall);
  return switch_value != "0";
#endif
}

bool IsActionBoxEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableActionBox);
}

}  // switch_utils

}  // extensions
<|endoftext|>


<commit_before>/// \file RClusterPool.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2020-03-11
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <ROOT/RClusterPool.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RPageStorage.hxx>

#include <TError.h>

#include <algorithm>
#include <chrono>
#include <future>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <utility>

bool ROOT::Experimental::Detail::RClusterPool::RInFlightCluster::operator <(const RInFlightCluster &other) const
{
   if (fClusterId < other.fClusterId)
      return true;
   if (fClusterId > other.fClusterId)
      return false;
   if (fColumns.size() < other.fColumns.size())
      return true;
   if (fColumns.size() > other.fColumns.size())
      return false;
   for (auto itr1 = fColumns.begin(), itr2 = other.fColumns.begin(); itr1 != fColumns.end(); ++itr1, ++itr2) {
      if (*itr1 == *itr2)
         continue;
      return *itr1 < *itr2;
   }
   // *this == other
   return false;
}

ROOT::Experimental::Detail::RClusterPool::RClusterPool(RPageSource *pageSource, unsigned int size)
   : fPageSource(pageSource)
   , fPool(size, nullptr)
   , fThreadIo(&RClusterPool::ExecLoadClusters, this)
{
   R__ASSERT(size > 0);
   fWindowPre = 0;
   fWindowPost = size;
   // Large pools maintain a small look-back window together with the large look-ahead window
   while ((1u << fWindowPre) < (fWindowPost - (fWindowPre + 1))) {
      fWindowPre++;
      fWindowPost--;
   }
}

ROOT::Experimental::Detail::RClusterPool::~RClusterPool()
{
   {
      // Controlled shutdown of the I/O thread
      std::unique_lock<std::mutex> lock(fLockWorkQueue);
      fWorkQueue.emplace(RWorkItem());
      fCvHasWork.notify_one();
   }
   fThreadIo.join();
}

void ROOT::Experimental::Detail::RClusterPool::ExecLoadClusters()
{
   while (true) {
      std::vector<RWorkItem> workItems;
      {
         std::unique_lock<std::mutex> lock(fLockWorkQueue);
         fCvHasWork.wait(lock, [&]{ return !fWorkQueue.empty(); });
         while (!fWorkQueue.empty()) {
            workItems.emplace_back(std::move(fWorkQueue.front()));
            fWorkQueue.pop();
         }
      }

      for (auto &item : workItems) {
         if (item.fClusterId == kInvalidDescriptorId)
            return;

         // TODO(jblomer): the page source needs to be capable of loading multiple clusters in one go
         auto cluster = fPageSource->LoadCluster(item.fClusterId, item.fColumns);

         // Meanwhile, the user might have requested clusters outside the look-ahead window, so that we don't
         // need the cluster anymore, in which case we simply discard it right away, before moving it to the pool
         bool discard = false;
         {
            std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
            for (auto &inFlight : fInFlightClusters) {
               if (inFlight.fClusterId != item.fClusterId)
                  continue;
               discard = inFlight.fIsExpired;
               break;
            }
         }
         if (discard)
            cluster.reset();

         item.fPromise.set_value(std::move(cluster));
      }
   } // while (true)
}

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::FindInPool(DescriptorId_t clusterId)
{
   for (const auto &cptr : fPool) {
      if (cptr && (cptr->GetId() == clusterId))
         return cptr;
   }
   return nullptr;
}

size_t ROOT::Experimental::Detail::RClusterPool::FindFreeSlot() {
   auto N = fPool.size();
   for (unsigned i = 0; i < N; ++i) {
      if (!fPool[i])
         return i;
   }

   R__ASSERT(false);
   return N;
}

namespace {

/// Helper class for the (cluster, column list) pairs that should be loaded in the background
class RProvides {
   using DescriptorId_t = ROOT::Experimental::DescriptorId_t;
   using ColumnSet_t = ROOT::Experimental::Detail::RPageSource::ColumnSet_t;

private:
   std::map<DescriptorId_t, ColumnSet_t> fMap;

public:
   void Insert(DescriptorId_t clusterId, const ColumnSet_t &columns)
   {
      fMap.emplace(clusterId, columns);
   }

   bool Contains(DescriptorId_t clusterId) {
      return fMap.count(clusterId) > 0;
   }

   void Erase(DescriptorId_t clusterId, const ColumnSet_t &columns)
   {
      auto itr = fMap.find(clusterId);
      if (itr == fMap.end())
         return;
      ColumnSet_t d;
      std::copy_if(columns.begin(), columns.end(), std::inserter(d, d.end()),
         [&itr] (DescriptorId_t needle) { return itr->second.count(needle) == 0; });
      if (d.empty()) {
         fMap.erase(itr);
      } else {
         itr->second = d;
      }
   }

   decltype(fMap)::iterator begin() { return fMap.begin(); }
   decltype(fMap)::iterator end() { return fMap.end(); }
};

} // anonymous namespace

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::GetCluster(
   DescriptorId_t clusterId, const RPageSource::ColumnSet_t &columns)
{
   const auto &desc = fPageSource->GetDescriptor();

   // Determine previous cluster ids that we keep if they happen to be in the pool
   std::set<DescriptorId_t> keep;
   auto prev = clusterId;
   for (unsigned int i = 0; i < fWindowPre; ++i) {
      prev = desc.FindPrevClusterId(prev);
      if (prev == kInvalidDescriptorId)
         break;
      keep.insert(prev);
   }

   // Determine following cluster ids and the column ids that we want to make available
   RProvides provide;
   provide.Insert(clusterId, columns);
   auto next = clusterId;
   for (unsigned int i = 1; i < fWindowPost; ++i) {
      next = desc.FindNextClusterId(next);
      if (next == kInvalidDescriptorId)
         break;
      provide.Insert(next, columns);
   }

   // Clear the cache from clusters not the in the look-ahead or the look-back window
   for (auto &cptr : fPool) {
      if (!cptr)
         continue;
      if (provide.Contains(cptr->GetId()) > 0)
         continue;
      if (keep.count(cptr->GetId()) > 0)
         continue;
      cptr.reset();
   }

   // Move clusters that meanwhile arrived into cache pool
   {
      std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
      for (auto itr = fInFlightClusters.begin(); itr != fInFlightClusters.end(); ) {
         R__ASSERT(itr->fFuture.valid());
         itr->fIsExpired = !provide.Contains(itr->fClusterId) && (keep.count(itr->fClusterId) == 0);

         if (itr->fFuture.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
            // Remove the set of columns that are already scheduled for being loaded
            provide.Erase(itr->fClusterId, itr->fColumns);
            ++itr;
            continue;
         }

         auto cptr = itr->fFuture.get();
         // If cptr is nullptr, the cluster expired previously and was released by the I/O thread
         if (!cptr || itr->fIsExpired) {
            cptr.reset();
            itr = fInFlightClusters.erase(itr);
            continue;
         }

         // We either put a fresh cluster into a free slot or we merge the cluster with an existing one
         auto existingCluster = FindInPool(cptr->GetId());
         if (existingCluster) {
            existingCluster->MergeCluster(std::move(*cptr));
         } else {
            auto idxFreeSlot = FindFreeSlot();
            fPool[idxFreeSlot] = std::move(cptr);
         }
         itr = fInFlightClusters.erase(itr);
      }

      // Determine clusters which get triggered for background loading
      for (auto &cptr : fPool) {
         if (!cptr)
            continue;
         provide.Erase(cptr->GetId(), cptr->GetAvailColumns());
      }

      // Update the work queue and the in-flight cluster list with new requests
      // The work queue lock is taken while we hold the in flight clusters lock.  There is no other
      // spot where both locks are held concurrently.  In particular, the locks are never taken in reversed order
      // and there is no risk of a deadlock.
      // TODO(jblomer): we should ensure that clusterId is given first to the I/O thread.  That is usually the
      // case but it's not ensured by the code
      std::unique_lock<std::mutex> lockWorkQueue(fLockWorkQueue);
      for (const auto &kv : provide) {
         R__ASSERT(!kv.second.empty());

         RWorkItem workItem;
         workItem.fClusterId = kv.first;
         workItem.fColumns = kv.second;

         RInFlightCluster inFlightCluster;
         inFlightCluster.fClusterId = kv.first;
         inFlightCluster.fColumns = kv.second;
         inFlightCluster.fFuture = workItem.fPromise.get_future();
         fInFlightClusters.emplace_back(std::move(inFlightCluster));

         fWorkQueue.emplace(std::move(workItem));
      }
      if (fWorkQueue.size() > 0)
         fCvHasWork.notify_one();
   } // work queue and in-flight clusters lock guards

   return WaitFor(clusterId, columns);
}

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::WaitFor(
   DescriptorId_t clusterId, const RPageSource::ColumnSet_t &columns)
{
   while (true) {
      // Fast exit: the cluster happens to be already present in the cache pool
      auto result = FindInPool(clusterId);
      if (result) {
         bool hasMissingColumn = false;
         for (auto cid : columns) {
            if (result->ContainsColumn(cid))
               continue;

            hasMissingColumn = true;
            break;
         }
         if (!hasMissingColumn)
            return result;
      }

      // Otherwise the missing data must have been triggered for loading by now, so block and wait
      auto itr = fInFlightClusters.begin();
      for (; itr != fInFlightClusters.end(); ++itr) {
         if (itr->fClusterId == clusterId)
            break;
      }
      R__ASSERT(itr != fInFlightClusters.end());

      auto cptr = itr->fFuture.get();
      if (result) {
         result->MergeCluster(std::move(*cptr));
      } else {
         auto idxFreeSlot = FindFreeSlot();
         fPool[idxFreeSlot] = std::move(cptr);
      }

      std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
      fInFlightClusters.erase(itr);
   }
}
<commit_msg>[ntuple] fix up set difference calculation<commit_after>/// \file RClusterPool.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2020-03-11
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <ROOT/RClusterPool.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RPageStorage.hxx>

#include <TError.h>

#include <algorithm>
#include <chrono>
#include <future>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <utility>

bool ROOT::Experimental::Detail::RClusterPool::RInFlightCluster::operator <(const RInFlightCluster &other) const
{
   if (fClusterId < other.fClusterId)
      return true;
   if (fClusterId > other.fClusterId)
      return false;
   if (fColumns.size() < other.fColumns.size())
      return true;
   if (fColumns.size() > other.fColumns.size())
      return false;
   for (auto itr1 = fColumns.begin(), itr2 = other.fColumns.begin(); itr1 != fColumns.end(); ++itr1, ++itr2) {
      if (*itr1 == *itr2)
         continue;
      return *itr1 < *itr2;
   }
   // *this == other
   return false;
}

ROOT::Experimental::Detail::RClusterPool::RClusterPool(RPageSource *pageSource, unsigned int size)
   : fPageSource(pageSource)
   , fPool(size, nullptr)
   , fThreadIo(&RClusterPool::ExecLoadClusters, this)
{
   R__ASSERT(size > 0);
   fWindowPre = 0;
   fWindowPost = size;
   // Large pools maintain a small look-back window together with the large look-ahead window
   while ((1u << fWindowPre) < (fWindowPost - (fWindowPre + 1))) {
      fWindowPre++;
      fWindowPost--;
   }
}

ROOT::Experimental::Detail::RClusterPool::~RClusterPool()
{
   {
      // Controlled shutdown of the I/O thread
      std::unique_lock<std::mutex> lock(fLockWorkQueue);
      fWorkQueue.emplace(RWorkItem());
      fCvHasWork.notify_one();
   }
   fThreadIo.join();
}

void ROOT::Experimental::Detail::RClusterPool::ExecLoadClusters()
{
   while (true) {
      std::vector<RWorkItem> workItems;
      {
         std::unique_lock<std::mutex> lock(fLockWorkQueue);
         fCvHasWork.wait(lock, [&]{ return !fWorkQueue.empty(); });
         while (!fWorkQueue.empty()) {
            workItems.emplace_back(std::move(fWorkQueue.front()));
            fWorkQueue.pop();
         }
      }

      for (auto &item : workItems) {
         if (item.fClusterId == kInvalidDescriptorId)
            return;

         // TODO(jblomer): the page source needs to be capable of loading multiple clusters in one go
         auto cluster = fPageSource->LoadCluster(item.fClusterId, item.fColumns);

         // Meanwhile, the user might have requested clusters outside the look-ahead window, so that we don't
         // need the cluster anymore, in which case we simply discard it right away, before moving it to the pool
         bool discard = false;
         {
            std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
            for (auto &inFlight : fInFlightClusters) {
               if (inFlight.fClusterId != item.fClusterId)
                  continue;
               discard = inFlight.fIsExpired;
               break;
            }
         }
         if (discard)
            cluster.reset();

         item.fPromise.set_value(std::move(cluster));
      }
   } // while (true)
}

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::FindInPool(DescriptorId_t clusterId)
{
   for (const auto &cptr : fPool) {
      if (cptr && (cptr->GetId() == clusterId))
         return cptr;
   }
   return nullptr;
}

size_t ROOT::Experimental::Detail::RClusterPool::FindFreeSlot() {
   auto N = fPool.size();
   for (unsigned i = 0; i < N; ++i) {
      if (!fPool[i])
         return i;
   }

   R__ASSERT(false);
   return N;
}

namespace {

/// Helper class for the (cluster, column list) pairs that should be loaded in the background
class RProvides {
   using DescriptorId_t = ROOT::Experimental::DescriptorId_t;
   using ColumnSet_t = ROOT::Experimental::Detail::RPageSource::ColumnSet_t;

private:
   std::map<DescriptorId_t, ColumnSet_t> fMap;

public:
   void Insert(DescriptorId_t clusterId, const ColumnSet_t &columns)
   {
      fMap.emplace(clusterId, columns);
   }

   bool Contains(DescriptorId_t clusterId) {
      return fMap.count(clusterId) > 0;
   }

   void Erase(DescriptorId_t clusterId, const ColumnSet_t &columns)
   {
      auto itr = fMap.find(clusterId);
      if (itr == fMap.end())
         return;
      ColumnSet_t d;
      std::copy_if(itr->second.begin(), itr->second.end(), std::inserter(d, d.end()),
         [&columns] (DescriptorId_t needle) { return columns.count(needle) == 0; });
      if (d.empty()) {
         fMap.erase(itr);
      } else {
         itr->second = d;
      }
   }

   decltype(fMap)::iterator begin() { return fMap.begin(); }
   decltype(fMap)::iterator end() { return fMap.end(); }
};

} // anonymous namespace

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::GetCluster(
   DescriptorId_t clusterId, const RPageSource::ColumnSet_t &columns)
{
   const auto &desc = fPageSource->GetDescriptor();

   // Determine previous cluster ids that we keep if they happen to be in the pool
   std::set<DescriptorId_t> keep;
   auto prev = clusterId;
   for (unsigned int i = 0; i < fWindowPre; ++i) {
      prev = desc.FindPrevClusterId(prev);
      if (prev == kInvalidDescriptorId)
         break;
      keep.insert(prev);
   }

   // Determine following cluster ids and the column ids that we want to make available
   RProvides provide;
   provide.Insert(clusterId, columns);
   auto next = clusterId;
   for (unsigned int i = 1; i < fWindowPost; ++i) {
      next = desc.FindNextClusterId(next);
      if (next == kInvalidDescriptorId)
         break;
      provide.Insert(next, columns);
   }

   // Clear the cache from clusters not the in the look-ahead or the look-back window
   for (auto &cptr : fPool) {
      if (!cptr)
         continue;
      if (provide.Contains(cptr->GetId()) > 0)
         continue;
      if (keep.count(cptr->GetId()) > 0)
         continue;
      cptr.reset();
   }

   // Move clusters that meanwhile arrived into cache pool
   {
      std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
      for (auto itr = fInFlightClusters.begin(); itr != fInFlightClusters.end(); ) {
         R__ASSERT(itr->fFuture.valid());
         itr->fIsExpired = !provide.Contains(itr->fClusterId) && (keep.count(itr->fClusterId) == 0);

         if (itr->fFuture.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
            // Remove the set of columns that are already scheduled for being loaded
            provide.Erase(itr->fClusterId, itr->fColumns);
            ++itr;
            continue;
         }

         auto cptr = itr->fFuture.get();
         // If cptr is nullptr, the cluster expired previously and was released by the I/O thread
         if (!cptr || itr->fIsExpired) {
            cptr.reset();
            itr = fInFlightClusters.erase(itr);
            continue;
         }

         // We either put a fresh cluster into a free slot or we merge the cluster with an existing one
         auto existingCluster = FindInPool(cptr->GetId());
         if (existingCluster) {
            existingCluster->MergeCluster(std::move(*cptr));
         } else {
            auto idxFreeSlot = FindFreeSlot();
            fPool[idxFreeSlot] = std::move(cptr);
         }
         itr = fInFlightClusters.erase(itr);
      }

      // Determine clusters which get triggered for background loading
      for (auto &cptr : fPool) {
         if (!cptr)
            continue;
         provide.Erase(cptr->GetId(), cptr->GetAvailColumns());
      }

      // Update the work queue and the in-flight cluster list with new requests
      // The work queue lock is taken while we hold the in flight clusters lock.  There is no other
      // spot where both locks are held concurrently.  In particular, the locks are never taken in reversed order
      // and there is no risk of a deadlock.
      // TODO(jblomer): we should ensure that clusterId is given first to the I/O thread.  That is usually the
      // case but it's not ensured by the code
      std::unique_lock<std::mutex> lockWorkQueue(fLockWorkQueue);
      for (const auto &kv : provide) {
         R__ASSERT(!kv.second.empty());

         RWorkItem workItem;
         workItem.fClusterId = kv.first;
         workItem.fColumns = kv.second;

         RInFlightCluster inFlightCluster;
         inFlightCluster.fClusterId = kv.first;
         inFlightCluster.fColumns = kv.second;
         inFlightCluster.fFuture = workItem.fPromise.get_future();
         fInFlightClusters.emplace_back(std::move(inFlightCluster));

         fWorkQueue.emplace(std::move(workItem));
      }
      if (fWorkQueue.size() > 0)
         fCvHasWork.notify_one();
   } // work queue and in-flight clusters lock guards

   return WaitFor(clusterId, columns);
}

std::shared_ptr<ROOT::Experimental::Detail::RCluster>
ROOT::Experimental::Detail::RClusterPool::WaitFor(
   DescriptorId_t clusterId, const RPageSource::ColumnSet_t &columns)
{
   while (true) {
      // Fast exit: the cluster happens to be already present in the cache pool
      auto result = FindInPool(clusterId);
      if (result) {
         bool hasMissingColumn = false;
         for (auto cid : columns) {
            if (result->ContainsColumn(cid))
               continue;

            hasMissingColumn = true;
            break;
         }
         if (!hasMissingColumn)
            return result;
      }

      // Otherwise the missing data must have been triggered for loading by now, so block and wait
      auto itr = fInFlightClusters.begin();
      for (; itr != fInFlightClusters.end(); ++itr) {
         if (itr->fClusterId == clusterId)
            break;
      }
      R__ASSERT(itr != fInFlightClusters.end());

      auto cptr = itr->fFuture.get();
      if (result) {
         result->MergeCluster(std::move(*cptr));
      } else {
         auto idxFreeSlot = FindFreeSlot();
         fPool[idxFreeSlot] = std::move(cptr);
      }

      std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockInFlightClusters);
      fInFlightClusters.erase(itr);
   }
}
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/MetaTypeRegistrar.h"

namespace joynr
{

MetaTypeRegistrar* MetaTypeRegistrar::registrarInstance = 0;

MetaTypeRegistrar::MetaTypeRegistrar()
        : publicationInterpreters(),
          publicationInterpretersMutex(),
          replyInterpreters(),
          replyInterpretersMutex()
{
    // Register known types
    registerMetaType<std::string>();
    registerMetaType<bool>();
    registerMetaType<float>();
    registerMetaType<double>();
    registerMetaType<int8_t>();
    registerMetaType<uint8_t>();
    registerMetaType<int16_t>();
    registerMetaType<uint16_t>();
    registerMetaType<int32_t>();
    registerMetaType<uint32_t>();
    registerMetaType<int64_t>();
    registerMetaType<uint64_t>();

    // Register a reply interpreter for void type
    std::lock_guard<std::mutex> lock(replyInterpretersMutex);
    replyInterpreters.insert({Util::getTypeId<void>(), new ReplyInterpreter<void>()});
}

MetaTypeRegistrar& MetaTypeRegistrar::instance()
{
    static std::mutex mutex;

    // Use double-checked locking so that, under normal use, a
    // mutex lock is not required.
    if (!registrarInstance) {
        std::lock_guard<std::mutex> lock(mutex);
        if (!registrarInstance) {
            registrarInstance = new MetaTypeRegistrar();
        }
    }

    return *registrarInstance;
}

IPublicationInterpreter& MetaTypeRegistrar::getPublicationInterpreter(int typeId)
{
    std::lock_guard<std::mutex> lock(publicationInterpretersMutex);

    IPublicationInterpreter* ret;
    auto search = publicationInterpreters.find(typeId);
    if (search != publicationInterpreters.end()) {
        ret = search->second;
    }

    // It is a programming error if the interpreter does not exist
    assert(ret);
    return *ret;
}

IReplyInterpreter& MetaTypeRegistrar::getReplyInterpreter(int typeId)
{
    std::lock_guard<std::mutex> lock(replyInterpretersMutex);

    IReplyInterpreter* ret;
    auto search = replyInterpreters.find(typeId);
    if (search != replyInterpreters.end()) {
        ret = search->second;
    }

    // It is a programming error if the interpreter does not exist
    assert(ret);
    return *ret;
}

} // namespace joynr
<commit_msg>[C++] fixed missing initialization of pointer<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/MetaTypeRegistrar.h"

namespace joynr
{

MetaTypeRegistrar* MetaTypeRegistrar::registrarInstance = 0;

MetaTypeRegistrar::MetaTypeRegistrar()
        : publicationInterpreters(),
          publicationInterpretersMutex(),
          replyInterpreters(),
          replyInterpretersMutex()
{
    // Register known types
    registerMetaType<std::string>();
    registerMetaType<bool>();
    registerMetaType<float>();
    registerMetaType<double>();
    registerMetaType<int8_t>();
    registerMetaType<uint8_t>();
    registerMetaType<int16_t>();
    registerMetaType<uint16_t>();
    registerMetaType<int32_t>();
    registerMetaType<uint32_t>();
    registerMetaType<int64_t>();
    registerMetaType<uint64_t>();

    // Register a reply interpreter for void type
    std::lock_guard<std::mutex> lock(replyInterpretersMutex);
    replyInterpreters.insert({Util::getTypeId<void>(), new ReplyInterpreter<void>()});
}

MetaTypeRegistrar& MetaTypeRegistrar::instance()
{
    static std::mutex mutex;

    // Use double-checked locking so that, under normal use, a
    // mutex lock is not required.
    if (!registrarInstance) {
        std::lock_guard<std::mutex> lock(mutex);
        if (!registrarInstance) {
            registrarInstance = new MetaTypeRegistrar();
        }
    }

    return *registrarInstance;
}

IPublicationInterpreter& MetaTypeRegistrar::getPublicationInterpreter(int typeId)
{
    std::lock_guard<std::mutex> lock(publicationInterpretersMutex);

    IPublicationInterpreter* ret = nullptr;
    auto search = publicationInterpreters.find(typeId);
    if (search != publicationInterpreters.end()) {
        ret = search->second;
    }

    // It is a programming error if the interpreter does not exist
    assert(ret);
    return *ret;
}

IReplyInterpreter& MetaTypeRegistrar::getReplyInterpreter(int typeId)
{
    std::lock_guard<std::mutex> lock(replyInterpretersMutex);

    IReplyInterpreter* ret = nullptr;
    auto search = replyInterpreters.find(typeId);
    if (search != replyInterpreters.end()) {
        ret = search->second;
    }

    // It is a programming error if the interpreter does not exist
    assert(ret);
    return *ret;
}

} // namespace joynr
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "EC_3DCanvasSource.h"

#include "EC_3DCanvas.h"
#include "EC_Mesh.h"
#include "EC_OgreCustomObject.h"
#include "IModule.h"
#include "ModuleManager.h"
#include "Entity.h"
#include "UiProxyWidget.h"
#include "UiServiceInterface.h"
#include "LoggingFunctions.h"

DEFINE_POCO_LOGGING_FUNCTIONS("EC_3DCanvasSource")

#include <QWebView>
#include <QLineEdit>
#include <QApplication>
#include <QPushButton>
#include <QUiLoader>
#include <QVBoxLayout>

#include "MemoryLeakCheck.h"

EC_3DCanvasSource::EC_3DCanvasSource(IModule *module) :
    IComponent(module->GetFramework()),
    source(this, "source"),
    position(this, "position", 0),
    submesh(this, "submesh", 0),
    show2d(this, "show 2D", true),
    widget_(0),
    content_widget_(0),
    placeholder_widget_(0),
    proxy_(0),
    source_edit_(0),
    manipulate_ec_3dcanvas(true)
{
    connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(UpdateWidgetAndCanvas()));
    connect(this, SIGNAL(ParentEntitySet()), this, SLOT(RegisterActions()));
    CreateWidget();
}

EC_3DCanvasSource::~EC_3DCanvasSource()
{
    // Note: content widget is inside widget_s layout,
    // no need to do a separate deleteLater for it. This would cause problems on rundown.
    SAFE_DELETE_LATER(widget_);
}

void EC_3DCanvasSource::OnClick()
{
    if ((getshow2d() == true) && (widget_) && (proxy_))
    {
        if (proxy_->isVisible())
            proxy_->AnimatedHide();
        else
            proxy_->show();
    }
}

void EC_3DCanvasSource::SourceEdited()
{
    QString new_source = source_edit_->text();
    if (new_source != getsource())
    {
        // Replicate changed source to network
        // std::cout << "Changed source to " << new_source << std::endl;
        setsource(new_source);
        ComponentChanged(AttributeChange::Default);
    }
}

void EC_3DCanvasSource::StartPressed()
{
}

void EC_3DCanvasSource::PrevPressed()
{
}

void EC_3DCanvasSource::NextPressed()
{
}

void EC_3DCanvasSource::EndPressed()
{
}

void EC_3DCanvasSource::UpdateWidgetAndCanvas()
{
    UpdateWidget();
    UpdateCanvas();
}

void EC_3DCanvasSource::WebViewLinkClicked(const QUrl& url)
{
    //! \todo: check here if the link is something we want to open differently (external program etc.)

    // If url is different than the source, update the lineedit & browser & replicate to network
    QString url_str = url.toString();
    if (url_str != getsource())
    {
        QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);
        if (!webwidget)
            return;
        webwidget->setUrl(url);

        if (source_edit_)
            source_edit_->setText(url_str);

        // Set last_source now so that we won't trigger reload of the page again when the source comes back from network
        last_source_ = url_str;

        // std::cout << "Changed source by click to " << url_str << std::endl;
        setsource(url_str);
        ComponentChanged(AttributeChange::Default);
    }
}

void EC_3DCanvasSource::RepaintCanvas()
{
    if (!manipulate_ec_3dcanvas)
        return;

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
        return;

    ComponentPtr comp = entity->GetComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
        return;

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    canvas->Start();
}

void EC_3DCanvasSource::UpdateWidget()
{
    QString source = getsource();
    if (source.isEmpty())
    {
        QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));
        return;
    }

    if (source != last_source_)
    {
        if (source_edit_)
            source_edit_->setText(source);

        last_source_ = source;
        if (!placeholder_widget_)
        {
            LogError("No placeholder widget, cannot create content widget");
            return;
        }

        // See if source looks like an url, and instantiate a QWebView then if it doesn't already exist
        if (source.indexOf("http://") != -1)
        {
            QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);
            if (!webwidget)
            {
                // If widget exists, but is wrong type, delete and recreate
                if (content_widget_)
                {
                    content_widget_->deleteLater();
                    content_widget_ = 0;
                }

                webwidget = new QWebView(placeholder_widget_);
                QVBoxLayout *layout = placeholder_widget_->findChild<QVBoxLayout*>("widget_placeholder_layout");
                if (layout)
                    layout->addWidget(webwidget);

                webwidget->setUrl(QUrl(source));
                webwidget->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
                content_widget_ = webwidget;

                connect(webwidget, SIGNAL(loadFinished( bool )), this, SLOT(RepaintCanvas()));
                connect(webwidget, SIGNAL(loadProgress( int )), this, SLOT(RepaintCanvas()));
                connect(webwidget, SIGNAL(linkClicked( const QUrl & )), this, SLOT(WebViewLinkClicked( const QUrl & )));
                connect(webwidget->page(), SIGNAL(scrollRequested( int, int, const QRect & )), this, SLOT(RepaintCanvas()));
            }
            else
            {
                // If source changed, update the webview URL
                webwidget->setUrl(QUrl(source));
            }
        }
    }
}

void EC_3DCanvasSource::UpdateCanvas()
{
    if (!content_widget_ || !manipulate_ec_3dcanvas)
        return;

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
    {
        LogError("No parent entity, cannot create/update 3DCanvas");
        return;
    }

    ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
    {
        LogError("Could not create/get 3DCanvas component");
        return;
    }

    // If entity has no valid mesh or prim yet, start a retry timer and try to set the canvas later
    if ((!entity->GetComponent(EC_Mesh::TypeNameStatic())) &&
        (!entity->GetComponent(EC_OgreCustomObject::TypeNameStatic())))
    {
        //LogInfo("Mesh or prim did not exist yet, retrying");
        QTimer::singleShot(1000, this, SLOT(UpdateCanvas()));
        return;
    }

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    canvas->SetWidget(content_widget_);
    int submesh = getsubmesh();
    if (submesh < 0)
        submesh = 0;
    canvas->SetSubmesh(submesh);
    canvas->Start();
}

void EC_3DCanvasSource::FetchWebViewUrl()
{
    // Workaround on the bug that ec_3canvas->webview()->url() is not valid when this component is created/updated.
    // Somehow its doesent have time to set it before we already come here. So this polls untill the url is valid.

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
    {
        LogError("No parent entity, cannot create/update 3DCanvas");
        return;
    }

    ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
    {
        LogError("Could not create/get 3DCanvas component");
        return;
    }

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    QWidget *canvas_widget = canvas->GetWidget();
    if (!canvas_widget)
        return;
    QWebView *canvas_webview = dynamic_cast<QWebView*>(canvas_widget);
    if (!canvas_webview)
        return;
    QString url = canvas_webview->url().toString();
    if (!url.isEmpty())
    {
        setsource(url);
        ComponentChanged(AttributeChange::LocalOnly);
    }
    else
        QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));
}

void EC_3DCanvasSource::ChangeLanguage()
{
    if (widget_)
    {
        QString title = tr("3DCanvas Controls");
        widget_->setWindowTitle(title);
    }
}

void EC_3DCanvasSource::CreateWidget()
{
    UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();
    if (!ui)
    {
        LogError("Failed to acquire UI service");
        return;
    }

    QUiLoader loader;
    loader.setLanguageChangeEnabled(true);
    QFile file("./data/ui/3dcanvassource.ui");
    file.open(QFile::ReadOnly);
    widget_ = loader.load(&file);
    file.close();

    if (!widget_)
    {
        LogError("Failed to create 3D canvas controls widget");
        return;
    }

    widget_->setWindowTitle(tr("3DCanvas Controls"));
    proxy_ = ui->AddWidgetToScene(widget_);

    connect(qApp, SIGNAL(LanguageChanged()), this, SLOT(ChangeLanguage()));

    source_edit_ = widget_->findChild<QLineEdit*>("line_source");
    if (source_edit_)
    {
        connect(source_edit_, SIGNAL( editingFinished() ), this, SLOT( SourceEdited() ));
    }

    placeholder_widget_ = widget_->findChild<QWidget*>("widget_placeholder");

    QPushButton* button = widget_->findChild<QPushButton*>("but_start");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( StartPressed() ));
    button = widget_->findChild<QPushButton*>("but_prev");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( PrevPressed() ));
    button = widget_->findChild<QPushButton*>("but_next");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( NextPressed() ));
    button = widget_->findChild<QPushButton*>("but_end");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( EndPressed() ));
}

void EC_3DCanvasSource::RegisterActions()
{
    Scene::Entity *entity = GetParentEntity();
    assert(entity);
    if (entity)
        entity->ConnectAction("MousePress", this, SLOT(OnClick()));
}

<commit_msg>3D webview 2D widget wont show on click events if its scene is not active. So now it does not try to show when you click on entities in build mode that have the 3D webview<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "EC_3DCanvasSource.h"

#include "EC_3DCanvas.h"
#include "EC_Mesh.h"
#include "EC_OgreCustomObject.h"
#include "IModule.h"
#include "ModuleManager.h"
#include "Entity.h"
#include "UiProxyWidget.h"
#include "UiServiceInterface.h"
#include "LoggingFunctions.h"

DEFINE_POCO_LOGGING_FUNCTIONS("EC_3DCanvasSource")

#include <QWebView>
#include <QLineEdit>
#include <QApplication>
#include <QPushButton>
#include <QUiLoader>
#include <QVBoxLayout>
#include <QGraphicsScene>

#include "MemoryLeakCheck.h"

EC_3DCanvasSource::EC_3DCanvasSource(IModule *module) :
    IComponent(module->GetFramework()),
    source(this, "source"),
    position(this, "position", 0),
    submesh(this, "submesh", 0),
    show2d(this, "show 2D", true),
    widget_(0),
    content_widget_(0),
    placeholder_widget_(0),
    proxy_(0),
    source_edit_(0),
    manipulate_ec_3dcanvas(true)
{
    connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(UpdateWidgetAndCanvas()));
    connect(this, SIGNAL(ParentEntitySet()), this, SLOT(RegisterActions()));
    CreateWidget();
}

EC_3DCanvasSource::~EC_3DCanvasSource()
{
    // Note: content widget is inside widget_s layout,
    // no need to do a separate deleteLater for it. This would cause problems on rundown.
    SAFE_DELETE_LATER(widget_);
}

void EC_3DCanvasSource::OnClick()
{
    if ((getshow2d() == true) && (widget_) && (proxy_))
    {
        if (!proxy_->scene())
            return;
        if (!proxy_->scene()->isActive())
            return;
        if (proxy_->isVisible())
            proxy_->AnimatedHide();
        else
            proxy_->show();
    }
}

void EC_3DCanvasSource::SourceEdited()
{
    QString new_source = source_edit_->text();
    if (new_source != getsource())
    {
        // Replicate changed source to network
        // std::cout << "Changed source to " << new_source << std::endl;
        setsource(new_source);
        ComponentChanged(AttributeChange::Default);
    }
}

void EC_3DCanvasSource::StartPressed()
{
}

void EC_3DCanvasSource::PrevPressed()
{
}

void EC_3DCanvasSource::NextPressed()
{
}

void EC_3DCanvasSource::EndPressed()
{
}

void EC_3DCanvasSource::UpdateWidgetAndCanvas()
{
    UpdateWidget();
    UpdateCanvas();
}

void EC_3DCanvasSource::WebViewLinkClicked(const QUrl& url)
{
    //! \todo: check here if the link is something we want to open differently (external program etc.)

    // If url is different than the source, update the lineedit & browser & replicate to network
    QString url_str = url.toString();
    if (url_str != getsource())
    {
        QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);
        if (!webwidget)
            return;
        webwidget->setUrl(url);

        if (source_edit_)
            source_edit_->setText(url_str);

        // Set last_source now so that we won't trigger reload of the page again when the source comes back from network
        last_source_ = url_str;

        // std::cout << "Changed source by click to " << url_str << std::endl;
        setsource(url_str);
        ComponentChanged(AttributeChange::Default);
    }
}

void EC_3DCanvasSource::RepaintCanvas()
{
    if (!manipulate_ec_3dcanvas)
        return;

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
        return;

    ComponentPtr comp = entity->GetComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
        return;

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    canvas->Start();
}

void EC_3DCanvasSource::UpdateWidget()
{
    QString source = getsource();
    if (source.isEmpty())
    {
        QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));
        return;
    }

    if (source != last_source_)
    {
        if (source_edit_)
            source_edit_->setText(source);

        last_source_ = source;
        if (!placeholder_widget_)
        {
            LogError("No placeholder widget, cannot create content widget");
            return;
        }

        // See if source looks like an url, and instantiate a QWebView then if it doesn't already exist
        if (source.indexOf("http://") != -1)
        {
            QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);
            if (!webwidget)
            {
                // If widget exists, but is wrong type, delete and recreate
                if (content_widget_)
                {
                    content_widget_->deleteLater();
                    content_widget_ = 0;
                }

                webwidget = new QWebView(placeholder_widget_);
                QVBoxLayout *layout = placeholder_widget_->findChild<QVBoxLayout*>("widget_placeholder_layout");
                if (layout)
                    layout->addWidget(webwidget);

                webwidget->setUrl(QUrl(source));
                webwidget->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
                content_widget_ = webwidget;

                connect(webwidget, SIGNAL(loadFinished( bool )), this, SLOT(RepaintCanvas()));
                connect(webwidget, SIGNAL(loadProgress( int )), this, SLOT(RepaintCanvas()));
                connect(webwidget, SIGNAL(linkClicked( const QUrl & )), this, SLOT(WebViewLinkClicked( const QUrl & )));
                connect(webwidget->page(), SIGNAL(scrollRequested( int, int, const QRect & )), this, SLOT(RepaintCanvas()));
            }
            else
            {
                // If source changed, update the webview URL
                webwidget->setUrl(QUrl(source));
            }
        }
    }
}

void EC_3DCanvasSource::UpdateCanvas()
{
    if (!content_widget_ || !manipulate_ec_3dcanvas)
        return;

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
    {
        LogError("No parent entity, cannot create/update 3DCanvas");
        return;
    }

    ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
    {
        LogError("Could not create/get 3DCanvas component");
        return;
    }

    // If entity has no valid mesh or prim yet, start a retry timer and try to set the canvas later
    if ((!entity->GetComponent(EC_Mesh::TypeNameStatic())) &&
        (!entity->GetComponent(EC_OgreCustomObject::TypeNameStatic())))
    {
        //LogInfo("Mesh or prim did not exist yet, retrying");
        QTimer::singleShot(1000, this, SLOT(UpdateCanvas()));
        return;
    }

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    canvas->SetWidget(content_widget_);
    int submesh = getsubmesh();
    if (submesh < 0)
        submesh = 0;
    canvas->SetSubmesh(submesh);
    canvas->Start();
}

void EC_3DCanvasSource::FetchWebViewUrl()
{
    // Workaround on the bug that ec_3canvas->webview()->url() is not valid when this component is created/updated.
    // Somehow its doesent have time to set it before we already come here. So this polls untill the url is valid.

    Scene::Entity* entity = GetParentEntity();
    if (!entity)
    {
        LogError("No parent entity, cannot create/update 3DCanvas");
        return;
    }

    ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());
    if (!comp)
    {
        LogError("Could not create/get 3DCanvas component");
        return;
    }

    EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());
    QWidget *canvas_widget = canvas->GetWidget();
    if (!canvas_widget)
        return;
    QWebView *canvas_webview = dynamic_cast<QWebView*>(canvas_widget);
    if (!canvas_webview)
        return;
    QString url = canvas_webview->url().toString();
    if (!url.isEmpty())
    {
        setsource(url);
        ComponentChanged(AttributeChange::LocalOnly);
    }
    else
        QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));
}

void EC_3DCanvasSource::ChangeLanguage()
{
    if (widget_)
    {
        QString title = tr("3DCanvas Controls");
        widget_->setWindowTitle(title);
    }
}

void EC_3DCanvasSource::CreateWidget()
{
    UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();
    if (!ui)
    {
        LogError("Failed to acquire UI service");
        return;
    }

    QUiLoader loader;
    loader.setLanguageChangeEnabled(true);
    QFile file("./data/ui/3dcanvassource.ui");
    file.open(QFile::ReadOnly);
    widget_ = loader.load(&file);
    file.close();

    if (!widget_)
    {
        LogError("Failed to create 3D canvas controls widget");
        return;
    }

    widget_->setWindowTitle(tr("3DCanvas Controls"));
    proxy_ = ui->AddWidgetToScene(widget_);

    connect(qApp, SIGNAL(LanguageChanged()), this, SLOT(ChangeLanguage()));

    source_edit_ = widget_->findChild<QLineEdit*>("line_source");
    if (source_edit_)
    {
        connect(source_edit_, SIGNAL( editingFinished() ), this, SLOT( SourceEdited() ));
    }

    placeholder_widget_ = widget_->findChild<QWidget*>("widget_placeholder");

    QPushButton* button = widget_->findChild<QPushButton*>("but_start");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( StartPressed() ));
    button = widget_->findChild<QPushButton*>("but_prev");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( PrevPressed() ));
    button = widget_->findChild<QPushButton*>("but_next");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( NextPressed() ));
    button = widget_->findChild<QPushButton*>("but_end");
    if (button) connect(button, SIGNAL( clicked() ), this, SLOT( EndPressed() ));
}

void EC_3DCanvasSource::RegisterActions()
{
    Scene::Entity *entity = GetParentEntity();
    assert(entity);
    if (entity)
        entity->ConnectAction("MousePress", this, SLOT(OnClick()));
}

<|endoftext|>