<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/importer/external_process_importer_client.h"

#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/importer/external_process_importer_host.h"
#include "chrome/browser/importer/in_process_importer_bridge.h"
#include "chrome/common/importer/firefox_importer_utils.h"
#include "chrome/common/importer/imported_bookmark_entry.h"
#include "chrome/common/importer/profile_import_process_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/utility_process_host.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

using content::BrowserThread;
using content::UtilityProcessHost;

ExternalProcessImporterClient::ExternalProcessImporterClient(
    ExternalProcessImporterHost* importer_host,
    const importer::SourceProfile& source_profile,
    uint16 items,
    InProcessImporterBridge* bridge)
    : total_bookmarks_count_(0),
      total_history_rows_count_(0),
      total_favicons_count_(0),
      process_importer_host_(importer_host),
      source_profile_(source_profile),
      items_(items),
      bridge_(bridge),
      cancelled_(false) {
  process_importer_host_->NotifyImportStarted();
}

void ExternalProcessImporterClient::Start() {
  AddRef();  // balanced in Cleanup.
  BrowserThread::ID thread_id;
  CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_id));
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ExternalProcessImporterClient::StartProcessOnIOThread,
                 this,
                 thread_id));
}

void ExternalProcessImporterClient::Cancel() {
  if (cancelled_)
    return;

  cancelled_ = true;
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(
          &ExternalProcessImporterClient::CancelImportProcessOnIOThread,
          this));
  Release();
}

void ExternalProcessImporterClient::OnProcessCrashed(int exit_code) {
  DLOG(ERROR) << __FUNCTION__;
  if (cancelled_)
    return;

  process_importer_host_->Cancel();
}

bool ExternalProcessImporterClient::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(ExternalProcessImporterClient, message)
    // Notification messages about the state of the import process.
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_Import_Started,
                        OnImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_Import_Finished,
                        OnImportFinished)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_ImportItem_Started,
                        OnImportItemStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_ImportItem_Finished,
                        OnImportItemFinished)
    // Data messages containing items to be written to the user profile.
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHistoryImportStart,
                        OnHistoryImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHistoryImportGroup,
                        OnHistoryImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHomePageImportReady,
                        OnHomePageImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyBookmarksImportStart,
                        OnBookmarksImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyBookmarksImportGroup,
                        OnBookmarksImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFaviconsImportStart,
                        OnFaviconsImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFaviconsImportGroup,
                        OnFaviconsImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyPasswordFormReady,
                        OnPasswordFormImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyKeywordsReady,
                        OnKeywordsImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFirefoxSearchEngData,
                        OnFirefoxSearchEngineDataReceived)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyIE7PasswordInfo,
                        OnIE7PasswordReceived)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void ExternalProcessImporterClient::OnImportStart() {
  if (cancelled_)
    return;

  bridge_->NotifyStarted();
}

void ExternalProcessImporterClient::OnImportFinished(
    bool succeeded, const std::string& error_msg) {
  if (cancelled_)
    return;

  if (!succeeded)
    LOG(WARNING) << "Import failed.  Error: " << error_msg;
  Cleanup();
}

void ExternalProcessImporterClient::OnImportItemStart(int item_data) {
  if (cancelled_)
    return;

  bridge_->NotifyItemStarted(static_cast<importer::ImportItem>(item_data));
}

void ExternalProcessImporterClient::OnImportItemFinished(int item_data) {
  if (cancelled_)
    return;

  importer::ImportItem import_item =
      static_cast<importer::ImportItem>(item_data);
  bridge_->NotifyItemEnded(import_item);
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ExternalProcessImporterClient::NotifyItemFinishedOnIOThread,
                 this,
                 import_item));
}

void ExternalProcessImporterClient::OnHistoryImportStart(
    size_t total_history_rows_count) {
  if (cancelled_)
    return;

  total_history_rows_count_ = total_history_rows_count;
  history_rows_.reserve(total_history_rows_count);
}

void ExternalProcessImporterClient::OnHistoryImportGroup(
    const std::vector<ImporterURLRow>& history_rows_group,
    int visit_source) {
  if (cancelled_)
    return;

  history_rows_.insert(history_rows_.end(), history_rows_group.begin(),
                       history_rows_group.end());
  if (history_rows_.size() == total_history_rows_count_)
    bridge_->SetHistoryItems(history_rows_,
                             static_cast<importer::VisitSource>(visit_source));
}

void ExternalProcessImporterClient::OnHomePageImportReady(
    const GURL& home_page) {
  if (cancelled_)
    return;

  bridge_->AddHomePage(home_page);
}

void ExternalProcessImporterClient::OnBookmarksImportStart(
    const string16& first_folder_name,
    size_t total_bookmarks_count) {
  if (cancelled_)
    return;

  bookmarks_first_folder_name_ = first_folder_name;
  total_bookmarks_count_ = total_bookmarks_count;
  bookmarks_.reserve(total_bookmarks_count);
}

void ExternalProcessImporterClient::OnBookmarksImportGroup(
    const std::vector<ImportedBookmarkEntry>& bookmarks_group) {
  if (cancelled_)
    return;

  // Collect sets of bookmarks from importer process until we have reached
  // total_bookmarks_count_:
  bookmarks_.insert(bookmarks_.end(), bookmarks_group.begin(),
                    bookmarks_group.end());
  if (bookmarks_.size() == total_bookmarks_count_)
    bridge_->AddBookmarks(bookmarks_, bookmarks_first_folder_name_);
}

void ExternalProcessImporterClient::OnFaviconsImportStart(
    size_t total_favicons_count) {
  if (cancelled_)
    return;

  total_favicons_count_ = total_favicons_count;
  favicons_.reserve(total_favicons_count);
}

void ExternalProcessImporterClient::OnFaviconsImportGroup(
    const std::vector<ImportedFaviconUsage>& favicons_group) {
  if (cancelled_)
    return;

  favicons_.insert(favicons_.end(), favicons_group.begin(),
                    favicons_group.end());
  if (favicons_.size() == total_favicons_count_)
    bridge_->SetFavicons(favicons_);
}

void ExternalProcessImporterClient::OnPasswordFormImportReady(
    const content::PasswordForm& form) {
  if (cancelled_)
    return;

  bridge_->SetPasswordForm(form);
}

void ExternalProcessImporterClient::OnKeywordsImportReady(
    const std::vector<importer::URLKeywordInfo>& url_keywords,
    bool unique_on_host_and_path) {
  if (cancelled_)
    return;
  bridge_->SetKeywords(url_keywords, unique_on_host_and_path);
}

void ExternalProcessImporterClient::OnFirefoxSearchEngineDataReceived(
    const std::vector<std::string> search_engine_data) {
  if (cancelled_)
    return;
  bridge_->SetFirefoxSearchEnginesXMLData(search_engine_data);
}

#if defined(OS_WIN)
void ExternalProcessImporterClient::OnIE7PasswordReceived(
    const importer::ImporterIE7PasswordInfo& importer_password_info) {
  if (cancelled_)
    return;
  bridge_->AddIE7PasswordInfo(importer_password_info);
}
#endif

ExternalProcessImporterClient::~ExternalProcessImporterClient() {}

void ExternalProcessImporterClient::Cleanup() {
  if (cancelled_)
    return;

  if (process_importer_host_)
    process_importer_host_->NotifyImportEnded();
  Release();
}

void ExternalProcessImporterClient::CancelImportProcessOnIOThread() {
  if (utility_process_host_.get())
    utility_process_host_->Send(new ProfileImportProcessMsg_CancelImport());
}

void ExternalProcessImporterClient::NotifyItemFinishedOnIOThread(
    importer::ImportItem import_item) {
  utility_process_host_->Send(
      new ProfileImportProcessMsg_ReportImportItemFinished(import_item));
}

void ExternalProcessImporterClient::StartProcessOnIOThread(
    BrowserThread::ID thread_id) {
  utility_process_host_ = UtilityProcessHost::Create(
      this, BrowserThread::GetMessageLoopProxyForThread(thread_id).get())
      ->AsWeakPtr();
  utility_process_host_->DisableSandbox();

#if defined(OS_MACOSX)
  base::EnvironmentVector env;
  std::string dylib_path = GetFirefoxDylibPath().value();
  if (!dylib_path.empty())
    env.push_back(std::make_pair("DYLD_FALLBACK_LIBRARY_PATH", dylib_path));
  utility_process_host_->SetEnv(env);
#endif

  // Dictionary of all localized strings that could be needed by the importer
  // in the external process.
  DictionaryValue localized_strings;
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_GROUP_FROM_FIREFOX),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_GROUP_FROM_FIREFOX));
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_GROUP_FROM_SAFARI),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_GROUP_FROM_SAFARI));
  localized_strings.SetString(
      base::IntToString(IDS_IMPORT_FROM_FIREFOX),
      l10n_util::GetStringUTF8(IDS_IMPORT_FROM_FIREFOX));
  localized_strings.SetString(
      base::IntToString(IDS_IMPORT_FROM_SAFARI),
      l10n_util::GetStringUTF8(IDS_IMPORT_FROM_SAFARI));
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_BAR_FOLDER_NAME),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_BAR_FOLDER_NAME));

  utility_process_host_->Send(new ProfileImportProcessMsg_StartImport(
      source_profile_, items_, localized_strings));
}
<commit_msg>Display "Imported" folder name again.<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/importer/external_process_importer_client.h"

#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/importer/external_process_importer_host.h"
#include "chrome/browser/importer/in_process_importer_bridge.h"
#include "chrome/common/importer/firefox_importer_utils.h"
#include "chrome/common/importer/imported_bookmark_entry.h"
#include "chrome/common/importer/profile_import_process_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/utility_process_host.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

using content::BrowserThread;
using content::UtilityProcessHost;

ExternalProcessImporterClient::ExternalProcessImporterClient(
    ExternalProcessImporterHost* importer_host,
    const importer::SourceProfile& source_profile,
    uint16 items,
    InProcessImporterBridge* bridge)
    : total_bookmarks_count_(0),
      total_history_rows_count_(0),
      total_favicons_count_(0),
      process_importer_host_(importer_host),
      source_profile_(source_profile),
      items_(items),
      bridge_(bridge),
      cancelled_(false) {
  process_importer_host_->NotifyImportStarted();
}

void ExternalProcessImporterClient::Start() {
  AddRef();  // balanced in Cleanup.
  BrowserThread::ID thread_id;
  CHECK(BrowserThread::GetCurrentThreadIdentifier(&thread_id));
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ExternalProcessImporterClient::StartProcessOnIOThread,
                 this,
                 thread_id));
}

void ExternalProcessImporterClient::Cancel() {
  if (cancelled_)
    return;

  cancelled_ = true;
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(
          &ExternalProcessImporterClient::CancelImportProcessOnIOThread,
          this));
  Release();
}

void ExternalProcessImporterClient::OnProcessCrashed(int exit_code) {
  DLOG(ERROR) << __FUNCTION__;
  if (cancelled_)
    return;

  process_importer_host_->Cancel();
}

bool ExternalProcessImporterClient::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(ExternalProcessImporterClient, message)
    // Notification messages about the state of the import process.
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_Import_Started,
                        OnImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_Import_Finished,
                        OnImportFinished)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_ImportItem_Started,
                        OnImportItemStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_ImportItem_Finished,
                        OnImportItemFinished)
    // Data messages containing items to be written to the user profile.
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHistoryImportStart,
                        OnHistoryImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHistoryImportGroup,
                        OnHistoryImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyHomePageImportReady,
                        OnHomePageImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyBookmarksImportStart,
                        OnBookmarksImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyBookmarksImportGroup,
                        OnBookmarksImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFaviconsImportStart,
                        OnFaviconsImportStart)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFaviconsImportGroup,
                        OnFaviconsImportGroup)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyPasswordFormReady,
                        OnPasswordFormImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyKeywordsReady,
                        OnKeywordsImportReady)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyFirefoxSearchEngData,
                        OnFirefoxSearchEngineDataReceived)
#if defined(OS_WIN)
    IPC_MESSAGE_HANDLER(ProfileImportProcessHostMsg_NotifyIE7PasswordInfo,
                        OnIE7PasswordReceived)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void ExternalProcessImporterClient::OnImportStart() {
  if (cancelled_)
    return;

  bridge_->NotifyStarted();
}

void ExternalProcessImporterClient::OnImportFinished(
    bool succeeded, const std::string& error_msg) {
  if (cancelled_)
    return;

  if (!succeeded)
    LOG(WARNING) << "Import failed.  Error: " << error_msg;
  Cleanup();
}

void ExternalProcessImporterClient::OnImportItemStart(int item_data) {
  if (cancelled_)
    return;

  bridge_->NotifyItemStarted(static_cast<importer::ImportItem>(item_data));
}

void ExternalProcessImporterClient::OnImportItemFinished(int item_data) {
  if (cancelled_)
    return;

  importer::ImportItem import_item =
      static_cast<importer::ImportItem>(item_data);
  bridge_->NotifyItemEnded(import_item);
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&ExternalProcessImporterClient::NotifyItemFinishedOnIOThread,
                 this,
                 import_item));
}

void ExternalProcessImporterClient::OnHistoryImportStart(
    size_t total_history_rows_count) {
  if (cancelled_)
    return;

  total_history_rows_count_ = total_history_rows_count;
  history_rows_.reserve(total_history_rows_count);
}

void ExternalProcessImporterClient::OnHistoryImportGroup(
    const std::vector<ImporterURLRow>& history_rows_group,
    int visit_source) {
  if (cancelled_)
    return;

  history_rows_.insert(history_rows_.end(), history_rows_group.begin(),
                       history_rows_group.end());
  if (history_rows_.size() == total_history_rows_count_)
    bridge_->SetHistoryItems(history_rows_,
                             static_cast<importer::VisitSource>(visit_source));
}

void ExternalProcessImporterClient::OnHomePageImportReady(
    const GURL& home_page) {
  if (cancelled_)
    return;

  bridge_->AddHomePage(home_page);
}

void ExternalProcessImporterClient::OnBookmarksImportStart(
    const string16& first_folder_name,
    size_t total_bookmarks_count) {
  if (cancelled_)
    return;

  bookmarks_first_folder_name_ = first_folder_name;
  total_bookmarks_count_ = total_bookmarks_count;
  bookmarks_.reserve(total_bookmarks_count);
}

void ExternalProcessImporterClient::OnBookmarksImportGroup(
    const std::vector<ImportedBookmarkEntry>& bookmarks_group) {
  if (cancelled_)
    return;

  // Collect sets of bookmarks from importer process until we have reached
  // total_bookmarks_count_:
  bookmarks_.insert(bookmarks_.end(), bookmarks_group.begin(),
                    bookmarks_group.end());
  if (bookmarks_.size() == total_bookmarks_count_)
    bridge_->AddBookmarks(bookmarks_, bookmarks_first_folder_name_);
}

void ExternalProcessImporterClient::OnFaviconsImportStart(
    size_t total_favicons_count) {
  if (cancelled_)
    return;

  total_favicons_count_ = total_favicons_count;
  favicons_.reserve(total_favicons_count);
}

void ExternalProcessImporterClient::OnFaviconsImportGroup(
    const std::vector<ImportedFaviconUsage>& favicons_group) {
  if (cancelled_)
    return;

  favicons_.insert(favicons_.end(), favicons_group.begin(),
                    favicons_group.end());
  if (favicons_.size() == total_favicons_count_)
    bridge_->SetFavicons(favicons_);
}

void ExternalProcessImporterClient::OnPasswordFormImportReady(
    const content::PasswordForm& form) {
  if (cancelled_)
    return;

  bridge_->SetPasswordForm(form);
}

void ExternalProcessImporterClient::OnKeywordsImportReady(
    const std::vector<importer::URLKeywordInfo>& url_keywords,
    bool unique_on_host_and_path) {
  if (cancelled_)
    return;
  bridge_->SetKeywords(url_keywords, unique_on_host_and_path);
}

void ExternalProcessImporterClient::OnFirefoxSearchEngineDataReceived(
    const std::vector<std::string> search_engine_data) {
  if (cancelled_)
    return;
  bridge_->SetFirefoxSearchEnginesXMLData(search_engine_data);
}

#if defined(OS_WIN)
void ExternalProcessImporterClient::OnIE7PasswordReceived(
    const importer::ImporterIE7PasswordInfo& importer_password_info) {
  if (cancelled_)
    return;
  bridge_->AddIE7PasswordInfo(importer_password_info);
}
#endif

ExternalProcessImporterClient::~ExternalProcessImporterClient() {}

void ExternalProcessImporterClient::Cleanup() {
  if (cancelled_)
    return;

  if (process_importer_host_)
    process_importer_host_->NotifyImportEnded();
  Release();
}

void ExternalProcessImporterClient::CancelImportProcessOnIOThread() {
  if (utility_process_host_.get())
    utility_process_host_->Send(new ProfileImportProcessMsg_CancelImport());
}

void ExternalProcessImporterClient::NotifyItemFinishedOnIOThread(
    importer::ImportItem import_item) {
  utility_process_host_->Send(
      new ProfileImportProcessMsg_ReportImportItemFinished(import_item));
}

void ExternalProcessImporterClient::StartProcessOnIOThread(
    BrowserThread::ID thread_id) {
  utility_process_host_ = UtilityProcessHost::Create(
      this, BrowserThread::GetMessageLoopProxyForThread(thread_id).get())
      ->AsWeakPtr();
  utility_process_host_->DisableSandbox();

#if defined(OS_MACOSX)
  base::EnvironmentVector env;
  std::string dylib_path = GetFirefoxDylibPath().value();
  if (!dylib_path.empty())
    env.push_back(std::make_pair("DYLD_FALLBACK_LIBRARY_PATH", dylib_path));
  utility_process_host_->SetEnv(env);
#endif

  // Dictionary of all localized strings that could be needed by the importer
  // in the external process.
  DictionaryValue localized_strings;
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_GROUP),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_GROUP));
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_GROUP_FROM_FIREFOX),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_GROUP_FROM_FIREFOX));
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_GROUP_FROM_SAFARI),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_GROUP_FROM_SAFARI));
  localized_strings.SetString(
      base::IntToString(IDS_IMPORT_FROM_FIREFOX),
      l10n_util::GetStringUTF8(IDS_IMPORT_FROM_FIREFOX));
  localized_strings.SetString(
      base::IntToString(IDS_IMPORT_FROM_ICEWEASEL),
      l10n_util::GetStringUTF8(IDS_IMPORT_FROM_ICEWEASEL));
  localized_strings.SetString(
      base::IntToString(IDS_IMPORT_FROM_SAFARI),
      l10n_util::GetStringUTF8(IDS_IMPORT_FROM_SAFARI));
  localized_strings.SetString(
      base::IntToString(IDS_BOOKMARK_BAR_FOLDER_NAME),
      l10n_util::GetStringUTF8(IDS_BOOKMARK_BAR_FOLDER_NAME));

  utility_process_host_->Send(new ProfileImportProcessMsg_StartImport(
      source_profile_, items_, localized_strings));
}
<|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/renderer_host/render_widget_host_view_gtk.h"

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>

#include "base/logging.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_device_linux.h"

namespace {

// -----------------------------------------------------------------------------
// Callback functions to proxy to RenderWidgetHostViewGtk...

gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
                        RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
                     RenderWidgetHostViewGtk* host) {
  const gfx::Rect damage_rect(expose->area);
  host->Paint(damage_rect);
  return FALSE;
}

gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
                              RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
                 RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
                  RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
                                 RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
                        RenderWidgetHostViewGtk* host) {
  return FALSE;
}

gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
                          RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

}  // anonymous namespace

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  return new RenderWidgetHostViewGtk(widget);
}

RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget)
    : widget_(widget) {
  widget_->set_view(this);

  view_ = gtk_drawing_area_new();

  gtk_widget_add_events(view_, GDK_EXPOSURE_MASK |
                               GDK_POINTER_MOTION_MASK |
                               GDK_BUTTON_PRESS_MASK |
                               GDK_BUTTON_RELEASE_MASK |
                               GDK_KEY_PRESS_MASK |
                               GDK_KEY_RELEASE_MASK);
  GTK_WIDGET_SET_FLAGS(view_, GTK_CAN_FOCUS);
  g_signal_connect(view_, "configure-event", G_CALLBACK(ConfigureEvent), this);
  g_signal_connect(view_, "expose-event", G_CALLBACK(ExposeEvent), this);
  g_signal_connect(view_, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
                   this);
  g_signal_connect(view_, "key-release-event",
                   G_CALLBACK(KeyPressReleaseEvent), this);
  g_signal_connect(view_, "focus-in-event", G_CALLBACK(FocusIn), this);
  g_signal_connect(view_, "focus-out-event", G_CALLBACK(FocusOut), this);
  g_signal_connect(view_, "button-press-event",
                   G_CALLBACK(ButtonPressReleaseEvent), this);
  g_signal_connect(view_, "button-release-event",
                   G_CALLBACK(ButtonPressReleaseEvent), this);
  g_signal_connect(view_, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
                   this);
  g_signal_connect(view_, "scroll-event", G_CALLBACK(MouseScrollEvent),
                   this);
}

RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
  gtk_widget_destroy(view_);
}

void RenderWidgetHostViewGtk::DidBecomeSelected() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::WasHidden() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
  NOTIMPLEMENTED();
}

gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
  NOTIMPLEMENTED();
  return NULL;
}

void RenderWidgetHostViewGtk::MovePluginWindows(
    const std::vector<WebPluginGeometry>& plugin_window_moves) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Focus() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Blur() {
  NOTIMPLEMENTED();
}

bool RenderWidgetHostViewGtk::HasFocus() {
  NOTIMPLEMENTED();
  return false;
}

void RenderWidgetHostViewGtk::Show() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Hide() {
  NOTIMPLEMENTED();
}

gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
  return gfx::Rect(view_->allocation.x, view_->allocation.y,
                   view_->allocation.width, view_->allocation.height);
}

void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::UpdateCursorIfOverSelf() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
                                              const gfx::Rect& caret_rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
                                            int dy) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::RendererGone() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Destroy() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
  BackingStore* backing_store = widget_->GetBackingStore();

  if (backing_store) {
    GdkRectangle grect = {
      damage_rect.x(),
      damage_rect.y(),
      damage_rect.width(),
      damage_rect.height()
    };
    GdkWindow* window = view_->window;
    gdk_window_begin_paint_rect(window, &grect);

    skia::PlatformDeviceLinux &platdev =
        backing_store->canvas()->getTopPlatformDevice();
    skia::BitmapPlatformDeviceLinux* const bitdev =
        static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
    cairo_t* cairo_drawable = gdk_cairo_create(window);
    cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
    cairo_paint(cairo_drawable);
    cairo_destroy(cairo_drawable);

    gdk_window_end_paint(window);
  } else {
    NOTIMPLEMENTED();
  }
}

<commit_msg>Linux: fix crash in OnGetScreenInfo<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/renderer_host/render_widget_host_view_gtk.h"

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>

#include "base/logging.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_device_linux.h"

namespace {

// -----------------------------------------------------------------------------
// Callback functions to proxy to RenderWidgetHostViewGtk...

gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
                        RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
                     RenderWidgetHostViewGtk* host) {
  const gfx::Rect damage_rect(expose->area);
  host->Paint(damage_rect);
  return FALSE;
}

gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
                              RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
                 RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
                  RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
                                 RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
                        RenderWidgetHostViewGtk* host) {
  return FALSE;
}

gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
                          RenderWidgetHostViewGtk* host) {
  NOTIMPLEMENTED();
  return FALSE;
}

}  // anonymous namespace

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  return new RenderWidgetHostViewGtk(widget);
}

RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget)
    : widget_(widget) {
  widget_->set_view(this);

  view_ = gtk_drawing_area_new();

  gtk_widget_add_events(view_, GDK_EXPOSURE_MASK |
                               GDK_POINTER_MOTION_MASK |
                               GDK_BUTTON_PRESS_MASK |
                               GDK_BUTTON_RELEASE_MASK |
                               GDK_KEY_PRESS_MASK |
                               GDK_KEY_RELEASE_MASK);
  GTK_WIDGET_SET_FLAGS(view_, GTK_CAN_FOCUS);
  g_signal_connect(view_, "configure-event", G_CALLBACK(ConfigureEvent), this);
  g_signal_connect(view_, "expose-event", G_CALLBACK(ExposeEvent), this);
  g_signal_connect(view_, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
                   this);
  g_signal_connect(view_, "key-release-event",
                   G_CALLBACK(KeyPressReleaseEvent), this);
  g_signal_connect(view_, "focus-in-event", G_CALLBACK(FocusIn), this);
  g_signal_connect(view_, "focus-out-event", G_CALLBACK(FocusOut), this);
  g_signal_connect(view_, "button-press-event",
                   G_CALLBACK(ButtonPressReleaseEvent), this);
  g_signal_connect(view_, "button-release-event",
                   G_CALLBACK(ButtonPressReleaseEvent), this);
  g_signal_connect(view_, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
                   this);
  g_signal_connect(view_, "scroll-event", G_CALLBACK(MouseScrollEvent),
                   this);
}

RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
  gtk_widget_destroy(view_);
}

void RenderWidgetHostViewGtk::DidBecomeSelected() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::WasHidden() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
  NOTIMPLEMENTED();
}

gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
  NOTIMPLEMENTED();
  // TODO(port): We need to pass some widget pointer out here because the
  // renderer echos it back to us when it asks for GetScreenInfo. However, we
  // should probably be passing the top-level window or some such instead.
  return view_;
}

void RenderWidgetHostViewGtk::MovePluginWindows(
    const std::vector<WebPluginGeometry>& plugin_window_moves) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Focus() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Blur() {
  NOTIMPLEMENTED();
}

bool RenderWidgetHostViewGtk::HasFocus() {
  NOTIMPLEMENTED();
  return false;
}

void RenderWidgetHostViewGtk::Show() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Hide() {
  NOTIMPLEMENTED();
}

gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
  return gfx::Rect(view_->allocation.x, view_->allocation.y,
                   view_->allocation.width, view_->allocation.height);
}

void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::UpdateCursorIfOverSelf() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
                                              const gfx::Rect& caret_rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
                                            int dy) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::RendererGone() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Destroy() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
  BackingStore* backing_store = widget_->GetBackingStore();

  if (backing_store) {
    GdkRectangle grect = {
      damage_rect.x(),
      damage_rect.y(),
      damage_rect.width(),
      damage_rect.height()
    };
    GdkWindow* window = view_->window;
    gdk_window_begin_paint_rect(window, &grect);

    skia::PlatformDeviceLinux &platdev =
        backing_store->canvas()->getTopPlatformDevice();
    skia::BitmapPlatformDeviceLinux* const bitdev =
        static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
    cairo_t* cairo_drawable = gdk_cairo_create(window);
    cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
    cairo_paint(cairo_drawable);
    cairo_destroy(cairo_drawable);

    gdk_window_end_paint(window);
  } else {
    NOTIMPLEMENTED();
  }
}

<|endoftext|>


<commit_before>#include "viewer/primitives/image.hh"

#include <GL/glew.h>

#include <cassert>

namespace viewer {

Image::Image(const cv::Mat& image, const double scale, double alpha) {
  to_update_ = true;
  alpha_ = alpha;
  width_m_ = scale;
  update_image(image);
}

Image::Image(const Eigen::MatrixXd& image, double scale, double alpha) {
  to_update_ = true;
  alpha_ = alpha;
  width_m_ = scale;
  update_image(image);
}

void Image::update_image(const Eigen::MatrixXd& image) {
  const std::lock_guard<std::mutex> lk(draw_mutex_);

  const Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic> image_as_uchar =
      (image * 255.0).cast<uint8_t>();
  cv::Mat new_image;
  cv::eigen2cv(image_as_uchar, new_image);
  cv::cvtColor(new_image, image_, cv::COLOR_GRAY2BGR);
  to_update_ = true;
}

void Image::update_image(const cv::Mat& image) {
  const std::lock_guard<std::mutex> lk(draw_mutex_);
  if (image.channels() == 1) {
    cv::cvtColor(image, image_, cv::COLOR_GRAY2BGR);
  } else if (image.channels() == 3) {
    image.copyTo(image_);
  } else {
    assert(false);
  }
  to_update_ = true;
}

void Image::update_gl() const {
  if (!allocated_texture_) {
    glGenTextures(1, &texture_id_);
    allocated_texture_ = true;
  }

  glBindTexture(GL_TEXTURE_2D, texture_id_);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image_.cols, image_.rows, 0, GL_BGR,
               GL_UNSIGNED_BYTE, image_.data);
}

void Image::draw() const {
  const std::lock_guard<std::mutex> lk(draw_mutex_);

  if (to_update_) {
    update_gl();
    to_update_ = false;
  }

  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, texture_id_);

  glColor4d(1.0, 1.0, 1.0, alpha_);
  glBegin(GL_QUADS);

  const double aspect_ratio = image_.cols / static_cast<double>(image_.rows);

  const double height = aspect_ratio * width_m_;

  glTexCoord2d(1, 0);
  glVertex3d(height, 0, 0);
  glTexCoord2d(1, 1);
  glVertex3d(height, width_m_, 0);
  glTexCoord2d(0, 1);
  glVertex3d(0, width_m_, 0);
  glTexCoord2d(0, 0);
  glVertex3d(0, 0, 0);

  glEnd();

  glDisable(GL_TEXTURE_2D);
}
}  // namespace viewer
<commit_msg>Unflip images in viewer<commit_after>#include "viewer/primitives/image.hh"

#include <GL/glew.h>

#include <cassert>

namespace viewer {

Image::Image(const cv::Mat& image, const double scale, double alpha) {
  to_update_ = true;
  alpha_ = alpha;
  width_m_ = scale;
  update_image(image);
}

Image::Image(const Eigen::MatrixXd& image, double scale, double alpha) {
  to_update_ = true;
  alpha_ = alpha;
  width_m_ = scale;
  update_image(image);
}

void Image::update_image(const Eigen::MatrixXd& image) {
  const std::lock_guard<std::mutex> lk(draw_mutex_);

  const Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic> image_as_uchar =
      (image * 255.0).cast<uint8_t>();
  cv::Mat new_image;
  cv::eigen2cv(image_as_uchar, new_image);
  cv::cvtColor(new_image, image_, cv::COLOR_GRAY2BGR);
  to_update_ = true;
}

void Image::update_image(const cv::Mat& image) {
  const std::lock_guard<std::mutex> lk(draw_mutex_);
  if (image.channels() == 1) {
    cv::Mat not_yet_flipped;
    cv::cvtColor(image, not_yet_flipped, cv::COLOR_GRAY2BGR);
    cv::flip(not_yet_flipped, image_, 0);
  } else if (image.channels() == 3) {
    cv::flip(image, image_, 0);
  } else {
    assert(false);
  }
  to_update_ = true;
}

void Image::update_gl() const {
  if (!allocated_texture_) {
    glGenTextures(1, &texture_id_);
    allocated_texture_ = true;
  }

  glBindTexture(GL_TEXTURE_2D, texture_id_);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image_.cols, image_.rows, 0, GL_BGR,
               GL_UNSIGNED_BYTE, image_.data);
}

void Image::draw() const {
  const std::lock_guard<std::mutex> lk(draw_mutex_);

  if (to_update_) {
    update_gl();
    to_update_ = false;
  }

  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, texture_id_);

  glColor4d(1.0, 1.0, 1.0, alpha_);
  glBegin(GL_QUADS);

  const double aspect_ratio = image_.cols / static_cast<double>(image_.rows);

  const double height = aspect_ratio * width_m_;

  glTexCoord2d(1, 0);
  glVertex3d(height, 0, 0);
  glTexCoord2d(1, 1);
  glVertex3d(height, width_m_, 0);
  glTexCoord2d(0, 1);
  glVertex3d(0, width_m_, 0);
  glTexCoord2d(0, 0);
  glVertex3d(0, 0, 0);

  glEnd();

  glDisable(GL_TEXTURE_2D);
}
}  // namespace viewer
<|endoftext|>


<commit_before>#include "agent.h"
#include "modules/echo.h"
#include "log.h"
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <boost/process.hpp>

#include <json/json.h>

#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validation_results.hpp>
#include <valijson/validator.hpp>

namespace puppetlabs {
namespace cthun {

void run_command(std::string exec, std::vector<std::string> args, std::string stdin, std::string &stdout, std::string &stderr) {
    boost::process::context context;
    context.stdout_behavior = boost::process::capture_stream();
    context.stderr_behavior = boost::process::capture_stream();

    boost::process::child child = boost::process::launch(exec, args, context);
    boost::process::status status = child.wait();

    boost::process::pistream &out = child.get_stdout();
    boost::process::pistream &err = child.get_stderr();

    std::string line;
    while (std::getline(out, line)) {
        stdout += line;
    }

    while (std::getline(err, line)) {
        stderr += line;
    }
}

Agent::Agent() {
    modules_["echo"] = std::unique_ptr<Module>(new Modules::Echo);

    // some common schema constants to reduce typing
    valijson::constraints::TypeConstraint json_type_object(valijson::constraints::TypeConstraint::kObject);
    valijson::constraints::TypeConstraint json_type_string(valijson::constraints::TypeConstraint::kString);
    valijson::constraints::TypeConstraint json_type_array(valijson::constraints::TypeConstraint::kArray);

    // action sub-schema
    valijson::Schema action_schema;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap action_properties;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap action_pattern_properties;
    valijson::constraints::RequiredConstraint::RequiredProperties action_required;

    action_schema.addConstraint(json_type_object);

    action_required.insert("name");
    action_properties["name"].addConstraint(json_type_string);

    action_required.insert("input");
    action_properties["input"].addConstraint(json_type_object);

    action_required.insert("output");
    action_properties["output"].addConstraint(json_type_object);

    // constrain the properties to just those in the metadata_properies map
    action_schema.addConstraint(new valijson::constraints::PropertiesConstraint(
                                    action_properties,
                                    action_pattern_properties));

    // specify the required properties
    action_schema.addConstraint(new valijson::constraints::RequiredConstraint(action_required));

    // the metadata schema
    valijson::Schema metadata_schema;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap metadata_properties;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap metadata_pattern_properties;
    valijson::constraints::RequiredConstraint::RequiredProperties metadata_required;

    metadata_schema.addConstraint(json_type_object);

    // description is required
    metadata_required.insert("description");
    metadata_properties["description"].addConstraint(json_type_string);

    // actions is an array of the action sub-schema
    metadata_required.insert("actions");
    metadata_properties["actions"].addConstraint(json_type_array);
    valijson::constraints::ItemsConstraint items_of_type_action_schema(action_schema);
    metadata_properties["actions"].addConstraint(items_of_type_action_schema);

    // constrain the properties to just those in the metadata_properies map
    metadata_schema.addConstraint(new valijson::constraints::PropertiesConstraint(
                                      metadata_properties,
                                      metadata_pattern_properties));

    // specify the required properties
    metadata_schema.addConstraint(new valijson::constraints::RequiredConstraint(metadata_required));

    boost::filesystem::path module_path { "modules" };
    boost::filesystem::directory_iterator end;
    for (auto file = boost::filesystem::directory_iterator(module_path); file != end; ++file) {
        if (!boost::filesystem::is_directory(file->status())) {
            BOOST_LOG_TRIVIAL(info) << file->path().filename().string();

            std::string metadata;
            std::string error;
            run_command(file->path().string(), { "metadata" }, "", metadata, error);

            Json::Value document;
            Json::Reader reader;
            if (!reader.parse(metadata, document)) {
                BOOST_LOG_TRIVIAL(error) << "Parse error: " << reader.getFormatedErrorMessages();
                continue;
            }

            valijson::Validator validator(metadata_schema);
            valijson::adapters::JsonCppAdapter adapted_document(document);
            valijson::ValidationResults validation_results;
            if (!validator.validate(adapted_document, &validation_results)) {
                BOOST_LOG_TRIVIAL(error) << "Failed validation";
                valijson::ValidationResults::Error error;
                while (validation_results.popError(error)) {
                    for (auto path : error.context) {
                        BOOST_LOG_TRIVIAL(error) << path;
                    }
                    BOOST_LOG_TRIVIAL(error) << error.description;
                }

                continue;
            }
            BOOST_LOG_TRIVIAL(info) << "validation OK";

            std::unique_ptr<Module> loading(new Module);
            loading->name = file->path().filename().string();
            const Json::Value actions = document["actions"];
            for (auto action : actions) {
                BOOST_LOG_TRIVIAL(info) << "declaring action " << action["name"].asString();
                valijson::Schema input_schema;
                valijson::Schema output_schema;

                valijson::SchemaParser parser;
                valijson::adapters::JsonCppAdapter input_doc_schema(action["input"]);
                valijson::adapters::JsonCppAdapter output_doc_schema(action["output"]);

                try {
                    parser.populateSchema(input_doc_schema, input_schema);
                } catch (...) {
                    BOOST_LOG_TRIVIAL(info) << "Failed to parse input schema.";
                    continue;
                }

                try {
                    parser.populateSchema(output_doc_schema, output_schema);
                } catch (...) {
                    BOOST_LOG_TRIVIAL(info) << "Failed to parse error schema.";
                    continue;
                }

                loading->actions[action["name"].asString()] = Action { input_schema, output_schema };
            }

            modules_[loading->name] = std::move(loading);
        }
    }
}

void Agent::run() {
}

}  // namespace cthun
}  // namespace puppetlabs
<commit_msg>make run_command std do a thing<commit_after>#include "agent.h"
#include "modules/echo.h"
#include "log.h"
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <boost/process.hpp>

#include <json/json.h>

#include <valijson/adapters/jsoncpp_adapter.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validation_results.hpp>
#include <valijson/validator.hpp>

namespace puppetlabs {
namespace cthun {

void run_command(std::string exec, std::vector<std::string> args, std::string stdin, std::string &stdout, std::string &stderr) {
    boost::process::context context;
    context.stdin_behavior = boost::process::capture_stream();
    context.stdout_behavior = boost::process::capture_stream();
    context.stderr_behavior = boost::process::capture_stream();

    boost::process::child child = boost::process::launch(exec, args, context);

    boost::process::postream &in = child.get_stdin();

    in << stdin;
    in.close();

    boost::process::pistream &out = child.get_stdout();
    std::string line;
    while (std::getline(out, line)) {
        stdout += line;
    }

    boost::process::pistream &err = child.get_stderr();
    while (std::getline(err, line)) {
        stderr += line;
    }

    boost::process::status status = child.wait();
}

Agent::Agent() {
    modules_["echo"] = std::unique_ptr<Module>(new Modules::Echo);

    // some common schema constants to reduce typing
    valijson::constraints::TypeConstraint json_type_object(valijson::constraints::TypeConstraint::kObject);
    valijson::constraints::TypeConstraint json_type_string(valijson::constraints::TypeConstraint::kString);
    valijson::constraints::TypeConstraint json_type_array(valijson::constraints::TypeConstraint::kArray);

    // action sub-schema
    valijson::Schema action_schema;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap action_properties;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap action_pattern_properties;
    valijson::constraints::RequiredConstraint::RequiredProperties action_required;

    action_schema.addConstraint(json_type_object);

    action_required.insert("name");
    action_properties["name"].addConstraint(json_type_string);

    action_required.insert("input");
    action_properties["input"].addConstraint(json_type_object);

    action_required.insert("output");
    action_properties["output"].addConstraint(json_type_object);

    // constrain the properties to just those in the metadata_properies map
    action_schema.addConstraint(new valijson::constraints::PropertiesConstraint(
                                    action_properties,
                                    action_pattern_properties));

    // specify the required properties
    action_schema.addConstraint(new valijson::constraints::RequiredConstraint(action_required));

    // the metadata schema
    valijson::Schema metadata_schema;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap metadata_properties;
    valijson::constraints::PropertiesConstraint::PropertySchemaMap metadata_pattern_properties;
    valijson::constraints::RequiredConstraint::RequiredProperties metadata_required;

    metadata_schema.addConstraint(json_type_object);

    // description is required
    metadata_required.insert("description");
    metadata_properties["description"].addConstraint(json_type_string);

    // actions is an array of the action sub-schema
    metadata_required.insert("actions");
    metadata_properties["actions"].addConstraint(json_type_array);
    valijson::constraints::ItemsConstraint items_of_type_action_schema(action_schema);
    metadata_properties["actions"].addConstraint(items_of_type_action_schema);

    // constrain the properties to just those in the metadata_properies map
    metadata_schema.addConstraint(new valijson::constraints::PropertiesConstraint(
                                      metadata_properties,
                                      metadata_pattern_properties));

    // specify the required properties
    metadata_schema.addConstraint(new valijson::constraints::RequiredConstraint(metadata_required));

    boost::filesystem::path module_path { "modules" };
    boost::filesystem::directory_iterator end;
    for (auto file = boost::filesystem::directory_iterator(module_path); file != end; ++file) {
        if (!boost::filesystem::is_directory(file->status())) {
            BOOST_LOG_TRIVIAL(info) << file->path().filename().string();

            std::string metadata;
            std::string error;
            run_command(file->path().string(), { "metadata" }, "", metadata, error);

            Json::Value document;
            Json::Reader reader;
            if (!reader.parse(metadata, document)) {
                BOOST_LOG_TRIVIAL(error) << "Parse error: " << reader.getFormatedErrorMessages();
                continue;
            }

            valijson::Validator validator(metadata_schema);
            valijson::adapters::JsonCppAdapter adapted_document(document);
            valijson::ValidationResults validation_results;
            if (!validator.validate(adapted_document, &validation_results)) {
                BOOST_LOG_TRIVIAL(error) << "Failed validation";
                valijson::ValidationResults::Error error;
                while (validation_results.popError(error)) {
                    for (auto path : error.context) {
                        BOOST_LOG_TRIVIAL(error) << path;
                    }
                    BOOST_LOG_TRIVIAL(error) << error.description;
                }

                continue;
            }
            BOOST_LOG_TRIVIAL(info) << "validation OK";

            std::unique_ptr<Module> loading(new Module);
            loading->name = file->path().filename().string();
            const Json::Value actions = document["actions"];
            for (auto action : actions) {
                BOOST_LOG_TRIVIAL(info) << "declaring action " << action["name"].asString();
                valijson::Schema input_schema;
                valijson::Schema output_schema;

                valijson::SchemaParser parser;
                valijson::adapters::JsonCppAdapter input_doc_schema(action["input"]);
                valijson::adapters::JsonCppAdapter output_doc_schema(action["output"]);

                try {
                    parser.populateSchema(input_doc_schema, input_schema);
                } catch (...) {
                    BOOST_LOG_TRIVIAL(info) << "Failed to parse input schema.";
                    continue;
                }

                try {
                    parser.populateSchema(output_doc_schema, output_schema);
                } catch (...) {
                    BOOST_LOG_TRIVIAL(info) << "Failed to parse error schema.";
                    continue;
                }

                loading->actions[action["name"].asString()] = Action { input_schema, output_schema };
            }

            modules_[loading->name] = std::move(loading);
        }
    }
}

void Agent::run() {
}

}  // namespace cthun
}  // namespace puppetlabs
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg, Daniel Wallin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/alert.hpp"
#include <boost/thread/xtime.hpp>

enum { queue_size_limit = 1000 };

namespace libtorrent {

	alert::alert() : m_timestamp(time_now()) {}
	alert::~alert() {}
	ptime alert::timestamp() const { return m_timestamp; }

	alert_manager::alert_manager()
		: m_alert_mask(alert::error_notification)
	{}

	alert_manager::~alert_manager()
	{
		while (!m_alerts.empty())
		{
			delete m_alerts.front();
			m_alerts.pop();
		}
	}

	alert const* alert_manager::wait_for_alert(time_duration max_wait)
	{
		boost::mutex::scoped_lock lock(m_mutex);

		if (!m_alerts.empty()) return m_alerts.front();

		int secs = total_seconds(max_wait);
		max_wait -= seconds(secs);
		boost::xtime xt;
		boost::xtime_get(&xt, boost::TIME_UTC);
		xt.sec += secs;
		boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000;
		if (nsec > 1000000000)
		{
			nsec -= 1000000000;
			xt.sec += 1;
		}
		xt.nsec = boost::xtime::xtime_nsec_t(nsec);
		if (!m_condition.timed_wait(lock, xt)) return 0;
		TORRENT_ASSERT(!m_alerts.empty());
		if (m_alerts.empty()) return 0;
		return m_alerts.front();
	}

	void alert_manager::post_alert(const alert& alert_)
	{
		boost::mutex::scoped_lock lock(m_mutex);

		if (m_alerts.size() >= queue_size_limit) return;
		m_alerts.push(alert_.clone().release());
		m_condition.notify_all();
	}

	std::auto_ptr<alert> alert_manager::get()
	{
		boost::mutex::scoped_lock lock(m_mutex);

		TORRENT_ASSERT(!m_alerts.empty());

		alert* result = m_alerts.front();
		m_alerts.pop();
		return std::auto_ptr<alert>(result);
	}

	bool alert_manager::pending() const
	{
		boost::mutex::scoped_lock lock(m_mutex);

		return !m_alerts.empty();
	}

} // namespace libtorrent

<commit_msg>removed invalid assert<commit_after>/*

Copyright (c) 2003, Arvid Norberg, Daniel Wallin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/alert.hpp"
#include <boost/thread/xtime.hpp>

enum { queue_size_limit = 1000 };

namespace libtorrent {

	alert::alert() : m_timestamp(time_now()) {}
	alert::~alert() {}
	ptime alert::timestamp() const { return m_timestamp; }

	alert_manager::alert_manager()
		: m_alert_mask(alert::error_notification)
	{}

	alert_manager::~alert_manager()
	{
		while (!m_alerts.empty())
		{
			delete m_alerts.front();
			m_alerts.pop();
		}
	}

	alert const* alert_manager::wait_for_alert(time_duration max_wait)
	{
		boost::mutex::scoped_lock lock(m_mutex);

		if (!m_alerts.empty()) return m_alerts.front();

		int secs = total_seconds(max_wait);
		max_wait -= seconds(secs);
		boost::xtime xt;
		boost::xtime_get(&xt, boost::TIME_UTC);
		xt.sec += secs;
		boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000;
		if (nsec > 1000000000)
		{
			nsec -= 1000000000;
			xt.sec += 1;
		}
		xt.nsec = boost::xtime::xtime_nsec_t(nsec);
		// apparently this call can be interrupted
		// prematurely if there are other signals
		if (!m_condition.timed_wait(lock, xt)) return 0;
		if (m_alerts.empty()) return 0;
		return m_alerts.front();
	}

	void alert_manager::post_alert(const alert& alert_)
	{
		boost::mutex::scoped_lock lock(m_mutex);

		if (m_alerts.size() >= queue_size_limit) return;
		m_alerts.push(alert_.clone().release());
		m_condition.notify_all();
	}

	std::auto_ptr<alert> alert_manager::get()
	{
		boost::mutex::scoped_lock lock(m_mutex);

		TORRENT_ASSERT(!m_alerts.empty());

		alert* result = m_alerts.front();
		m_alerts.pop();
		return std::auto_ptr<alert>(result);
	}

	bool alert_manager::pending() const
	{
		boost::mutex::scoped_lock lock(m_mutex);

		return !m_alerts.empty();
	}

} // namespace libtorrent

<|endoftext|>


<commit_before><commit_msg>Fix crash in window shutdown by accessing the Widget via a more unique property.<commit_after><|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <cassert>
#include "vvdebugmsg.h"
#include "vvibrimage.h"
#include "vvibr.h"

vvIbrImage::vvIbrImage(short h, short w, uchar* image, int dp)
: vvImage(h, w, image)
, _depthPrecision(dp)
, _depthCodeType(0)
, _codedDepthSize(0)
, _pixeldepth(NULL)
, _codeddepth(NULL)
, _viewport(0, 0, w, h)
{
  _projectionMatrix.identity();
  _modelViewMatrix.identity();
  _depthMin = _depthMax = 0.f;
}

vvIbrImage::vvIbrImage()
: vvImage()
, _depthPrecision(0)
, _depthCodeType(0)
, _codedDepthSize(0)
, _pixeldepth(NULL)
, _codeddepth(NULL)
, _viewport(0, 0, 0, 0)
{
  _projectionMatrix.identity();
  _modelViewMatrix.identity();
  _depthMin = _depthMax = 0.f;
}

vvIbrImage::~vvIbrImage()
{
  if(t == VV_CLIENT)
    delete[] _pixeldepth;
  delete[] _codeddepth;
}

uchar* vvIbrImage::getPixelDepth() const
{
  return _pixeldepth;
}

uchar *vvIbrImage::getCodedDepth() const
{
  if(_depthCodeType == 0)
    return _pixeldepth;
  else
    return _codeddepth;
}

int vvIbrImage::getDepthCodetype() const
{
  return _depthCodeType;
}

void vvIbrImage::setDepthCodetype(int ct)
{
  _depthCodeType = ct;
}

//----------------------------------------------------------------------------
/** Allocates momory for a new image and 2.5d-data
 */
void vvIbrImage::alloc_pd()
{
  if(t == VV_CLIENT)
  {
    delete[] _pixeldepth;
    _pixeldepth = new uchar[width*height*_depthPrecision/8];
  }

  delete[] _codeddepth;
  _codeddepth = new uchar[width*height*_depthPrecision/8];
}

int vvIbrImage::getDepthPrecision() const
{
  return _depthPrecision;
}

int vvIbrImage::getDepthSize() const
{
  switch(_depthCodeType)
  {
  case 0:
    return width*height*(_depthPrecision/8);
  default:
    return _codedDepthSize;
  }
}

void vvIbrImage::setDepthPrecision(int dp)
{
  assert(dp==8 || dp==16 || dp==32);
  _depthPrecision = dp;
  if(t == VV_CLIENT)
  {
    delete[] _pixeldepth;
    _pixeldepth = NULL;
  }
}

void vvIbrImage::setNewDepthPtr(uchar *depth)
{
  _pixeldepth = depth;
  _depthCodeType = 0;
  _codedDepthSize = 0;
}

void vvIbrImage::setDepthSize(int size)
{
  _codedDepthSize = size;
}

void vvIbrImage::setModelViewMatrix(const vvMatrix &mv)
{
  _modelViewMatrix = mv;
}

vvMatrix vvIbrImage::getModelViewMatrix() const
{
  return _modelViewMatrix;
}

void vvIbrImage::setProjectionMatrix(const vvMatrix &pm)
{
  _projectionMatrix = pm;
}

vvMatrix vvIbrImage::getProjectionMatrix() const
{
  return _projectionMatrix;
}

void vvIbrImage::setDepthRange(const float dmin, const float dmax)
{
  _depthMin = dmin;
  _depthMax = dmax;
}

void vvIbrImage::getDepthRange(float *dmin, float *dmax) const
{
  *dmin = _depthMin;
  *dmax = _depthMax;
}

void vvIbrImage::setViewport(const vvGLTools::Viewport &vp)
{
  _viewport = vp;
}

vvGLTools::Viewport vvIbrImage::getViewport() const
{
  return _viewport;
}

vvMatrix vvIbrImage::getReprojectionMatrix() const
{
  return vvIbr::calcImgMatrix(_projectionMatrix, _modelViewMatrix, _viewport, _depthMin, _depthMax);
}

int vvIbrImage::encode(short ct, short sh, short eh, short sw, short ew)
{
  vvDebugMsg::msg(3, "vvIbrImage::encode: depth code type is ", ct);
  int err = vvImage::encode(ct, sh, eh, sw, ew);

  float cr = 1.f;
  switch(ct)
  {
  case 0:
    cr=1.f;
    _depthCodeType = 0;
    break;
  default:
    _codedDepthSize = gen_RLC_encode(_pixeldepth, _codeddepth, width*height, _depthPrecision/8, width*height*(_depthPrecision/8));
    if(_codedDepthSize < 0)
    {
      cr = 1.f;
      _depthCodeType = 0;
    }
    else
    {
      cr = (float)_codedDepthSize/width/height/(_depthPrecision/8);
      _depthCodeType = 1;
    }
    break;
  }

  vvDebugMsg::msg(3, "vvIbrImage::encode: depth compression ratio is ", cr);

  return err;
}

int vvIbrImage::decode()
{
  vvDebugMsg::msg(3, "vvIbrImage::decode: depth code type is ", _depthCodeType);
  int err = vvImage::decode();
  if(err)
    return err;

  switch(_depthCodeType)
  {
  case 0:
    break;
  default:
    err = gen_RLC_decode(_codeddepth, _pixeldepth, _codedDepthSize, _depthPrecision/8, width*height*(_depthPrecision/8));
    if(!err)
    {
      vvDebugMsg::msg(3, "vvIbrImage::decode: success, compressed size was ", _codedDepthSize);
      _depthCodeType = 0;
      _codedDepthSize = 0;
    }
    else
    {
      vvDebugMsg::msg(1, "vvIbrImage::decode: failed to decode depth");
    }
    break;
  }

  return err;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>encode whole depth image also for higher depth precision<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <cassert>
#include "vvdebugmsg.h"
#include "vvibrimage.h"
#include "vvibr.h"

vvIbrImage::vvIbrImage(short h, short w, uchar* image, int dp)
: vvImage(h, w, image)
, _depthPrecision(dp)
, _depthCodeType(0)
, _codedDepthSize(0)
, _pixeldepth(NULL)
, _codeddepth(NULL)
, _viewport(0, 0, w, h)
{
  _projectionMatrix.identity();
  _modelViewMatrix.identity();
  _depthMin = _depthMax = 0.f;
}

vvIbrImage::vvIbrImage()
: vvImage()
, _depthPrecision(0)
, _depthCodeType(0)
, _codedDepthSize(0)
, _pixeldepth(NULL)
, _codeddepth(NULL)
, _viewport(0, 0, 0, 0)
{
  _projectionMatrix.identity();
  _modelViewMatrix.identity();
  _depthMin = _depthMax = 0.f;
}

vvIbrImage::~vvIbrImage()
{
  if(t == VV_CLIENT)
    delete[] _pixeldepth;
  delete[] _codeddepth;
}

uchar* vvIbrImage::getPixelDepth() const
{
  return _pixeldepth;
}

uchar *vvIbrImage::getCodedDepth() const
{
  if(_depthCodeType == 0)
    return _pixeldepth;
  else
    return _codeddepth;
}

int vvIbrImage::getDepthCodetype() const
{
  return _depthCodeType;
}

void vvIbrImage::setDepthCodetype(int ct)
{
  _depthCodeType = ct;
}

//----------------------------------------------------------------------------
/** Allocates momory for a new image and 2.5d-data
 */
void vvIbrImage::alloc_pd()
{
  if(t == VV_CLIENT)
  {
    delete[] _pixeldepth;
    _pixeldepth = new uchar[width*height*_depthPrecision/8];
  }

  delete[] _codeddepth;
  _codeddepth = new uchar[width*height*_depthPrecision/8];
}

int vvIbrImage::getDepthPrecision() const
{
  return _depthPrecision;
}

int vvIbrImage::getDepthSize() const
{
  switch(_depthCodeType)
  {
  case 0:
    return width*height*(_depthPrecision/8);
  default:
    return _codedDepthSize;
  }
}

void vvIbrImage::setDepthPrecision(int dp)
{
  assert(dp==8 || dp==16 || dp==32);
  _depthPrecision = dp;
  if(t == VV_CLIENT)
  {
    delete[] _pixeldepth;
    _pixeldepth = NULL;
  }
}

void vvIbrImage::setNewDepthPtr(uchar *depth)
{
  _pixeldepth = depth;
  _depthCodeType = 0;
  _codedDepthSize = 0;
}

void vvIbrImage::setDepthSize(int size)
{
  _codedDepthSize = size;
}

void vvIbrImage::setModelViewMatrix(const vvMatrix &mv)
{
  _modelViewMatrix = mv;
}

vvMatrix vvIbrImage::getModelViewMatrix() const
{
  return _modelViewMatrix;
}

void vvIbrImage::setProjectionMatrix(const vvMatrix &pm)
{
  _projectionMatrix = pm;
}

vvMatrix vvIbrImage::getProjectionMatrix() const
{
  return _projectionMatrix;
}

void vvIbrImage::setDepthRange(const float dmin, const float dmax)
{
  _depthMin = dmin;
  _depthMax = dmax;
}

void vvIbrImage::getDepthRange(float *dmin, float *dmax) const
{
  *dmin = _depthMin;
  *dmax = _depthMax;
}

void vvIbrImage::setViewport(const vvGLTools::Viewport &vp)
{
  _viewport = vp;
}

vvGLTools::Viewport vvIbrImage::getViewport() const
{
  return _viewport;
}

vvMatrix vvIbrImage::getReprojectionMatrix() const
{
  return vvIbr::calcImgMatrix(_projectionMatrix, _modelViewMatrix, _viewport, _depthMin, _depthMax);
}

int vvIbrImage::encode(short ct, short sh, short eh, short sw, short ew)
{
  vvDebugMsg::msg(3, "vvIbrImage::encode: depth code type is ", ct);
  int err = vvImage::encode(ct, sh, eh, sw, ew);

  float cr = 1.f;
  switch(ct)
  {
  case 0:
    cr=1.f;
    _depthCodeType = 0;
    break;
  default:
    _codedDepthSize = gen_RLC_encode(_pixeldepth, _codeddepth, width*height*(_depthPrecision/8), _depthPrecision/8, width*height*(_depthPrecision/8));
    if(_codedDepthSize < 0)
    {
      cr = 1.f;
      _depthCodeType = 0;
    }
    else
    {
      cr = (float)_codedDepthSize/width/height/(_depthPrecision/8);
      _depthCodeType = 1;
    }
    break;
  }

  vvDebugMsg::msg(3, "vvIbrImage::encode: depth compression ratio is ", cr);

  return err;
}

int vvIbrImage::decode()
{
  vvDebugMsg::msg(3, "vvIbrImage::decode: depth code type is ", _depthCodeType);
  int err = vvImage::decode();
  if(err)
    return err;

  switch(_depthCodeType)
  {
  case 0:
    break;
  default:
    err = gen_RLC_decode(_codeddepth, _pixeldepth, _codedDepthSize, _depthPrecision/8, width*height*(_depthPrecision/8));
    if(!err)
    {
      vvDebugMsg::msg(3, "vvIbrImage::decode: success, compressed size was ", _codedDepthSize);
      _depthCodeType = 0;
      _codedDepthSize = 0;
    }
    else
    {
      vvDebugMsg::msg(1, "vvIbrImage::decode: failed to decode depth");
    }
    break;
  }

  return err;
}
// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|>


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

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "SaveDataReaction.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMProxyIterator.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ModuleManager::instance(), SIGNAL(dataSourceAdded(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ModuleManager::instance(), SIGNAL(moduleAdded(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    if (currentIndex().isValid()) {
      deleteItem(currentIndex());
    }
  } else {
    QTreeView::keyPressEvent(e);
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  QAction* saveDataAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    saveDataAction = contextMenu.addAction("Save Data");
    new SaveDataReaction(saveDataAction);
    if (dataSource->type() == DataSource::Volume) {
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  auto deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  auto selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    auto mainWindow = qobject_cast<QMainWindow*>(window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 1) {
    auto pipelineModel = qobject_cast<PipelineModel*>(model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();

      // If the view is not a SpreadSheetView, look for the first one and
      // use it if possible.
      vtkNew<vtkSMProxyIterator> iter;
      iter->SetSessionProxyManager(ActiveObjects::instance().proxyManager());
      iter->SetModeToOneGroup();
      for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) {
        auto viewProxy = vtkSMViewProxy::SafeDownCast(iter->GetProxy());
        if (std::string(viewProxy->GetXMLName()) == "SpreadSheetView") {
          view = viewProxy;
          break;
        }
      }

      // If a spreadsheet view wasn't found, controller->ShowInPreferredView()
      // will create one.
      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
      view = controller->ShowInPreferredView(result->producerProxy(), 0, view);
      ActiveObjects::instance().setActiveView(view);
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);

  if (auto dataSource = pipelineModel->dataSource(current)) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (auto module = pipelineModel->module(current)) {
    ActiveObjects::instance().setActiveModule(module);
  } else if (auto op = pipelineModel->op(current)) {
    ActiveObjects::instance().setActiveOperator(op);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<commit_msg>Fix column index<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "SaveDataReaction.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMProxyIterator.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ModuleManager::instance(), SIGNAL(dataSourceAdded(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ModuleManager::instance(), SIGNAL(moduleAdded(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    if (currentIndex().isValid()) {
      deleteItem(currentIndex());
    }
  } else {
    QTreeView::keyPressEvent(e);
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  QAction* saveDataAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    saveDataAction = contextMenu.addAction("Save Data");
    new SaveDataReaction(saveDataAction);
    if (dataSource->type() == DataSource::Volume) {
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  auto deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  auto selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    auto mainWindow = qobject_cast<QMainWindow*>(window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 2) {
    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();

      // If the view is not a SpreadSheetView, look for the first one and
      // use it if possible.
      vtkNew<vtkSMProxyIterator> iter;
      iter->SetSessionProxyManager(ActiveObjects::instance().proxyManager());
      iter->SetModeToOneGroup();
      for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) {
        auto viewProxy = vtkSMViewProxy::SafeDownCast(iter->GetProxy());
        if (std::string(viewProxy->GetXMLName()) == "SpreadSheetView") {
          view = viewProxy;
          break;
        }
      }

      // If a spreadsheet view wasn't found, controller->ShowInPreferredView()
      // will create one.
      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
      view = controller->ShowInPreferredView(result->producerProxy(), 0, view);
      ActiveObjects::instance().setActiveView(view);
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);

  if (auto dataSource = pipelineModel->dataSource(current)) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (auto module = pipelineModel->module(current)) {
    ActiveObjects::instance().setActiveModule(module);
  } else if (auto op = pipelineModel->op(current)) {
    ActiveObjects::instance().setActiveOperator(op);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<|endoftext|>


<commit_before>#include "mainwindow.hh"
#include <QApplication>
#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

int main(int argc, char *argv[])
{
    easyloggingpp::Loggers::setApplicationArguments(argc, argv);

    // Configure all loggers
    easyloggingpp::Configurations viewerConf("../LogViewer/log.conf");
    easyloggingpp::Loggers::reconfigureAllLoggers(viewerConf);

    LTRACE << "Starting LogViewer";

    easyloggingpp::Loggers::setFilename("/tmp/logs/tmp.log");
    LINFO << "This";
    easyloggingpp::Loggers::setFilename(easyloggingpp::Loggers::trivialLogger(), "/tmp/logs/tmptr.log");
    LINFO << "This 2";

    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
}
<commit_msg>reset back the main<commit_after>#include "mainwindow.hh"
#include <QApplication>
#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

int main(int argc, char *argv[])
{
    easyloggingpp::Loggers::setApplicationArguments(argc, argv);

    // Configure all loggers
    easyloggingpp::Configurations viewerConf("../LogViewer/log.conf");
    easyloggingpp::Loggers::reconfigureAllLoggers(viewerConf);

    LTRACE << "Starting LogViewer";

    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
}
<|endoftext|>


<commit_before>#include "core/connection.hpp"

// boost
#include <boost/test/unit_test.hpp>

/**
 * Example test cases for core connections.
 * These this test shows how connections are used in general.
 * Tests for special cases are below.
 */
BOOST_AUTO_TEST_CASE(examples)
{
	//test trivial connection of two objects
	auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter
	auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter

	// this connection has no parameter and returns and int.
	auto one_plus_one = connect(give_one, increment);
	BOOST_CHECK(one_plus_one() == 2);

	//test chained connection,
	//take connection from above and add a new connectable as a sink.
	auto two_plus_one = connect(one_plus_one, increment);
	BOOST_CHECK(two_plus_one() == 3);

	//connections can have both, parameters and return values:
	{
		// connection of two anonymous nodes, takes and returns an int.
		auto plus_two = connect
			(
				[](int i) ->int {return i+1;},
				[](int i) ->int {return i+1;}
			);
		BOOST_CHECK(plus_two(1) == 3);
	}
	//this is completely equivalent to:
	{
		auto plus_two = connect(increment, increment);
		BOOST_CHECK(plus_two(1) == 3);
	}
}

BOOST_AUTO_TEST_CASE(stream_operator_example)
{
	auto make_four = [](){return 1;} // one
			>> [](int i){return ++i;} // plus one
			>> [](int i){return i+2;}; // plus two
	BOOST_CHECK_EQUAL(make_four(), 4); // is four
}

BOOST_AUTO_TEST_CASE(test_fork)
{
	struct foo
	{
		bool operator()() {return true;}
	};

	struct bar
	{
		bool operator()(bool a) {return !a;}
	};
	//auto dummy_fork = fork([](){return 1;}, [](int i){return i++;});
	auto test = fork(foo(), bar());
	BOOST_CHECK(test() == false);

}

// test cases for different pairs of parameter and result types
BOOST_AUTO_TEST_CASE(parameter_result_pairs)
{
	// this variable is captures by lambdas
	// to check if lambdas without return values work.
	int capture_ref = 0;

	//named differnt sources and sinks to make tests more readable
	auto write_param = [&](int i){ capture_ref = i; };
	auto increment = [](int i) -> int {return i+1;};
	auto give_one = [](){return 1;};
	auto give_three = [](){return 3;};
	auto do_nothing = [](){};
	auto ignore_in = [](int i){};
	auto increment_ref = [&](){ capture_ref++; };

	// param int,  payload int,  result int
	auto plus_two = connect(increment, increment);
	BOOST_CHECK_EQUAL(plus_two(1), 3);

	// param int,  payload int,  result void
	// this connection takes a parameter and returns void
	// An int is transmitted as payload between source and sink.
	auto write_increment = connect(increment, write_param);
	write_increment(0);
	BOOST_CHECK_EQUAL(capture_ref,1);

	// param int,  payload void, result int
	auto ignore_input_return1 = connect(ignore_in, give_one);
	BOOST_CHECK_EQUAL(ignore_input_return1(99), 1);

	// param int,  payload void, result void
	connect(ignore_in, increment_ref)(99);
	BOOST_CHECK_EQUAL(capture_ref, 2);

	// param void, payload int,  result int
	// This connection takes no paramter and returns an int.
	// An int is transmitted as payload between source and sink.
	BOOST_CHECK_EQUAL(connect(give_one, increment)(), 2);

	// param void, payload int,  result void
	connect(give_three, write_param)();
	BOOST_CHECK_EQUAL(capture_ref, 3);

	// param void, payload void, result int
	// This connection takes no paramter and returns and int.
	// There is also no payload between source and sink.
	BOOST_CHECK_EQUAL(connect(do_nothing, give_one)(),1);

	// param void, payload void, result void
	// This connection takes no parameter, and returns void
	// There is also no payload between source and sink.
	connect(do_nothing, increment_ref)();
	BOOST_CHECK_EQUAL(capture_ref, 4);
}
<commit_msg>deleted dead code in TestConnection<commit_after>#include "core/connection.hpp"

// boost
#include <boost/test/unit_test.hpp>

/**
 * Example test cases for core connections.
 * These this test shows how connections are used in general.
 * Tests for special cases are below.
 */
BOOST_AUTO_TEST_CASE(examples)
{
	//test trivial connection of two objects
	auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter
	auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter

	// this connection has no parameter and returns and int.
	auto one_plus_one = connect(give_one, increment);
	BOOST_CHECK(one_plus_one() == 2);

	//test chained connection,
	//take connection from above and add a new connectable as a sink.
	auto two_plus_one = connect(one_plus_one, increment);
	BOOST_CHECK(two_plus_one() == 3);

	//connections can have both, parameters and return values:
	{
		// connection of two anonymous nodes, takes and returns an int.
		auto plus_two = connect
			(
				[](int i) ->int {return i+1;},
				[](int i) ->int {return i+1;}
			);
		BOOST_CHECK(plus_two(1) == 3);
	}
	//this is completely equivalent to:
	{
		auto plus_two = connect(increment, increment);
		BOOST_CHECK(plus_two(1) == 3);
	}
}

BOOST_AUTO_TEST_CASE(stream_operator_example)
{
	auto make_four = [](){return 1;} // one
			>> [](int i){return ++i;} // plus one
			>> [](int i){return i+2;}; // plus two
	BOOST_CHECK_EQUAL(make_four(), 4); // is four
}

// test cases for different pairs of parameter and result types
BOOST_AUTO_TEST_CASE(parameter_result_pairs)
{
	// this variable is captures by lambdas
	// to check if lambdas without return values work.
	int capture_ref = 0;

	//named differnt sources and sinks to make tests more readable
	auto write_param = [&](int i){ capture_ref = i; };
	auto increment = [](int i) -> int {return i+1;};
	auto give_one = [](){return 1;};
	auto give_three = [](){return 3;};
	auto do_nothing = [](){};
	auto ignore_in = [](int i){};
	auto increment_ref = [&](){ capture_ref++; };

	// param int,  payload int,  result int
	auto plus_two = connect(increment, increment);
	BOOST_CHECK_EQUAL(plus_two(1), 3);

	// param int,  payload int,  result void
	// this connection takes a parameter and returns void
	// An int is transmitted as payload between source and sink.
	auto write_increment = connect(increment, write_param);
	write_increment(0);
	BOOST_CHECK_EQUAL(capture_ref,1);

	// param int,  payload void, result int
	auto ignore_input_return1 = connect(ignore_in, give_one);
	BOOST_CHECK_EQUAL(ignore_input_return1(99), 1);

	// param int,  payload void, result void
	connect(ignore_in, increment_ref)(99);
	BOOST_CHECK_EQUAL(capture_ref, 2);

	// param void, payload int,  result int
	// This connection takes no paramter and returns an int.
	// An int is transmitted as payload between source and sink.
	BOOST_CHECK_EQUAL(connect(give_one, increment)(), 2);

	// param void, payload int,  result void
	connect(give_three, write_param)();
	BOOST_CHECK_EQUAL(capture_ref, 3);

	// param void, payload void, result int
	// This connection takes no paramter and returns and int.
	// There is also no payload between source and sink.
	BOOST_CHECK_EQUAL(connect(do_nothing, give_one)(),1);

	// param void, payload void, result void
	// This connection takes no parameter, and returns void
	// There is also no payload between source and sink.
	connect(do_nothing, increment_ref)();
	BOOST_CHECK_EQUAL(capture_ref, 4);
}<|endoftext|>