<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Michal Uricar
 * Copyright (C) 2012 Michal Uricar
 */

#include <shogun/structure/DualLibQPBMSOSVM.h>
#include <shogun/structure/libppbm.h>
#include <shogun/structure/libp3bm.h>
#include <shogun/structure/libncbm.h>

using namespace shogun;

CDualLibQPBMSOSVM::CDualLibQPBMSOSVM()
:CLinearStructuredOutputMachine()
{
}

CDualLibQPBMSOSVM::CDualLibQPBMSOSVM(
		CStructuredModel*   	model,
		CLossFunction*      	loss,
		CStructuredLabels*  	labs,
		float64_t           	_lambda,
		SGVector< float64_t >	W)
 : CLinearStructuredOutputMachine(model, loss, labs)
{
	set_TolRel(0.001);
	set_TolAbs(0.0);
	set_BufSize(1000);
	set_lambda(_lambda);
	set_cleanICP(true);
	set_cleanAfter(10);
	set_K(0.4);
	set_Tmax(100);
	set_cp_models(1);
	set_verbose(true);
	set_solver(BMRM);

	// get dimension of w
	uint32_t nDim=this->m_model->get_dim();

	// Check for initial solution
	if (W.vlen==0)
	{
		m_w=SGVector< float64_t >(nDim);

		m_w.zero();
	}
	else
	{
		set_w(W);
	}

	init();
}

CDualLibQPBMSOSVM::~CDualLibQPBMSOSVM()
{
}

void CDualLibQPBMSOSVM::init()
{
	SG_ADD(&m_TolRel, "m_TolRel", "Relative tolerance", MS_NOT_AVAILABLE);
	SG_ADD(&m_TolAbs, "m_TolAbs", "Absolute tolerance", MS_NOT_AVAILABLE);
	SG_ADD(&m_BufSize, "m_BuffSize", "Size of CP Buffer", MS_AVAILABLE);
	SG_ADD(&m_lambda, "m_lambda", "Regularization constant lambda",
			MS_AVAILABLE);
	SG_ADD(&m_cleanICP, "m_cleanICP", "Inactive cutting plane removal flag",
			MS_AVAILABLE);
	SG_ADD(&m_cleanAfter,
			"m_cleanAfter",
			"Number of inactive iterations after which ICP will be removed",
			MS_NOT_AVAILABLE);
	SG_ADD(&m_K, "m_K", "Parameter K", MS_NOT_AVAILABLE);
	SG_ADD(&m_Tmax, "m_Tmax", "Parameter Tmax", MS_AVAILABLE);
	SG_ADD(&m_cp_models, "m_cp_models", "Number of cutting plane models",
			MS_AVAILABLE);
	SG_ADD(&m_verbose, "m_verbose", "Verbosity flag", MS_AVAILABLE);
}

bool CDualLibQPBMSOSVM::train_machine(CFeatures* data)
{
	if (data)
		set_features(data);

	// call the solver
	switch(m_solver)
	{
		case BMRM:
			m_result=svm_bmrm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_verbose);
			break;
		case PPBMRM:
			m_result=svm_ppbm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_verbose);
			break;
		case P3BMRM:
			m_result=svm_p3bm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_cp_models, m_verbose);
			break;
		case NCBM:
			m_result=svm_ncbm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, true, m_verbose);
	}

	if (m_result.exitflag==1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
<commit_msg>Fix for DualLibQPBMSOSVM of calling NCBM<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Michal Uricar
 * Copyright (C) 2012 Michal Uricar
 */

#include <shogun/structure/DualLibQPBMSOSVM.h>
#include <shogun/structure/libppbm.h>
#include <shogun/structure/libp3bm.h>
#include <shogun/structure/libncbm.h>

using namespace shogun;

CDualLibQPBMSOSVM::CDualLibQPBMSOSVM()
:CLinearStructuredOutputMachine()
{
}

CDualLibQPBMSOSVM::CDualLibQPBMSOSVM(
		CStructuredModel*   	model,
		CLossFunction*      	loss,
		CStructuredLabels*  	labs,
		float64_t           	_lambda,
		SGVector< float64_t >	W)
 : CLinearStructuredOutputMachine(model, loss, labs)
{
	set_TolRel(0.001);
	set_TolAbs(0.0);
	set_BufSize(1000);
	set_lambda(_lambda);
	set_cleanICP(true);
	set_cleanAfter(10);
	set_K(0.4);
	set_Tmax(100);
	set_cp_models(1);
	set_verbose(true);
	set_solver(BMRM);

	// get dimension of w
	uint32_t nDim=this->m_model->get_dim();

	// Check for initial solution
	if (W.vlen==0)
	{
		m_w=SGVector< float64_t >(nDim);

		m_w.zero();
	}
	else
	{
		set_w(W);
	}

	init();
}

CDualLibQPBMSOSVM::~CDualLibQPBMSOSVM()
{
}

void CDualLibQPBMSOSVM::init()
{
	SG_ADD(&m_TolRel, "m_TolRel", "Relative tolerance", MS_NOT_AVAILABLE);
	SG_ADD(&m_TolAbs, "m_TolAbs", "Absolute tolerance", MS_NOT_AVAILABLE);
	SG_ADD(&m_BufSize, "m_BuffSize", "Size of CP Buffer", MS_AVAILABLE);
	SG_ADD(&m_lambda, "m_lambda", "Regularization constant lambda",
			MS_AVAILABLE);
	SG_ADD(&m_cleanICP, "m_cleanICP", "Inactive cutting plane removal flag",
			MS_AVAILABLE);
	SG_ADD(&m_cleanAfter,
			"m_cleanAfter",
			"Number of inactive iterations after which ICP will be removed",
			MS_NOT_AVAILABLE);
	SG_ADD(&m_K, "m_K", "Parameter K", MS_NOT_AVAILABLE);
	SG_ADD(&m_Tmax, "m_Tmax", "Parameter Tmax", MS_AVAILABLE);
	SG_ADD(&m_cp_models, "m_cp_models", "Number of cutting plane models",
			MS_AVAILABLE);
	SG_ADD(&m_verbose, "m_verbose", "Verbosity flag", MS_AVAILABLE);
}

bool CDualLibQPBMSOSVM::train_machine(CFeatures* data)
{
	if (data)
		set_features(data);

	// call the solver
	switch(m_solver)
	{
		case BMRM:
			m_result=svm_bmrm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_verbose);
			break;
		case PPBMRM:
			m_result=svm_ppbm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_verbose);
			break;
		case P3BMRM:
			m_result=svm_p3bm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, m_K, m_Tmax,
					m_cp_models, m_verbose);
			break;
		case NCBM:
			m_result=svm_ncbm_solver(m_model, m_w.vector, m_TolRel, m_TolAbs,
					m_lambda, m_BufSize, m_cleanICP, m_cleanAfter, true /* convex */,
					true /* use line search*/, m_verbose);
	}

	if (m_result.exitflag==1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
<|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 "chrome/browser/alternate_nav_url_fetcher.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/url_request/url_request.h"

AlternateNavURLFetcher::AlternateNavURLFetcher(
    const GURL& alternate_nav_url)
    : LinkInfoBarDelegate(NULL),
      alternate_nav_url_(alternate_nav_url),
      controller_(NULL),
      state_(NOT_STARTED),
      navigated_to_entry_(false),
      infobar_contents_(NULL) {
  registrar_.Add(this, NotificationType::NAV_ENTRY_PENDING,
                 NotificationService::AllSources());
}

void AlternateNavURLFetcher::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::NAV_ENTRY_PENDING:
      controller_ = Source<NavigationController>(source).ptr();
      DCHECK(controller_->pending_entry());

      // Unregister for this notification now that we're pending, and start
      // listening for the corresponding commit. We also need to listen for the
      // tab close command since that means the load will never commit!
      registrar_.Remove(this, NotificationType::NAV_ENTRY_PENDING,
                        NotificationService::AllSources());
      registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                     Source<NavigationController>(controller_));
      registrar_.Add(this, NotificationType::TAB_CLOSED,
                     Source<NavigationController>(controller_));

      DCHECK_EQ(NOT_STARTED, state_);
      state_ = IN_PROGRESS;
      fetcher_.reset(new URLFetcher(GURL(alternate_nav_url_), URLFetcher::HEAD,
                                    this));
      fetcher_->set_request_context(
          controller_->profile()->GetRequestContext());
      fetcher_->Start();
      break;

    case NotificationType::NAV_ENTRY_COMMITTED:
      // The page was navigated, we can show the infobar now if necessary.
      registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
                        Source<NavigationController>(controller_));
      navigated_to_entry_ = true;
      ShowInfobarIfPossible();
      break;

    case NotificationType::TAB_CLOSED:
      // We have been closed. In order to prevent the URLFetcher from trying to
      // access the controller that will be invalid, we delete ourselves.
      // This deletes the URLFetcher and insures its callback won't be called.
      delete this;
      break;

    default:
      NOTREACHED();
  }
}

void AlternateNavURLFetcher::OnURLFetchComplete(const URLFetcher* source,
                                                const GURL& url,
                                                const URLRequestStatus& status,
                                                int response_code,
                                                const ResponseCookies& cookies,
                                                const std::string& data) {
  DCHECK(fetcher_.get() == source);
  if (status.is_success() &&
      // HTTP 2xx, 401, and 407 all indicate that the target address exists.
      (((response_code / 100) == 2) ||
       (response_code == 401) || (response_code == 407))) {
    state_ = SUCCEEDED;
  } else {
    state_ = FAILED;
  }
  ShowInfobarIfPossible();
}

std::wstring AlternateNavURLFetcher::GetMessageTextWithOffset(
    size_t* link_offset) const {
  const std::wstring label = l10n_util::GetStringF(
      IDS_ALTERNATE_NAV_URL_VIEW_LABEL, std::wstring(), link_offset);
  DCHECK(*link_offset != std::wstring::npos);
  return label;
}

std::wstring AlternateNavURLFetcher::GetLinkText() const {
  return UTF8ToWide(alternate_nav_url_.spec());
}

SkBitmap* AlternateNavURLFetcher::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_ALT_NAV_URL);
}

bool AlternateNavURLFetcher::LinkClicked(WindowOpenDisposition disposition) {
  infobar_contents_->OpenURL(
      alternate_nav_url_, GURL(), disposition,
      // Pretend the user typed this URL, so that navigating to
      // it will be the default action when it's typed again in
      // the future.
      PageTransition::TYPED);

  // We should always close, even if the navigation did not occur within this
  // TabContents.
  return true;
}

void AlternateNavURLFetcher::InfoBarClosed() {
  delete this;
}

void AlternateNavURLFetcher::ShowInfobarIfPossible() {
  if (!navigated_to_entry_ || state_ != SUCCEEDED) {
    if (state_ == FAILED)
      delete this;
    return;
  }

  infobar_contents_ = controller_->tab_contents();
  StoreActiveEntryUniqueID(infobar_contents_);
  // We will be deleted when the InfoBar is destroyed. (See InfoBarClosed).
  infobar_contents_->AddInfoBar(this);
}
<commit_msg>Blacklist particular TLD+1s for accidental search infobars, to avoid showing the user an infobar on all kinds of searches.<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 "chrome/browser/alternate_nav_url_fetcher.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/registry_controlled_domain.h"
#include "net/url_request/url_request.h"

AlternateNavURLFetcher::AlternateNavURLFetcher(
    const GURL& alternate_nav_url)
    : LinkInfoBarDelegate(NULL),
      alternate_nav_url_(alternate_nav_url),
      controller_(NULL),
      state_(NOT_STARTED),
      navigated_to_entry_(false),
      infobar_contents_(NULL) {
  registrar_.Add(this, NotificationType::NAV_ENTRY_PENDING,
                 NotificationService::AllSources());
}

void AlternateNavURLFetcher::Observe(NotificationType type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::NAV_ENTRY_PENDING:
      controller_ = Source<NavigationController>(source).ptr();
      DCHECK(controller_->pending_entry());

      // Unregister for this notification now that we're pending, and start
      // listening for the corresponding commit. We also need to listen for the
      // tab close command since that means the load will never commit!
      registrar_.Remove(this, NotificationType::NAV_ENTRY_PENDING,
                        NotificationService::AllSources());
      registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
                     Source<NavigationController>(controller_));
      registrar_.Add(this, NotificationType::TAB_CLOSED,
                     Source<NavigationController>(controller_));

      DCHECK_EQ(NOT_STARTED, state_);
      state_ = IN_PROGRESS;
      fetcher_.reset(new URLFetcher(GURL(alternate_nav_url_), URLFetcher::HEAD,
                                    this));
      fetcher_->set_request_context(
          controller_->profile()->GetRequestContext());
      fetcher_->Start();
      break;

    case NotificationType::NAV_ENTRY_COMMITTED:
      // The page was navigated, we can show the infobar now if necessary.
      registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
                        Source<NavigationController>(controller_));
      navigated_to_entry_ = true;
      ShowInfobarIfPossible();
      break;

    case NotificationType::TAB_CLOSED:
      // We have been closed. In order to prevent the URLFetcher from trying to
      // access the controller that will be invalid, we delete ourselves.
      // This deletes the URLFetcher and insures its callback won't be called.
      delete this;
      break;

    default:
      NOTREACHED();
  }
}

void AlternateNavURLFetcher::OnURLFetchComplete(const URLFetcher* source,
                                                const GURL& url,
                                                const URLRequestStatus& status,
                                                int response_code,
                                                const ResponseCookies& cookies,
                                                const std::string& data) {
  DCHECK(fetcher_.get() == source);
  if (status.is_success() &&
      // HTTP 2xx, 401, and 407 all indicate that the target address exists.
      (((response_code / 100) == 2) ||
       (response_code == 401) || (response_code == 407))) {
    state_ = SUCCEEDED;

    // The following TLD+1s are used as destinations by ISPs/DNS providers/etc.
    // who return provider-controlled pages to arbitrary user navigation
    // attempts.  Because this can result in infobars on large fractions of user
    // searches, we don't show automatic infobars for these.  Note that users
    // can still choose to explicitly navigate to or search for pages in these
    // domains, and can still get infobars for cases that wind up on other
    // domains (e.g. legit intranet sites), we're just trying to avoid
    // erroneously harassing the user with our own UI prompts.
    const char* kBlacklistedSites[] = {
        "comcast.com",
        "opendns.com",
        "verizon.net",
    };
    for (size_t i = 0; i < arraysize(kBlacklistedSites); ++i) {
      if (net::RegistryControlledDomainService::SameDomainOrHost(
          url, GURL(kBlacklistedSites[i]))) {
        state_ = FAILED;
        break;
      }
    }
  } else {
    state_ = FAILED;
  }

  ShowInfobarIfPossible();
}

std::wstring AlternateNavURLFetcher::GetMessageTextWithOffset(
    size_t* link_offset) const {
  const std::wstring label = l10n_util::GetStringF(
      IDS_ALTERNATE_NAV_URL_VIEW_LABEL, std::wstring(), link_offset);
  DCHECK(*link_offset != std::wstring::npos);
  return label;
}

std::wstring AlternateNavURLFetcher::GetLinkText() const {
  return UTF8ToWide(alternate_nav_url_.spec());
}

SkBitmap* AlternateNavURLFetcher::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_ALT_NAV_URL);
}

bool AlternateNavURLFetcher::LinkClicked(WindowOpenDisposition disposition) {
  infobar_contents_->OpenURL(
      alternate_nav_url_, GURL(), disposition,
      // Pretend the user typed this URL, so that navigating to
      // it will be the default action when it's typed again in
      // the future.
      PageTransition::TYPED);

  // We should always close, even if the navigation did not occur within this
  // TabContents.
  return true;
}

void AlternateNavURLFetcher::InfoBarClosed() {
  delete this;
}

void AlternateNavURLFetcher::ShowInfobarIfPossible() {
  if (!navigated_to_entry_ || state_ != SUCCEEDED) {
    if (state_ == FAILED)
      delete this;
    return;
  }

  infobar_contents_ = controller_->tab_contents();
  StoreActiveEntryUniqueID(infobar_contents_);
  // We will be deleted when the InfoBar is destroyed. (See InfoBarClosed).
  infobar_contents_->AddInfoBar(this);
}
<|endoftext|>


<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        uninitialize_tests.cpp
 * @brief       未初期化テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2012-2016, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

IUTEST(Test, Dummy)
{
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    (void)argc;
    (void)argv;
    if( IUTEST_RUN_ALL_TESTS() == 0 )
    {
#if !defined(IUTEST_USE_GTEST)
        return 1;
#else
        printf("googletest latest is behavior changed...\n");
#endif
    }
    printf("*** Successful ***\n");
    return 0;
}
<commit_msg>fix cpplint<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        uninitialize_tests.cpp
 * @brief       未初期化テスト
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2012-2018, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

IUTEST(Test, Dummy)
{
}

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    (void)argc;
    (void)argv;
    if( IUTEST_RUN_ALL_TESTS() == 0 )
    {
#if !defined(IUTEST_USE_GTEST)
        return 1;
#else
        printf("googletest latest is behavior changed...\n");
#endif
    }
    printf("*** Successful ***\n");
    return 0;
}
<|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/browser/ui/simple_message_box.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "grit/generated_resources.h"
#include "ui/aura/window.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/wm/public/dispatcher_client.h"

#if defined(OS_WIN)
#include "ui/base/win/message_box_win.h"
#include "ui/views/win/hwnd_util.h"
#endif

namespace chrome {

namespace {

class SimpleMessageBoxViews : public views::DialogDelegate {
 public:
  SimpleMessageBoxViews(const base::string16& title,
                        const base::string16& message,
                        MessageBoxType type,
                        const base::string16& yes_text,
                        const base::string16& no_text,
                        bool is_system_modal,
                        MessageBoxResult* result);
  virtual ~SimpleMessageBoxViews();

  // Overridden from views::DialogDelegate:
  virtual int GetDialogButtons() const OVERRIDE;
  virtual base::string16 GetDialogButtonLabel(
      ui::DialogButton button) const OVERRIDE;
  virtual bool Cancel() OVERRIDE;
  virtual bool Accept() OVERRIDE;

  // Overridden from views::WidgetDelegate:
  virtual base::string16 GetWindowTitle() const OVERRIDE;
  virtual void DeleteDelegate() OVERRIDE;
  virtual ui::ModalType GetModalType() const OVERRIDE;
  virtual views::View* GetContentsView() OVERRIDE;
  virtual views::Widget* GetWidget() OVERRIDE;
  virtual const views::Widget* GetWidget() const OVERRIDE;

 private:

  // This terminates the nested message-loop.
  void Done();

  const base::string16 window_title_;
  const MessageBoxType type_;
  base::string16 yes_text_;
  base::string16 no_text_;
  MessageBoxResult* result_;
  bool is_system_modal_;
  views::MessageBoxView* message_box_view_;

  DISALLOW_COPY_AND_ASSIGN(SimpleMessageBoxViews);
};

////////////////////////////////////////////////////////////////////////////////
// SimpleMessageBoxViews, public:

SimpleMessageBoxViews::SimpleMessageBoxViews(const base::string16& title,
                                             const base::string16& message,
                                             MessageBoxType type,
                                             const base::string16& yes_text,
                                             const base::string16& no_text,
                                             bool is_system_modal,
                                             MessageBoxResult* result)
    : window_title_(title),
      type_(type),
      yes_text_(yes_text),
      no_text_(no_text),
      result_(result),
      is_system_modal_(is_system_modal),
      message_box_view_(new views::MessageBoxView(
          views::MessageBoxView::InitParams(message))) {
  CHECK(result_);
  if (yes_text_.empty()) {
    if (type_ == MESSAGE_BOX_TYPE_QUESTION)
      yes_text_ =
          l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL);
    else if (type_ == MESSAGE_BOX_TYPE_OK_CANCEL)
      yes_text_ = l10n_util::GetStringUTF16(IDS_OK);
    else
      yes_text_ = l10n_util::GetStringUTF16(IDS_OK);
  }

  if (no_text_.empty()) {
    if (type_ == MESSAGE_BOX_TYPE_QUESTION)
      no_text_ =
          l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL);
    else if (type_ == MESSAGE_BOX_TYPE_OK_CANCEL)
      no_text_ = l10n_util::GetStringUTF16(IDS_CANCEL);
  }
}

SimpleMessageBoxViews::~SimpleMessageBoxViews() {
}

int SimpleMessageBoxViews::GetDialogButtons() const {
  if (type_ == MESSAGE_BOX_TYPE_QUESTION ||
      type_ == MESSAGE_BOX_TYPE_OK_CANCEL) {
    return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
  }

  return ui::DIALOG_BUTTON_OK;
}

base::string16 SimpleMessageBoxViews::GetDialogButtonLabel(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_CANCEL)
    return no_text_;
  return yes_text_;
}

bool SimpleMessageBoxViews::Cancel() {
  *result_ = MESSAGE_BOX_RESULT_NO;
  Done();
  return true;
}

bool SimpleMessageBoxViews::Accept() {
  *result_ = MESSAGE_BOX_RESULT_YES;
  Done();
  return true;
}

base::string16 SimpleMessageBoxViews::GetWindowTitle() const {
  return window_title_;
}

void SimpleMessageBoxViews::DeleteDelegate() {
  delete this;
}

ui::ModalType SimpleMessageBoxViews::GetModalType() const {
  return is_system_modal_ ? ui::MODAL_TYPE_SYSTEM : ui::MODAL_TYPE_WINDOW;
}

views::View* SimpleMessageBoxViews::GetContentsView() {
  return message_box_view_;
}

views::Widget* SimpleMessageBoxViews::GetWidget() {
  return message_box_view_->GetWidget();
}

const views::Widget* SimpleMessageBoxViews::GetWidget() const {
  return message_box_view_->GetWidget();
}

////////////////////////////////////////////////////////////////////////////////
// SimpleMessageBoxViews, private:

void SimpleMessageBoxViews::Done() {
  aura::Window* window = GetWidget()->GetNativeView();
  aura::client::DispatcherClient* client =
      aura::client::GetDispatcherClient(window->GetRootWindow());
  client->QuitNestedMessageLoop();
}

#if defined(OS_WIN)
UINT GetMessageBoxFlagsFromType(MessageBoxType type) {
  UINT flags = MB_SETFOREGROUND;
  switch (type) {
    case MESSAGE_BOX_TYPE_INFORMATION:
      return flags | MB_OK | MB_ICONINFORMATION;
    case MESSAGE_BOX_TYPE_WARNING:
      return flags | MB_OK | MB_ICONWARNING;
    case MESSAGE_BOX_TYPE_QUESTION:
      return flags | MB_YESNO | MB_ICONQUESTION;
    case MESSAGE_BOX_TYPE_OK_CANCEL:
      return flags | MB_OKCANCEL | MB_ICONWARNING;
  }
  NOTREACHED();
  return flags | MB_OK | MB_ICONWARNING;
}
#endif

MessageBoxResult ShowMessageBoxImpl(gfx::NativeWindow parent,
                                    const base::string16& title,
                                    const base::string16& message,
                                    MessageBoxType type,
                                    const base::string16& yes_text,
                                    const base::string16& no_text) {
  // Views dialogs cannot be shown outside the UI thread message loop.
  // Fallback to logging with a default response or a Windows MessageBox.
  if (!base::MessageLoopForUI::IsCurrent() ||
      !base::MessageLoopForUI::current()->is_running()) {
#if defined(OS_WIN)
    int result = ui::MessageBox(views::HWNDForNativeWindow(parent), message,
                                title, GetMessageBoxFlagsFromType(type));
    return (result == IDYES || result == IDOK) ?
        MESSAGE_BOX_RESULT_YES : MESSAGE_BOX_RESULT_NO;
#else
    LOG(ERROR) << "Unable to show a dialog outside the UI thread message loop: "
               << title << " - " << message;
    return MESSAGE_BOX_RESULT_NO;
#endif
  }

  MessageBoxResult result = MESSAGE_BOX_RESULT_NO;
  SimpleMessageBoxViews* dialog = new SimpleMessageBoxViews(
      title,
      message,
      type,
      yes_text,
      no_text,
      parent == NULL,  // is_system_modal
      &result);
  CreateBrowserModalDialogViews(dialog, parent)->Show();

  // Use the widget's window itself so that the message loop exists when the
  // dialog is closed by some other means than |Cancel| or |Accept|.
  aura::Window* anchor = dialog->GetWidget()->GetNativeWindow();
  aura::client::DispatcherClient* client =
      aura::client::GetDispatcherClient(anchor->GetRootWindow());
  client->RunWithDispatcher(NULL);
  // NOTE: |dialog| will have been deleted by the time control returns here.

  return result;
}

}  // namespace

MessageBoxResult ShowMessageBox(gfx::NativeWindow parent,
                                const base::string16& title,
                                const base::string16& message,
                                MessageBoxType type) {
  return ShowMessageBoxImpl(
      parent, title, message, type, base::string16(), base::string16());
}

MessageBoxResult ShowMessageBoxWithButtonText(gfx::NativeWindow parent,
                                              const base::string16& title,
                                              const base::string16& message,
                                              const base::string16& yes_text,
                                              const base::string16& no_text) {
  return ShowMessageBoxImpl(
      parent, title, message, MESSAGE_BOX_TYPE_QUESTION, yes_text, no_text);
}

}  // namespace chrome
<commit_msg>SimpleMessageBoxViews: UI message loop does not need to be running on Linux.<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/browser/ui/simple_message_box.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "grit/generated_resources.h"
#include "ui/aura/window.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/wm/public/dispatcher_client.h"

#if defined(OS_WIN)
#include "ui/base/win/message_box_win.h"
#include "ui/views/win/hwnd_util.h"
#endif

namespace chrome {

namespace {

class SimpleMessageBoxViews : public views::DialogDelegate {
 public:
  SimpleMessageBoxViews(const base::string16& title,
                        const base::string16& message,
                        MessageBoxType type,
                        const base::string16& yes_text,
                        const base::string16& no_text,
                        bool is_system_modal,
                        MessageBoxResult* result);
  virtual ~SimpleMessageBoxViews();

  // Overridden from views::DialogDelegate:
  virtual int GetDialogButtons() const OVERRIDE;
  virtual base::string16 GetDialogButtonLabel(
      ui::DialogButton button) const OVERRIDE;
  virtual bool Cancel() OVERRIDE;
  virtual bool Accept() OVERRIDE;

  // Overridden from views::WidgetDelegate:
  virtual base::string16 GetWindowTitle() const OVERRIDE;
  virtual void DeleteDelegate() OVERRIDE;
  virtual ui::ModalType GetModalType() const OVERRIDE;
  virtual views::View* GetContentsView() OVERRIDE;
  virtual views::Widget* GetWidget() OVERRIDE;
  virtual const views::Widget* GetWidget() const OVERRIDE;

 private:

  // This terminates the nested message-loop.
  void Done();

  const base::string16 window_title_;
  const MessageBoxType type_;
  base::string16 yes_text_;
  base::string16 no_text_;
  MessageBoxResult* result_;
  bool is_system_modal_;
  views::MessageBoxView* message_box_view_;

  DISALLOW_COPY_AND_ASSIGN(SimpleMessageBoxViews);
};

////////////////////////////////////////////////////////////////////////////////
// SimpleMessageBoxViews, public:

SimpleMessageBoxViews::SimpleMessageBoxViews(const base::string16& title,
                                             const base::string16& message,
                                             MessageBoxType type,
                                             const base::string16& yes_text,
                                             const base::string16& no_text,
                                             bool is_system_modal,
                                             MessageBoxResult* result)
    : window_title_(title),
      type_(type),
      yes_text_(yes_text),
      no_text_(no_text),
      result_(result),
      is_system_modal_(is_system_modal),
      message_box_view_(new views::MessageBoxView(
          views::MessageBoxView::InitParams(message))) {
  CHECK(result_);
  if (yes_text_.empty()) {
    if (type_ == MESSAGE_BOX_TYPE_QUESTION)
      yes_text_ =
          l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL);
    else if (type_ == MESSAGE_BOX_TYPE_OK_CANCEL)
      yes_text_ = l10n_util::GetStringUTF16(IDS_OK);
    else
      yes_text_ = l10n_util::GetStringUTF16(IDS_OK);
  }

  if (no_text_.empty()) {
    if (type_ == MESSAGE_BOX_TYPE_QUESTION)
      no_text_ =
          l10n_util::GetStringUTF16(IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL);
    else if (type_ == MESSAGE_BOX_TYPE_OK_CANCEL)
      no_text_ = l10n_util::GetStringUTF16(IDS_CANCEL);
  }
}

SimpleMessageBoxViews::~SimpleMessageBoxViews() {
}

int SimpleMessageBoxViews::GetDialogButtons() const {
  if (type_ == MESSAGE_BOX_TYPE_QUESTION ||
      type_ == MESSAGE_BOX_TYPE_OK_CANCEL) {
    return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
  }

  return ui::DIALOG_BUTTON_OK;
}

base::string16 SimpleMessageBoxViews::GetDialogButtonLabel(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_CANCEL)
    return no_text_;
  return yes_text_;
}

bool SimpleMessageBoxViews::Cancel() {
  *result_ = MESSAGE_BOX_RESULT_NO;
  Done();
  return true;
}

bool SimpleMessageBoxViews::Accept() {
  *result_ = MESSAGE_BOX_RESULT_YES;
  Done();
  return true;
}

base::string16 SimpleMessageBoxViews::GetWindowTitle() const {
  return window_title_;
}

void SimpleMessageBoxViews::DeleteDelegate() {
  delete this;
}

ui::ModalType SimpleMessageBoxViews::GetModalType() const {
  return is_system_modal_ ? ui::MODAL_TYPE_SYSTEM : ui::MODAL_TYPE_WINDOW;
}

views::View* SimpleMessageBoxViews::GetContentsView() {
  return message_box_view_;
}

views::Widget* SimpleMessageBoxViews::GetWidget() {
  return message_box_view_->GetWidget();
}

const views::Widget* SimpleMessageBoxViews::GetWidget() const {
  return message_box_view_->GetWidget();
}

////////////////////////////////////////////////////////////////////////////////
// SimpleMessageBoxViews, private:

void SimpleMessageBoxViews::Done() {
  aura::Window* window = GetWidget()->GetNativeView();
  aura::client::DispatcherClient* client =
      aura::client::GetDispatcherClient(window->GetRootWindow());
  client->QuitNestedMessageLoop();
}

#if defined(OS_WIN)
UINT GetMessageBoxFlagsFromType(MessageBoxType type) {
  UINT flags = MB_SETFOREGROUND;
  switch (type) {
    case MESSAGE_BOX_TYPE_INFORMATION:
      return flags | MB_OK | MB_ICONINFORMATION;
    case MESSAGE_BOX_TYPE_WARNING:
      return flags | MB_OK | MB_ICONWARNING;
    case MESSAGE_BOX_TYPE_QUESTION:
      return flags | MB_YESNO | MB_ICONQUESTION;
    case MESSAGE_BOX_TYPE_OK_CANCEL:
      return flags | MB_OKCANCEL | MB_ICONWARNING;
  }
  NOTREACHED();
  return flags | MB_OK | MB_ICONWARNING;
}
#endif

MessageBoxResult ShowMessageBoxImpl(gfx::NativeWindow parent,
                                    const base::string16& title,
                                    const base::string16& message,
                                    MessageBoxType type,
                                    const base::string16& yes_text,
                                    const base::string16& no_text) {
  // Views dialogs cannot be shown outside the UI thread message loop or if the
  // ResourceBundle is not initialized yet.
  // Fallback to logging with a default response or a Windows MessageBox.
#if defined(OS_WIN)
  if (!base::MessageLoopForUI::IsCurrent() ||
      !base::MessageLoopForUI::current()->is_running() ||
      !ResourceBundle::HasSharedInstance()) {
    int result = ui::MessageBox(views::HWNDForNativeWindow(parent), message,
                                title, GetMessageBoxFlagsFromType(type));
    return (result == IDYES || result == IDOK) ?
        MESSAGE_BOX_RESULT_YES : MESSAGE_BOX_RESULT_NO;
  }
#else
  if (!base::MessageLoopForUI::IsCurrent() ||
      !ResourceBundle::HasSharedInstance()) {
    LOG(ERROR) << "Unable to show a dialog outside the UI thread message loop: "
               << title << " - " << message;
    return MESSAGE_BOX_RESULT_NO;
  }
#endif

  MessageBoxResult result = MESSAGE_BOX_RESULT_NO;
  SimpleMessageBoxViews* dialog = new SimpleMessageBoxViews(
      title,
      message,
      type,
      yes_text,
      no_text,
      parent == NULL,  // is_system_modal
      &result);
  CreateBrowserModalDialogViews(dialog, parent)->Show();

  // Use the widget's window itself so that the message loop exists when the
  // dialog is closed by some other means than |Cancel| or |Accept|.
  aura::Window* anchor = dialog->GetWidget()->GetNativeWindow();
  aura::client::DispatcherClient* client =
      aura::client::GetDispatcherClient(anchor->GetRootWindow());
  client->RunWithDispatcher(NULL);
  // NOTE: |dialog| will have been deleted by the time control returns here.

  return result;
}

}  // namespace

MessageBoxResult ShowMessageBox(gfx::NativeWindow parent,
                                const base::string16& title,
                                const base::string16& message,
                                MessageBoxType type) {
  return ShowMessageBoxImpl(
      parent, title, message, type, base::string16(), base::string16());
}

MessageBoxResult ShowMessageBoxWithButtonText(gfx::NativeWindow parent,
                                              const base::string16& title,
                                              const base::string16& message,
                                              const base::string16& yes_text,
                                              const base::string16& no_text) {
  return ShowMessageBoxImpl(
      parent, title, message, MESSAGE_BOX_TYPE_QUESTION, yes_text, no_text);
}

}  // namespace chrome
<|endoftext|>


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

Program:   Visualization Toolkit
Module:    vtkCarbonRenderWindowInteractor.cxx
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "vtkCarbonRenderWindow.h"
#include "vtkCarbonRenderWindowInteractor.h"
#include "vtkInteractorStyle.h"
#include "vtkActor.h"
#include <OpenGL/gl.h>
#include "vtkObjectFactory.h"

#import <Carbon/Carbon.h>

vtkCxxRevisionMacro(vtkCarbonRenderWindowInteractor, "1.2");
vtkStandardNewMacro(vtkCarbonRenderWindowInteractor);

void (*vtkCarbonRenderWindowInteractor::ClassExitMethod)(void *)
  = (void (*)(void *))NULL;
void *vtkCarbonRenderWindowInteractor::ClassExitMethodArg = (void *)NULL;
void (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)(void *)
  = (void (*)(void *))NULL;

//--------------------------------------------------------------------------
// callback routine to handle all window-related events
// The WindowPtr of the associated window is passed in userData
static pascal OSStatus myWinEvtHndlr(EventHandlerCallRef nextHandler,
                                     EventRef event, void* userData)
{
  WindowRef                        window;
  Rect                             bounds;
  OSStatus                         result = eventNotHandledErr;
  Point                            mouseLoc;
  vtkCarbonRenderWindow            *ren;
  vtkCarbonRenderWindowInteractor  *me;

  ren = (vtkCarbonRenderWindow *)GetWRefCon((WindowPtr)userData);

  if (NULL == ren)
    {
    return 0;
    }

  me = (vtkCarbonRenderWindowInteractor *)ren->GetInteractor();
  if (NULL == me)
    {
    return 0;
    }

  UInt32 modifierKeys;
  GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,
                    sizeof(modifierKeys), NULL, &modifierKeys);
  int controlDown = (modifierKeys & controlKey);
  int shiftDown = (modifierKeys & shiftKey);

  switch (GetEventClass(event))
    {
    case kEventClassWindow:
      {
      switch (GetEventKind(event))
        {
        case kEventWindowClickContentRgn:
          {
          GetEventParameter(event, kEventParamMouseLocation, typeQDPoint,
                            NULL, sizeof(Point), NULL, &mouseLoc);
          SetPortWindowPort(FrontWindow());
          GlobalToLocal(&mouseLoc);

          UInt16 buttonNumber;
          GetEventParameter(event,kEventParamMouseButton,typeMouseButton,NULL,
                            sizeof(buttonNumber),NULL,&buttonNumber);

          me->SetEventInformationFlipY(mouseLoc.h,mouseLoc.v,
                                       controlDown,shiftDown);
          switch (buttonNumber)
            {
            case 1:
              {
              me->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);
              break;
              }
            case 2:
              {
              me->InvokeEvent(vtkCommand::RightButtonPressEvent,NULL);
              break;
              }
            case 3:
              {
              me->InvokeEvent(vtkCommand::MiddleButtonPressEvent,NULL);
              break;
              }
            }
          result = noErr;
          break;
          }
        case kEventWindowDrawContent:
          {
          ren->Render();
          result = noErr;
          break;
          }
        case kEventWindowBoundsChanging:
          {
          InvalWindowRect(window, GetWindowPortBounds(window, &bounds));
          GetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle,
                            NULL, sizeof(bounds), NULL, &bounds);
          me->UpdateSize(bounds.right-bounds.left, bounds.bottom-bounds.top);
          me->InvokeEvent(vtkCommand::ConfigureEvent,NULL);
          ren->MakeCurrent();
          aglUpdateContext (ren->GetContextId());

          glViewport (0, 0,
                      bounds.right - bounds.left,
                      bounds.bottom - bounds.top);
          ren->Render();
          result = noErr;
          break;
          }
        case kEventWindowActivated:
          {
          InvalWindowRect(window, GetWindowPortBounds(window, &bounds));
          ren->MakeCurrent();
          aglUpdateContext (ren->GetContextId());
          result = noErr;
          break;
          }
        case kEventWindowClose:
          {
          result = CallNextEventHandler(nextHandler, event);
          break;
          }
        }
      break;
      }

    case kEventClassKeyboard:
      {
      SInt8 charCode;
      GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar,NULL,
                        sizeof(charCode),NULL,&charCode);
        switch (GetEventKind(event))
          {
          case kEventRawKeyDown:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
            me->InvokeEvent(vtkCommand::CharEvent, NULL);
            break;
            }
          case kEventRawKeyRepeat:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
            me->InvokeEvent(vtkCommand::CharEvent, NULL);
            break;
            }
          case kEventRawKeyUp:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);
            break;
            }
          }
        break;
      }

    case kEventClassMouse:
      {
      GetEventParameter(event, kEventParamMouseLocation, typeQDPoint,
                        NULL, sizeof(Point), NULL, &mouseLoc);
      SetPortWindowPort(FrontWindow());
      GlobalToLocal(&mouseLoc);
      GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,
                        sizeof(modifierKeys), NULL, &modifierKeys);
      UInt16 buttonNumber;
      GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL,
                        sizeof(buttonNumber), NULL, &buttonNumber);
      me->SetEventInformationFlipY(mouseLoc.h, mouseLoc.v,
                                   (modifierKeys & controlKey),
                                   (modifierKeys & shiftKey));
      switch (GetEventKind(event))
        {
        case kEventMouseUp:
          {
          switch (buttonNumber)
            {
            case 1:
              {
              me->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);
              break;
              }
            case 2:
              {
              me->InvokeEvent(vtkCommand::RightButtonReleaseEvent,NULL);
              break;
              }
            case 3:
              {
              me->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent,NULL);
              break;
              }
            }
          result = noErr;
          break;
          }
        case kEventMouseMoved:
          {
          me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
          result = noErr;
          break;
          }
        case kEventMouseDragged:
          {
          me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
          result = noErr;
          break;
          }
        default:
          {
          result = noErr;
          }
        }
      }
    }
  return result;
}

//--------------------------------------------------------------------------
// Construct object so that light follows camera motion.
vtkCarbonRenderWindowInteractor::vtkCarbonRenderWindowInteractor()
{
  this->WindowId           = NULL;
  this->TimerId            = 0;
  this->InstallMessageProc = 1;
  this->OldProc            = NULL;
}

//--------------------------------------------------------------------------
vtkCarbonRenderWindowInteractor::~vtkCarbonRenderWindowInteractor()
{
  this->Enabled = 0;
}

//--------------------------------------------------------------------------
void  vtkCarbonRenderWindowInteractor::Start()
{
  // Let the compositing handle the event loop if it wants to.
  if (this->HasObserver(vtkCommand::StartEvent))
    {
    this->InvokeEvent(vtkCommand::StartEvent,NULL);
    return;
    }

  // No need to do anything if this is a 'mapped' interactor
  if (!this->Enabled || !this->InstallMessageProc)
    {
    return;
    }
  RunApplicationEventLoop();
}

//--------------------------------------------------------------------------
// Fill in some local variables (most of this routine could probably go)
void vtkCarbonRenderWindowInteractor::Initialize()
{
  vtkCarbonRenderWindow *ren;
  int *size;

  // make sure we have a RenderWindow and camera
  if ( ! this->RenderWindow)
    {
    vtkErrorMacro(<<"No renderer defined!");
    return;
    }
  if (this->Initialized)
    {
    return;
    }
  this->Initialized = 1;
  // get the info we need from the RenderingWindow
  ren = (vtkCarbonRenderWindow *)(this->RenderWindow);
  ren->Start();
  size    = ren->GetSize();
  ren->GetPosition();
  this->WindowId = ren->GetWindowId();
  this->Enable();
  this->Size[0] = size[0];
  this->Size[1] = size[1];
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::Enable()
{
  vtkCarbonRenderWindow *ren;
  vtkCarbonRenderWindow *tmp;
  if (this->Enabled)
    {
    return;
    }
  if (this->InstallMessageProc)
    {
    // add our callback
    ren = (vtkCarbonRenderWindow *)(this->RenderWindow);
    // set up the event handling
    // specify which events we want to hear about
    OSStatus   err = noErr;
    EventTypeSpec list[] = {{ kEventClassWindow, kEventWindowClose },
                            { kEventClassWindow, kEventWindowDrawContent },
                            { kEventClassWindow, kEventWindowBoundsChanging },
                            { kEventClassWindow, kEventWindowActivated },
                            { kEventClassWindow, kEventWindowClickContentRgn },
                            { kEventClassMouse, kEventMouseUp },
                            { kEventClassMouse, kEventMouseMoved },
                            { kEventClassMouse, kEventMouseDragged },
                            { kEventClassKeyboard, kEventRawKeyDown },
                            { kEventClassKeyboard, kEventRawKeyRepeat },
                            { kEventClassKeyboard, kEventRawKeyUp }};
    // if we haven't already made our window event handler UPP then do so now
    if(!this->OldProc)
      {
      this->OldProc = NewEventHandlerUPP(myWinEvtHndlr);
      if(!this->OldProc)
        err = memFullErr;
      }

    if(!err)
      {
      EventHandlerRef  ref;
      err = InstallWindowEventHandler(ren->GetWindowId(), this->OldProc,
                                      sizeof(list)/sizeof(EventTypeSpec),
                                      list, ren->GetWindowId(), &ref);
      }
    }
  this->Enabled = 1;
  this->Modified();
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::Disable()
{
  vtkCarbonRenderWindow *tmp;
  if (!this->Enabled)
    {
    return;
    }
  this->Enabled = 0;
  this->Modified();
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::TerminateApp(void)
{
  cout << "vtkCarbonRenderWindowInteractor::TerminateApp\n";
}

//--------------------------------------------------------------------------
pascal void TimerAction (EventLoopTimerRef theTimer, void* userData)
{
  if (NULL != userData)
    {
    ((vtkCarbonRenderWindowInteractor *)userData)->
      InvokeEvent(vtkCommand::TimerEvent,NULL);
    }
}

//--------------------------------------------------------------------------
int vtkCarbonRenderWindowInteractor::CreateTimer(int timertype)
{
  EventLoopRef       mainLoop = GetMainEventLoop();
  EventLoopTimerUPP  timerUPP = NewEventLoopTimerUPP(TimerAction);

  if (timertype == VTKI_TIMER_FIRST)
    {
      InstallEventLoopTimer (mainLoop,
                             10*kEventDurationMillisecond,
                             10*kEventDurationMillisecond,
                             timerUPP,
                             this,
                             &this->TimerId);
    }
  return 1;
}

//--------------------------------------------------------------------------
int vtkCarbonRenderWindowInteractor::DestroyTimer(void)
{
  RemoveEventLoopTimer(this->TimerId);
  return 1;
}

//--------------------------------------------------------------------------
// Specify the default function to be called when an interactor needs to exit.
// This callback is overridden by an instance ExitMethod that is defined.
void vtkCarbonRenderWindowInteractor::SetClassExitMethod(void (*f)(void *),
                                                         void *arg)
{
  if (f != vtkCarbonRenderWindowInteractor::ClassExitMethod
      || arg != vtkCarbonRenderWindowInteractor::ClassExitMethodArg)
    {
    // delete the current arg if there is a delete method
    if ((vtkCarbonRenderWindowInteractor::ClassExitMethodArg) &&
        (vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete))
      {
      (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)
        (vtkCarbonRenderWindowInteractor::ClassExitMethodArg);
      }
    vtkCarbonRenderWindowInteractor::ClassExitMethod = f;
    vtkCarbonRenderWindowInteractor::ClassExitMethodArg = arg;

    // no call to this->Modified() since this is a class member function
    }
}

//--------------------------------------------------------------------------
// Set the arg delete method.  This is used to free user memory.
void
vtkCarbonRenderWindowInteractor::SetClassExitMethodArgDelete(void (*f)(void *))
{
  if (f != vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)
    {
    vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete = f;

    // no call to this->Modified() since this is a class member function
    }
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkRenderWindowInteractor::PrintSelf(os,indent);
  os << indent << "InstallMessageProc: " << this->InstallMessageProc << endl;
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::ExitCallback()
{
  if (this->ClassExitMethod)
    {
    (*this->ClassExitMethod)(this->ClassExitMethodArg);
    }
  else if (this->ClassExitMethod)
    {
    (*this->ClassExitMethod)(this->ClassExitMethodArg);
    }
  else
    {
    this->TerminateApp();
    }
}
<commit_msg>FIX: vtkCommand.h was no longer being included<commit_after>/*=========================================================================

Program:   Visualization Toolkit
Module:    vtkCarbonRenderWindowInteractor.cxx
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "vtkCarbonRenderWindow.h"
#include "vtkCarbonRenderWindowInteractor.h"
#include "vtkInteractorStyle.h"
#include "vtkActor.h"
#include <OpenGL/gl.h>
#include "vtkObjectFactory.h"
#include "vtkCommand.h"

#import <Carbon/Carbon.h>

vtkCxxRevisionMacro(vtkCarbonRenderWindowInteractor, "1.3");
vtkStandardNewMacro(vtkCarbonRenderWindowInteractor);

void (*vtkCarbonRenderWindowInteractor::ClassExitMethod)(void *)
  = (void (*)(void *))NULL;
void *vtkCarbonRenderWindowInteractor::ClassExitMethodArg = (void *)NULL;
void (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)(void *)
  = (void (*)(void *))NULL;

//--------------------------------------------------------------------------
// callback routine to handle all window-related events
// The WindowPtr of the associated window is passed in userData
static pascal OSStatus myWinEvtHndlr(EventHandlerCallRef nextHandler,
                                     EventRef event, void* userData)
{
  WindowRef                        window;
  Rect                             bounds;
  OSStatus                         result = eventNotHandledErr;
  Point                            mouseLoc;
  vtkCarbonRenderWindow            *ren;
  vtkCarbonRenderWindowInteractor  *me;

  ren = (vtkCarbonRenderWindow *)GetWRefCon((WindowPtr)userData);

  if (NULL == ren)
    {
    return 0;
    }

  me = (vtkCarbonRenderWindowInteractor *)ren->GetInteractor();
  if (NULL == me)
    {
    return 0;
    }

  UInt32 modifierKeys;
  GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,
                    sizeof(modifierKeys), NULL, &modifierKeys);
  int controlDown = (modifierKeys & controlKey);
  int shiftDown = (modifierKeys & shiftKey);

  switch (GetEventClass(event))
    {
    case kEventClassWindow:
      {
      switch (GetEventKind(event))
        {
        case kEventWindowClickContentRgn:
          {
          GetEventParameter(event, kEventParamMouseLocation, typeQDPoint,
                            NULL, sizeof(Point), NULL, &mouseLoc);
          SetPortWindowPort(FrontWindow());
          GlobalToLocal(&mouseLoc);

          UInt16 buttonNumber;
          GetEventParameter(event,kEventParamMouseButton,typeMouseButton,NULL,
                            sizeof(buttonNumber),NULL,&buttonNumber);

          me->SetEventInformationFlipY(mouseLoc.h,mouseLoc.v,
                                       controlDown,shiftDown);
          switch (buttonNumber)
            {
            case 1:
              {
              me->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL);
              break;
              }
            case 2:
              {
              me->InvokeEvent(vtkCommand::RightButtonPressEvent,NULL);
              break;
              }
            case 3:
              {
              me->InvokeEvent(vtkCommand::MiddleButtonPressEvent,NULL);
              break;
              }
            }
          result = noErr;
          break;
          }
        case kEventWindowDrawContent:
          {
          ren->Render();
          result = noErr;
          break;
          }
        case kEventWindowBoundsChanging:
          {
          InvalWindowRect(window, GetWindowPortBounds(window, &bounds));
          GetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle,
                            NULL, sizeof(bounds), NULL, &bounds);
          me->UpdateSize(bounds.right-bounds.left, bounds.bottom-bounds.top);
          me->InvokeEvent(vtkCommand::ConfigureEvent,NULL);
          ren->MakeCurrent();
          aglUpdateContext (ren->GetContextId());

          glViewport (0, 0,
                      bounds.right - bounds.left,
                      bounds.bottom - bounds.top);
          ren->Render();
          result = noErr;
          break;
          }
        case kEventWindowActivated:
          {
          InvalWindowRect(window, GetWindowPortBounds(window, &bounds));
          ren->MakeCurrent();
          aglUpdateContext (ren->GetContextId());
          result = noErr;
          break;
          }
        case kEventWindowClose:
          {
          result = CallNextEventHandler(nextHandler, event);
          break;
          }
        }
      break;
      }

    case kEventClassKeyboard:
      {
      SInt8 charCode;
      GetEventParameter(event, kEventParamKeyMacCharCodes, typeChar,NULL,
                        sizeof(charCode),NULL,&charCode);
        switch (GetEventKind(event))
          {
          case kEventRawKeyDown:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
            me->InvokeEvent(vtkCommand::CharEvent, NULL);
            break;
            }
          case kEventRawKeyRepeat:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
            me->InvokeEvent(vtkCommand::CharEvent, NULL);
            break;
            }
          case kEventRawKeyUp:
            {
            me->SetKeyEventInformation(controlDown, shiftDown,
                                       (int)charCode,1,&((char)charCode));
            me->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);
            break;
            }
          }
        break;
      }

    case kEventClassMouse:
      {
      GetEventParameter(event, kEventParamMouseLocation, typeQDPoint,
                        NULL, sizeof(Point), NULL, &mouseLoc);
      SetPortWindowPort(FrontWindow());
      GlobalToLocal(&mouseLoc);
      GetEventParameter(event, kEventParamKeyModifiers,typeUInt32, NULL,
                        sizeof(modifierKeys), NULL, &modifierKeys);
      UInt16 buttonNumber;
      GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL,
                        sizeof(buttonNumber), NULL, &buttonNumber);
      me->SetEventInformationFlipY(mouseLoc.h, mouseLoc.v,
                                   (modifierKeys & controlKey),
                                   (modifierKeys & shiftKey));
      switch (GetEventKind(event))
        {
        case kEventMouseUp:
          {
          switch (buttonNumber)
            {
            case 1:
              {
              me->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL);
              break;
              }
            case 2:
              {
              me->InvokeEvent(vtkCommand::RightButtonReleaseEvent,NULL);
              break;
              }
            case 3:
              {
              me->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent,NULL);
              break;
              }
            }
          result = noErr;
          break;
          }
        case kEventMouseMoved:
          {
          me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
          result = noErr;
          break;
          }
        case kEventMouseDragged:
          {
          me->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
          result = noErr;
          break;
          }
        default:
          {
          result = noErr;
          }
        }
      }
    }
  return result;
}

//--------------------------------------------------------------------------
// Construct object so that light follows camera motion.
vtkCarbonRenderWindowInteractor::vtkCarbonRenderWindowInteractor()
{
  this->WindowId           = NULL;
  this->TimerId            = 0;
  this->InstallMessageProc = 1;
  this->OldProc            = NULL;
}

//--------------------------------------------------------------------------
vtkCarbonRenderWindowInteractor::~vtkCarbonRenderWindowInteractor()
{
  this->Enabled = 0;
}

//--------------------------------------------------------------------------
void  vtkCarbonRenderWindowInteractor::Start()
{
  // Let the compositing handle the event loop if it wants to.
  if (this->HasObserver(vtkCommand::StartEvent))
    {
    this->InvokeEvent(vtkCommand::StartEvent,NULL);
    return;
    }

  // No need to do anything if this is a 'mapped' interactor
  if (!this->Enabled || !this->InstallMessageProc)
    {
    return;
    }
  RunApplicationEventLoop();
}

//--------------------------------------------------------------------------
// Fill in some local variables (most of this routine could probably go)
void vtkCarbonRenderWindowInteractor::Initialize()
{
  vtkCarbonRenderWindow *ren;
  int *size;

  // make sure we have a RenderWindow and camera
  if ( ! this->RenderWindow)
    {
    vtkErrorMacro(<<"No renderer defined!");
    return;
    }
  if (this->Initialized)
    {
    return;
    }
  this->Initialized = 1;
  // get the info we need from the RenderingWindow
  ren = (vtkCarbonRenderWindow *)(this->RenderWindow);
  ren->Start();
  size    = ren->GetSize();
  ren->GetPosition();
  this->WindowId = ren->GetWindowId();
  this->Enable();
  this->Size[0] = size[0];
  this->Size[1] = size[1];
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::Enable()
{
  vtkCarbonRenderWindow *ren;
  vtkCarbonRenderWindow *tmp;
  if (this->Enabled)
    {
    return;
    }
  if (this->InstallMessageProc)
    {
    // add our callback
    ren = (vtkCarbonRenderWindow *)(this->RenderWindow);
    // set up the event handling
    // specify which events we want to hear about
    OSStatus   err = noErr;
    EventTypeSpec list[] = {{ kEventClassWindow, kEventWindowClose },
                            { kEventClassWindow, kEventWindowDrawContent },
                            { kEventClassWindow, kEventWindowBoundsChanging },
                            { kEventClassWindow, kEventWindowActivated },
                            { kEventClassWindow, kEventWindowClickContentRgn },
                            { kEventClassMouse, kEventMouseUp },
                            { kEventClassMouse, kEventMouseMoved },
                            { kEventClassMouse, kEventMouseDragged },
                            { kEventClassKeyboard, kEventRawKeyDown },
                            { kEventClassKeyboard, kEventRawKeyRepeat },
                            { kEventClassKeyboard, kEventRawKeyUp }};
    // if we haven't already made our window event handler UPP then do so now
    if(!this->OldProc)
      {
      this->OldProc = NewEventHandlerUPP(myWinEvtHndlr);
      if(!this->OldProc)
        err = memFullErr;
      }

    if(!err)
      {
      EventHandlerRef  ref;
      err = InstallWindowEventHandler(ren->GetWindowId(), this->OldProc,
                                      sizeof(list)/sizeof(EventTypeSpec),
                                      list, ren->GetWindowId(), &ref);
      }
    }
  this->Enabled = 1;
  this->Modified();
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::Disable()
{
  vtkCarbonRenderWindow *tmp;
  if (!this->Enabled)
    {
    return;
    }
  this->Enabled = 0;
  this->Modified();
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::TerminateApp(void)
{
  cout << "vtkCarbonRenderWindowInteractor::TerminateApp\n";
}

//--------------------------------------------------------------------------
pascal void TimerAction (EventLoopTimerRef theTimer, void* userData)
{
  if (NULL != userData)
    {
    ((vtkCarbonRenderWindowInteractor *)userData)->
      InvokeEvent(vtkCommand::TimerEvent,NULL);
    }
}

//--------------------------------------------------------------------------
int vtkCarbonRenderWindowInteractor::CreateTimer(int timertype)
{
  EventLoopRef       mainLoop = GetMainEventLoop();
  EventLoopTimerUPP  timerUPP = NewEventLoopTimerUPP(TimerAction);

  if (timertype == VTKI_TIMER_FIRST)
    {
      InstallEventLoopTimer (mainLoop,
                             10*kEventDurationMillisecond,
                             10*kEventDurationMillisecond,
                             timerUPP,
                             this,
                             &this->TimerId);
    }
  return 1;
}

//--------------------------------------------------------------------------
int vtkCarbonRenderWindowInteractor::DestroyTimer(void)
{
  RemoveEventLoopTimer(this->TimerId);
  return 1;
}

//--------------------------------------------------------------------------
// Specify the default function to be called when an interactor needs to exit.
// This callback is overridden by an instance ExitMethod that is defined.
void vtkCarbonRenderWindowInteractor::SetClassExitMethod(void (*f)(void *),
                                                         void *arg)
{
  if (f != vtkCarbonRenderWindowInteractor::ClassExitMethod
      || arg != vtkCarbonRenderWindowInteractor::ClassExitMethodArg)
    {
    // delete the current arg if there is a delete method
    if ((vtkCarbonRenderWindowInteractor::ClassExitMethodArg) &&
        (vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete))
      {
      (*vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)
        (vtkCarbonRenderWindowInteractor::ClassExitMethodArg);
      }
    vtkCarbonRenderWindowInteractor::ClassExitMethod = f;
    vtkCarbonRenderWindowInteractor::ClassExitMethodArg = arg;

    // no call to this->Modified() since this is a class member function
    }
}

//--------------------------------------------------------------------------
// Set the arg delete method.  This is used to free user memory.
void
vtkCarbonRenderWindowInteractor::SetClassExitMethodArgDelete(void (*f)(void *))
{
  if (f != vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete)
    {
    vtkCarbonRenderWindowInteractor::ClassExitMethodArgDelete = f;

    // no call to this->Modified() since this is a class member function
    }
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkRenderWindowInteractor::PrintSelf(os,indent);
  os << indent << "InstallMessageProc: " << this->InstallMessageProc << endl;
}

//--------------------------------------------------------------------------
void vtkCarbonRenderWindowInteractor::ExitCallback()
{
  if (this->ClassExitMethod)
    {
    (*this->ClassExitMethod)(this->ClassExitMethodArg);
    }
  else if (this->ClassExitMethod)
    {
    (*this->ClassExitMethod)(this->ClassExitMethodArg);
    }
  else
    {
    this->TerminateApp();
    }
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_CONTAINER_HH
#define DUNE_STUFF_LA_CONTAINER_HH

#include <dune/common/typetraits.hh>

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

namespace Dune {
namespace Stuff {
namespace LA {

template< class ContainerImp >
class Container
{
public:
  static ContainerImp create(const size_t /*size*/)
  {
    static_assert(Dune::AlwaysFalse< ContainerImp >::value, "Please specialize this class for this ContainerImp!");
  }
};

#if HAVE_EIGEN
template< class S >
class Container< EigenDenseVector< S > >
{
public:
  static EigenDenseVector< S > create(const size_t size)
  {
    return EigenDenseVector< S >(size, S(1));
  }
};

template< class S >
class Container< EigenMappedDenseVector< S > >
{
public:
  static EigenMappedDenseVector< S > create(const size_t size)
  {
    return EigenMappedDenseVector< S >(size, S(1));
  }
};

template< class S >
class Container< EigenRowMajorSparseMatrix< S > >
{
public:
  static EigenRowMajorSparseMatrix< S > create(const size_t size)
  {
    Dune::Stuff::LA::SparsityPatternDefault pattern(size);
    for (size_t ii = 0; ii < size; ++ii)
      pattern.inner(ii).insert(ii);
    Dune::Stuff::LA::EigenRowMajorSparseMatrix< S > matrix(size, size, pattern);
    for (size_t ii = 0; ii < size; ++ii)
      matrix.unit_row(ii);
    return matrix;
  }
};

template< class S >
class Container< EigenDenseMatrix< S > >
{
public:
  static EigenDenseMatrix< S > create(const size_t size)
  {
    Dune::Stuff::LA::EigenDenseMatrix< S > matrix(size, size);
    for (size_t ii = 0; ii < size; ++ii)
      matrix.unit_row(ii);
    return matrix;
  }
};
#endif // HAVE_EIGEN

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

#endif // DUNE_STUFF_LA_CONTAINER_HH
<commit_msg>[la.container] added Container::create for DuneDynamic<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_CONTAINER_HH
#define DUNE_STUFF_LA_CONTAINER_HH

#include <dune/common/typetraits.hh>

#include "container/interfaces.hh"
#include "container/dunedynamic.hh"
#include "container/eigen.hh"

namespace Dune {
namespace Stuff {
namespace LA {

template< class ContainerImp >
class Container
{
public:
  static ContainerImp create(const size_t /*size*/)
  {
    static_assert(Dune::AlwaysFalse< ContainerImp >::value, "Please specialize this class for this ContainerImp!");
  }
};

template< class S >
class Container< DuneDynamicVector< S > >
{
public:
  static DuneDynamicVector< S > create(const size_t size)
  {
    return DuneDynamicVector< S >(size, S(1));
  }
};

template< class S >
class Container< DuneDynamicMatrix< S > >
{
public:
  static DuneDynamicMatrix< S > create(const size_t size)
  {
    DuneDynamicMatrix< S > matrix(size, size);
    for (size_t ii = 0; ii < size; ++ii)
      matrix.unit_row(ii);
    return matrix;
  }
};

#if HAVE_EIGEN
template< class S >
class Container< EigenDenseVector< S > >
{
public:
  static EigenDenseVector< S > create(const size_t size)
  {
    return EigenDenseVector< S >(size, S(1));
  }
};

template< class S >
class Container< EigenMappedDenseVector< S > >
{
public:
  static EigenMappedDenseVector< S > create(const size_t size)
  {
    return EigenMappedDenseVector< S >(size, S(1));
  }
};

template< class S >
class Container< EigenRowMajorSparseMatrix< S > >
{
public:
  static EigenRowMajorSparseMatrix< S > create(const size_t size)
  {
    Dune::Stuff::LA::SparsityPatternDefault pattern(size);
    for (size_t ii = 0; ii < size; ++ii)
      pattern.inner(ii).insert(ii);
    Dune::Stuff::LA::EigenRowMajorSparseMatrix< S > matrix(size, size, pattern);
    for (size_t ii = 0; ii < size; ++ii)
      matrix.unit_row(ii);
    return matrix;
  }
};

template< class S >
class Container< EigenDenseMatrix< S > >
{
public:
  static EigenDenseMatrix< S > create(const size_t size)
  {
    Dune::Stuff::LA::EigenDenseMatrix< S > matrix(size, size);
    for (size_t ii = 0; ii < size; ++ii)
      matrix.unit_row(ii);
    return matrix;
  }
};
#endif // HAVE_EIGEN

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

#endif // DUNE_STUFF_LA_CONTAINER_HH
<|endoftext|>


<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        iutest_result.hpp
 * @brief       iris unit test result
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2011-2017, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_
#define INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_

//======================================================================
// include
#include "internal/iutest_message.hpp"

namespace iutest
{

//======================================================================
// declare
namespace detail
{

class DefaultGlobalTestPartResultReporter;

}   // end of namespace detail

//======================================================================
// class
/**
 * @brief   テスト結果の通知処理インターフェイス
*/
class TestPartResultReporterInterface
{
public:
    virtual ~TestPartResultReporterInterface() {}
    /**
     * @brief   テスト結果通知受け取り関数
     * @param [in] result   = テスト結果
    */
    virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};

/**
 * @brief   テスト結果を示すクラス
*/
class TestPartResult : public detail::iuCodeMessage
{
public:
    /**
     * @brief   結果のタイプ
    */
    enum Type
    {
        kAssumeFailure = -3,    //!< 前提条件エラー
        kSkip = -2,             //!< スキップ
        kWarning = -1,          //!< 警告
        kSuccess,               //!< 成功
        kNonFatalFailure,       //!< 致命的ではない失敗
        kFatalFailure           //!< 致命的な失敗
    };
public:
    /**
     * @brief   コンストラクタ
     * @param [in]  file    = ファイル名
     * @param [in]  line    = 行番号
     * @param [in]  message = メッセージ
     * @param [in]  type    = 結果のタイプ
    */
    TestPartResult(const char* file, int line, const char* message, Type type)
        : detail::iuCodeMessage(file, line, message), m_type(type) {}
    //! コピーコンストラクタ
    TestPartResult(const TestPartResult& rhs) : detail::iuCodeMessage(rhs)
        , m_type(rhs.m_type) {}

public:
    /**
    * @brief    失敗かどうか
    */
    static bool type_is_failed(Type type) IUTEST_CXX_NOEXCEPT_SPEC
    {
        if( iutest::IUTEST_FLAG(warning_into_error) )
        {
            if( type == kWarning )
            {
                return true;
            }
        }
        return type > kSuccess;
    }

public:
    /**
     * @brief   失敗かどうか
    */
    bool        failed() const IUTEST_CXX_NOEXCEPT_SPEC { return type_is_failed(m_type);; }
    /**
     * @brief   成功かどうか
    */
    bool        passed() const IUTEST_CXX_NOEXCEPT_SPEC { return !failed(); }
    /**
     * @brief   警告かどうか
    */
    bool        warning() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kWarning; }
    /**
     * @brief   スキップかどうか
    */
    bool        skipped() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kSkip; }
    /**
     * @brief   前提条件エラーかどうか
    */
    bool        assume_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kAssumeFailure; }
    /**
     * @brief   成功かどうか（警告を除く）
    */
    bool        succeeded() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kSuccess; }

    /**
     * @brief   致命的ではない失敗かどうか
    */
    bool        nonfatally_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kNonFatalFailure; }

    /**
     * @brief   致命的な失敗かどうか
    */
    bool        fatally_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kFatalFailure; }

    /**
     * @brief   理由
    */
    const char* summary() const { return message(); }

    /**
     * @brief   結果のタイプ取得
    */
    Type        type() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type; }

private:
    Type m_type;
};

//! TestPartResult print 出力
inline iu_ostream& operator << (iu_ostream& os, const TestPartResult& result)
{
    return os << result.make_message();
}

/**
 * @brief   テストプロパティ
 * @note    XML 属性
*/
class TestProperty
{
public:
    /**
     * @brief   コンストラクタ
     * @param [in]  key     = キー
     * @param [in]  value   = 値
    */
    TestProperty(const ::std::string& key, const ::std::string& value)
        : m_key(key), m_value(value) {}

public:
    /**
     * @brief   値の設定
    */
    void SetValue(const ::std::string& value) { m_value = value; }
    const char* key()   const { return m_key.c_str(); }     //!< キーの取得
    const char* value() const { return m_value.c_str(); }   //!< 値の取得

public:
    /**
     * @brief   有効なキーかどうかチェック
     * @retval  true=有効
     * @retval  false=無効
    */
    bool Validate(const char** ban_list, size_t size) const
    {
        return ValidateName(m_key, ban_list, ban_list+size);
    }
    /**
     * @brief   有効なキーかどうかチェック
     * @retval  true=有効
     * @retval  false=無効
    */
    template<typename Ite>
    static bool ValidateName(const ::std::string& name, Ite begin, Ite end)
    {
        return ::std::find(begin, end, name) == end;
    }
#if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING)
    /** @overload */
    template<typename T, size_t N>
    static bool ValidateName(const ::std::string& name, T (&ar)[N])
    {
        return ValidateName(name, ar, ar + N);
    }
#endif

private:
    friend class TestResult;
    ::std::string m_key;
    ::std::string m_value;
};

/**
 * @brief   テスト結果を示すクラス
*/
class TestResult
{
    typedef ::std::vector<TestPartResult>   TestPartResults;
    typedef ::std::vector<TestProperty>     TestPropertys;
public:
    TestResult() : m_elapsedmsec(0) {}

public:
    /**
     * @brief   成功したかどうか
     * @return  真偽値
    */
    bool        Passed() const { return !Failed(); }
    /**
     * @brief   失敗したかどうか
     * @return  真偽値
    */
    bool        Failed() const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->failed() )
            {
                return true;
            }
        }
        return false;
    }
    /**
     * @brief   スキップしたかどうか
     * @return  真偽値
    */
    bool        Skipped() const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->skipped() || it->assume_failed() )
            {
                return Passed();
            }
        }
        return false;
    }

    /**
     * @brief   致命的なエラーがあるかどうか
     * @return  真偽値
    */
    bool        HasFatalFailure() const { return HasResult(TestPartResult::kFatalFailure); }

    /**
     * @brief   致命的でないエラーがあるかどうか
     * @return  真偽値
    */
    bool        HasNonfatalFailure() const { return HasResult(TestPartResult::kNonFatalFailure); }

    /**
     * @brief   前提条件エラーがあるかどうか
     * @return  真偽値
    */
    bool        HasAssumeFailure() const { return HasResult(TestPartResult::kAssumeFailure); }

    /**
     * @brief   警告があるかどうか
     * @return  真偽値
    */
    bool        HasWarning() const { return HasResult(TestPartResult::kWarning); }

    /**
     * @brief   テストの実行時間の取得
     * @return  テストの実行時間
    */
    TimeInMillisec  elapsed_time() const IUTEST_CXX_NOEXCEPT_SPEC { return m_elapsedmsec; }

    /**
     * @brief   結果の数を取得
     * @return  結果の数
    */
    int         total_part_count() const { return static_cast<int>(m_test_part_results.size()); }

    /**
     * @brief   プロパティ総数の取得
     * @return  総数
    */
    int         test_property_count() const { return static_cast<int>(m_test_propertys.size()); }

    /**
     * @brief   テスト結果の取得
     * @param [in]  index   = インデックス
     * @return  テスト結果
    */
    const TestPartResult&   GetTestPartResult(int index) const { return m_test_part_results[index]; }

    /**
     * @brief   プロパティの取得
     * @param [in]  index   = インデックス
     * @return  プロパティの
    */
    const TestProperty&     GetTestProperty(int index) const { return m_test_propertys[index]; }

public:
    /**
     * @brief   失敗の数を取得
     * @return  失敗の数
    */
    int total_error_count() const
    {
        int count = 0;
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->failed() )
            {
                ++count;
            }
        }
        return count;
    }

private:
    void AddTestPartResult(const TestPartResult& result) { m_test_part_results.push_back(result); }
    void set_elapsed_time(TimeInMillisec time) IUTEST_CXX_NOEXCEPT_SPEC { m_elapsedmsec = time; }

private:
    void RecordProperty(const TestProperty& prop)
    {
        for( TestPropertys::iterator it=m_test_propertys.begin()
            , end=m_test_propertys.end(); it != end; ++it )
        {
            if( detail::IsStringEqual(it->key(), prop.key()) )
            {
                it->m_value = prop.m_value;
                return;
            }
        }
        m_test_propertys.push_back(prop);
    }

    void ClearResult()
    {
        m_test_part_results.clear();
    }
    void Clear()
    {
        m_test_part_results.clear();
        m_test_propertys.clear();
        m_elapsedmsec = 0;
    }
    bool HasResult(TestPartResult::Type eType) const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->type() == eType )
            {
                return true;
            }
        }
        return false;
    }
private:
    friend class UnitTestImpl;
    friend class TestInfo;
    friend class TestCase;
    friend class detail::DefaultGlobalTestPartResultReporter;

    TestPartResults m_test_part_results;
    TestPropertys   m_test_propertys;
    TimeInMillisec  m_elapsedmsec;

    IUTEST_PP_DISALLOW_COPY_AND_ASSIGN(TestResult);
};

}   // end of namespace iutest

#endif // INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_
<commit_msg>fix  cpp/rule-of-two<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        iutest_result.hpp
 * @brief       iris unit test result
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2011-2017, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_
#define INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_

//======================================================================
// include
#include "internal/iutest_message.hpp"

namespace iutest
{

//======================================================================
// declare
namespace detail
{

class DefaultGlobalTestPartResultReporter;

}   // end of namespace detail

//======================================================================
// class
/**
 * @brief   テスト結果の通知処理インターフェイス
*/
class TestPartResultReporterInterface
{
public:
    virtual ~TestPartResultReporterInterface() {}
    /**
     * @brief   テスト結果通知受け取り関数
     * @param [in] result   = テスト結果
    */
    virtual void ReportTestPartResult(const TestPartResult& result) = 0;
};

/**
 * @brief   テスト結果を示すクラス
*/
class TestPartResult : public detail::iuCodeMessage
{
public:
    /**
     * @brief   結果のタイプ
    */
    enum Type
    {
        kAssumeFailure = -3,    //!< 前提条件エラー
        kSkip = -2,             //!< スキップ
        kWarning = -1,          //!< 警告
        kSuccess,               //!< 成功
        kNonFatalFailure,       //!< 致命的ではない失敗
        kFatalFailure           //!< 致命的な失敗
    };
public:
    /**
     * @brief   コンストラクタ
     * @param [in]  file    = ファイル名
     * @param [in]  line    = 行番号
     * @param [in]  message = メッセージ
     * @param [in]  type    = 結果のタイプ
    */
    TestPartResult(const char* file, int line, const char* message, Type type)
        : detail::iuCodeMessage(file, line, message), m_type(type) {}

public:
    /**
    * @brief    失敗かどうか
    */
    static bool type_is_failed(Type type) IUTEST_CXX_NOEXCEPT_SPEC
    {
        if( iutest::IUTEST_FLAG(warning_into_error) )
        {
            if( type == kWarning )
            {
                return true;
            }
        }
        return type > kSuccess;
    }

public:
    /**
     * @brief   失敗かどうか
    */
    bool        failed() const IUTEST_CXX_NOEXCEPT_SPEC { return type_is_failed(m_type);; }
    /**
     * @brief   成功かどうか
    */
    bool        passed() const IUTEST_CXX_NOEXCEPT_SPEC { return !failed(); }
    /**
     * @brief   警告かどうか
    */
    bool        warning() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kWarning; }
    /**
     * @brief   スキップかどうか
    */
    bool        skipped() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kSkip; }
    /**
     * @brief   前提条件エラーかどうか
    */
    bool        assume_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kAssumeFailure; }
    /**
     * @brief   成功かどうか（警告を除く）
    */
    bool        succeeded() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kSuccess; }

    /**
     * @brief   致命的ではない失敗かどうか
    */
    bool        nonfatally_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kNonFatalFailure; }

    /**
     * @brief   致命的な失敗かどうか
    */
    bool        fatally_failed() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type == kFatalFailure; }

    /**
     * @brief   理由
    */
    const char* summary() const { return message(); }

    /**
     * @brief   結果のタイプ取得
    */
    Type        type() const IUTEST_CXX_NOEXCEPT_SPEC { return m_type; }

private:
    Type m_type;
};

//! TestPartResult print 出力
inline iu_ostream& operator << (iu_ostream& os, const TestPartResult& result)
{
    return os << result.make_message();
}

/**
 * @brief   テストプロパティ
 * @note    XML 属性
*/
class TestProperty
{
public:
    /**
     * @brief   コンストラクタ
     * @param [in]  key     = キー
     * @param [in]  value   = 値
    */
    TestProperty(const ::std::string& key, const ::std::string& value)
        : m_key(key), m_value(value) {}

public:
    /**
     * @brief   値の設定
    */
    void SetValue(const ::std::string& value) { m_value = value; }
    const char* key()   const { return m_key.c_str(); }     //!< キーの取得
    const char* value() const { return m_value.c_str(); }   //!< 値の取得

public:
    /**
     * @brief   有効なキーかどうかチェック
     * @retval  true=有効
     * @retval  false=無効
    */
    bool Validate(const char** ban_list, size_t size) const
    {
        return ValidateName(m_key, ban_list, ban_list+size);
    }
    /**
     * @brief   有効なキーかどうかチェック
     * @retval  true=有効
     * @retval  false=無効
    */
    template<typename Ite>
    static bool ValidateName(const ::std::string& name, Ite begin, Ite end)
    {
        return ::std::find(begin, end, name) == end;
    }
#if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING)
    /** @overload */
    template<typename T, size_t N>
    static bool ValidateName(const ::std::string& name, T (&ar)[N])
    {
        return ValidateName(name, ar, ar + N);
    }
#endif

private:
    friend class TestResult;
    ::std::string m_key;
    ::std::string m_value;
};

/**
 * @brief   テスト結果を示すクラス
*/
class TestResult
{
    typedef ::std::vector<TestPartResult>   TestPartResults;
    typedef ::std::vector<TestProperty>     TestPropertys;
public:
    TestResult() : m_elapsedmsec(0) {}

public:
    /**
     * @brief   成功したかどうか
     * @return  真偽値
    */
    bool        Passed() const { return !Failed(); }
    /**
     * @brief   失敗したかどうか
     * @return  真偽値
    */
    bool        Failed() const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->failed() )
            {
                return true;
            }
        }
        return false;
    }
    /**
     * @brief   スキップしたかどうか
     * @return  真偽値
    */
    bool        Skipped() const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->skipped() || it->assume_failed() )
            {
                return Passed();
            }
        }
        return false;
    }

    /**
     * @brief   致命的なエラーがあるかどうか
     * @return  真偽値
    */
    bool        HasFatalFailure() const { return HasResult(TestPartResult::kFatalFailure); }

    /**
     * @brief   致命的でないエラーがあるかどうか
     * @return  真偽値
    */
    bool        HasNonfatalFailure() const { return HasResult(TestPartResult::kNonFatalFailure); }

    /**
     * @brief   前提条件エラーがあるかどうか
     * @return  真偽値
    */
    bool        HasAssumeFailure() const { return HasResult(TestPartResult::kAssumeFailure); }

    /**
     * @brief   警告があるかどうか
     * @return  真偽値
    */
    bool        HasWarning() const { return HasResult(TestPartResult::kWarning); }

    /**
     * @brief   テストの実行時間の取得
     * @return  テストの実行時間
    */
    TimeInMillisec  elapsed_time() const IUTEST_CXX_NOEXCEPT_SPEC { return m_elapsedmsec; }

    /**
     * @brief   結果の数を取得
     * @return  結果の数
    */
    int         total_part_count() const { return static_cast<int>(m_test_part_results.size()); }

    /**
     * @brief   プロパティ総数の取得
     * @return  総数
    */
    int         test_property_count() const { return static_cast<int>(m_test_propertys.size()); }

    /**
     * @brief   テスト結果の取得
     * @param [in]  index   = インデックス
     * @return  テスト結果
    */
    const TestPartResult&   GetTestPartResult(int index) const { return m_test_part_results[index]; }

    /**
     * @brief   プロパティの取得
     * @param [in]  index   = インデックス
     * @return  プロパティの
    */
    const TestProperty&     GetTestProperty(int index) const { return m_test_propertys[index]; }

public:
    /**
     * @brief   失敗の数を取得
     * @return  失敗の数
    */
    int total_error_count() const
    {
        int count = 0;
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->failed() )
            {
                ++count;
            }
        }
        return count;
    }

private:
    void AddTestPartResult(const TestPartResult& result) { m_test_part_results.push_back(result); }
    void set_elapsed_time(TimeInMillisec time) IUTEST_CXX_NOEXCEPT_SPEC { m_elapsedmsec = time; }

private:
    void RecordProperty(const TestProperty& prop)
    {
        for( TestPropertys::iterator it=m_test_propertys.begin()
            , end=m_test_propertys.end(); it != end; ++it )
        {
            if( detail::IsStringEqual(it->key(), prop.key()) )
            {
                it->m_value = prop.m_value;
                return;
            }
        }
        m_test_propertys.push_back(prop);
    }

    void ClearResult()
    {
        m_test_part_results.clear();
    }
    void Clear()
    {
        m_test_part_results.clear();
        m_test_propertys.clear();
        m_elapsedmsec = 0;
    }
    bool HasResult(TestPartResult::Type eType) const
    {
        for( TestPartResults::const_iterator it=m_test_part_results.begin()
            , end=m_test_part_results.end(); it != end; ++it )
        {
            if( it->type() == eType )
            {
                return true;
            }
        }
        return false;
    }
private:
    friend class UnitTestImpl;
    friend class TestInfo;
    friend class TestCase;
    friend class detail::DefaultGlobalTestPartResultReporter;

    TestPartResults m_test_part_results;
    TestPropertys   m_test_propertys;
    TimeInMillisec  m_elapsedmsec;

    IUTEST_PP_DISALLOW_COPY_AND_ASSIGN(TestResult);
};

}   // end of namespace iutest

#endif // INCG_IRIS_IUTEST_RESULT_HPP_D27B1599_F42F_4E2D_B3EB_FACE24C2B921_
<|endoftext|>


<commit_before>#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <scheduler.h>
#include <mock_scheduler.h>
#include <external_mocks.h>
#include <rule_tester_util.h>
#include <rules/rules.h>
#include <mock_index.h>

DEFINE_string(input_events, "", "json string containing input events");

mock_scheduler mock_sched;
scheduler g_scheduler{mock_sched};
external_mocks g_external_mocks{};

int main(int argc, char **argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);

  bool ok;
  std::vector<Event> events = json_to_events(FLAGS_input_events, ok);

  if (!ok) {
    LOG(ERROR) << "couldn't parse input events";
    return -1;
  }

  mock_index idx;
  class index index(idx);
  auto rule_stream = rules(index);

  for (const auto & event: events) {
    mock_sched.process_event_time(event.time());
    rule_stream(event);
  }

  std::cout << results(idx.events(), g_external_mocks.calls()) << "\n";

  return 0;
}
<commit_msg>Initialize libcds in rules_tester<commit_after>#include <gflags/gflags.h>
#include <glog/logging.h>
#include <iostream>
#include <scheduler.h>
#include <mock_scheduler.h>
#include <external_mocks.h>
#include <rule_tester_util.h>
#include <rules/rules.h>
#include <mock_index.h>
#include "atom.h"

DEFINE_string(input_events, "", "json string containing input events");

mock_scheduler mock_sched;
scheduler g_scheduler{mock_sched};
external_mocks g_external_mocks{};

int main(int argc, char **argv) {
  cds::Initialize();

  {
    cds::gc::HP hpGC;
    atom<bool>::attach_thread();

    google::ParseCommandLineFlags(&argc, &argv, true);

    bool ok;
    std::vector<Event> events = json_to_events(FLAGS_input_events, ok);

    if (!ok) {
      LOG(ERROR) << "couldn't parse input events";
      return -1;
    }

    mock_index idx;
    class index index(idx);
    auto rule_stream = sdo(rules(index));

    for (const auto & event: events) {
      mock_sched.process_event_time(event.time());
      rule_stream(event);
    }

    std::cout << results(idx.events(), g_external_mocks.calls()) << "\n";
  }
  cds::Terminate();

  return 0;
}
<|endoftext|>