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

#include "chrome/browser/ui/views/extensions/extension_popup.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/gfx/insets.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"

#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/views/corewm/window_animations.h"
#endif

using content::RenderViewHost;
using content::WebContents;

namespace {

// Returns true if |possible_parent| is a parent window of |child|.
bool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) {
  if (!child)
    return false;
#if !defined(USE_AURA) && defined(OS_WIN)
  if (::GetWindow(child, GW_OWNER) == possible_parent)
    return true;
#endif
  gfx::NativeView parent = child;
  while ((parent = platform_util::GetParent(parent))) {
    if (possible_parent == parent)
      return true;
  }

  return false;
}

}  // namespace

// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ExtensionPopup::kMinWidth = 25;
const int ExtensionPopup::kMinHeight = 25;
const int ExtensionPopup::kMaxWidth = 800;
const int ExtensionPopup::kMaxHeight = 600;

ExtensionPopup::ExtensionPopup(
    Browser* browser,
    extensions::ExtensionHost* host,
    views::View* anchor_view,
    views::BubbleBorder::ArrowLocation arrow_location,
    ShowAction show_action)
    : BubbleDelegateView(anchor_view, arrow_location),
      extension_host_(host),
      close_bubble_factory_(this) {
  inspect_with_devtools_ = show_action == SHOW_AND_INSPECT;
  // Adjust the margin so that contents fit better.
  const int margin = views::BubbleBorder::GetCornerRadius() / 2;
  set_margins(gfx::Insets(margin, margin, margin, margin));
  SetLayoutManager(new views::FillLayout());
  AddChildView(host->view());
  host->view()->SetContainer(this);
  // Use OnNativeFocusChange to check for child window activation on deactivate.
  set_close_on_deactivate(false);
  // Make the bubble move with its anchor (during inspection, etc.).
  set_move_with_anchor(true);

  // Wait to show the popup until the contained host finishes loading.
  registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
                 content::Source<WebContents>(host->host_contents()));

  // Listen for the containing view calling window.close();
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
                 content::Source<Profile>(host->profile()));

  // Listen for the dev tools opening on this popup, so we can stop it going
  // away when the dev tools get focus.
  registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED,
                 content::Source<Profile>(host->profile()));

  // Listen for the dev tools closing, so we can close this window if it is
  // being inspected and the inspector is closed.
  registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED,
      content::Source<content::BrowserContext>(host->profile()));
}

ExtensionPopup::~ExtensionPopup() {
  views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);
}

void ExtensionPopup::Observe(int type,
                             const content::NotificationSource& source,
                             const content::NotificationDetails& details) {
  switch (type) {
    case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:
      DCHECK(content::Source<WebContents>(host()->host_contents()) == source);
      // Show when the content finishes loading and its width is computed.
      ShowBubble();
      break;
    case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
      // If we aren't the host of the popup, then disregard the notification.
      if (content::Details<extensions::ExtensionHost>(host()) == details)
        GetWidget()->Close();
      break;
    case content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED:
      // Make sure it's the devtools window that inspecting our popup.
      // Widget::Close posts a task, which should give the devtools window a
      // chance to finish detaching from the inspected RenderViewHost.
      if (content::Details<RenderViewHost>(host()->render_view_host()) ==
          details) {
        GetWidget()->Close();
      }
      break;
    case content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED:
      // First check that the devtools are being opened on this popup.
      if (content::Details<RenderViewHost>(host()->render_view_host()) ==
          details) {
        // Set inspect_with_devtools_ so the popup will be kept open while
        // the devtools are open.
        inspect_with_devtools_ = true;
      }
      break;
    default:
      NOTREACHED() << L"Received unexpected notification";
  }
}

void ExtensionPopup::OnExtensionSizeChanged(ExtensionViewViews* view) {
  SizeToContents();
}

gfx::Size ExtensionPopup::GetPreferredSize() {
  // Constrain the size to popup min/max.
  gfx::Size sz = views::View::GetPreferredSize();
  sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));
  sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
  return sz;
}

void ExtensionPopup::OnNativeFocusChange(gfx::NativeView focused_before,
                                         gfx::NativeView focused_now) {
  // Don't close if a child of this window is activated (only needed on Win).
  // ExtensionPopups can create Javascipt dialogs; see crbug.com/106723.
  gfx::NativeView this_window = GetWidget()->GetNativeView();
  if (inspect_with_devtools_ || focused_now == this_window ||
      IsParent(focused_now, this_window))
    return;
  // Delay closing the widget because on Aura, closing right away makes the
  // activation controller trigger another focus change before the current focus
  // change is complete.
  if (!close_bubble_factory_.HasWeakPtrs()) {
    MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&ExtensionPopup::CloseBubble,
                   close_bubble_factory_.GetWeakPtr()));
  }
}

// static
ExtensionPopup* ExtensionPopup::ShowPopup(
    const GURL& url,
    Browser* browser,
    views::View* anchor_view,
    views::BubbleBorder::ArrowLocation arrow_location,
    ShowAction show_action) {
  ExtensionProcessManager* manager =
      extensions::ExtensionSystem::Get(browser->profile())->process_manager();
  extensions::ExtensionHost* host = manager->CreatePopupHost(url, browser);
  ExtensionPopup* popup = new ExtensionPopup(browser, host, anchor_view,
      arrow_location, show_action);
  views::BubbleDelegateView::CreateBubble(popup);

#if defined(USE_AURA)
  gfx::NativeView native_view = popup->GetWidget()->GetNativeView();
  views::corewm::SetWindowVisibilityAnimationType(
      native_view,
      views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL);
  views::corewm::SetWindowVisibilityAnimationVerticalPosition(
      native_view,
      -3.0f);
#endif

  // If the host had somehow finished loading, then we'd miss the notification
  // and not show.  This seems to happen in single-process mode.
  if (host->did_stop_loading())
    popup->ShowBubble();

  return popup;
}

void ExtensionPopup::ShowBubble() {
  Show();

  // Request focus for the View. Without this, the FocusManager gets confused.
  host()->view()->SetVisible(true);
  host()->view()->RequestFocus();

  // Focus on the host contents when the bubble is first shown.
  host()->host_contents()->GetView()->Focus();

  // Listen for widget focus changes after showing (used for non-aura win).
  views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);

  if (inspect_with_devtools_) {
    DevToolsWindow::ToggleDevToolsWindow(host()->render_view_host(),
        true,
        DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE);
  }
}

void ExtensionPopup::CloseBubble() {
  GetWidget()->Close();
}
<commit_msg>Revert 173932 "Fix bug where extension popups would not properly..." It breaks popup sizing with threaded compositing enabled.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/extensions/extension_popup.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/gfx/insets.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"

#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/views/corewm/window_animations.h"
#endif

using content::RenderViewHost;
using content::WebContents;

namespace {

// Returns true if |possible_parent| is a parent window of |child|.
bool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) {
  if (!child)
    return false;
#if !defined(USE_AURA) && defined(OS_WIN)
  if (::GetWindow(child, GW_OWNER) == possible_parent)
    return true;
#endif
  gfx::NativeView parent = child;
  while ((parent = platform_util::GetParent(parent))) {
    if (possible_parent == parent)
      return true;
  }

  return false;
}

}  // namespace

// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ExtensionPopup::kMinWidth = 25;
const int ExtensionPopup::kMinHeight = 25;
const int ExtensionPopup::kMaxWidth = 800;
const int ExtensionPopup::kMaxHeight = 600;

ExtensionPopup::ExtensionPopup(
    Browser* browser,
    extensions::ExtensionHost* host,
    views::View* anchor_view,
    views::BubbleBorder::ArrowLocation arrow_location,
    ShowAction show_action)
    : BubbleDelegateView(anchor_view, arrow_location),
      extension_host_(host),
      close_bubble_factory_(this) {
  inspect_with_devtools_ = show_action == SHOW_AND_INSPECT;
  // Adjust the margin so that contents fit better.
  const int margin = views::BubbleBorder::GetCornerRadius() / 2;
  set_margins(gfx::Insets(margin, margin, margin, margin));
  SetLayoutManager(new views::FillLayout());
  AddChildView(host->view());
  host->view()->SetContainer(this);
  // Use OnNativeFocusChange to check for child window activation on deactivate.
  set_close_on_deactivate(false);
  // Make the bubble move with its anchor (during inspection, etc.).
  set_move_with_anchor(true);

  // Wait to show the popup until the contained host finishes loading.
  registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
                 content::Source<WebContents>(host->host_contents()));

  // Listen for the containing view calling window.close();
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
                 content::Source<Profile>(host->profile()));

  // Listen for the dev tools opening on this popup, so we can stop it going
  // away when the dev tools get focus.
  registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED,
                 content::Source<Profile>(host->profile()));

  // Listen for the dev tools closing, so we can close this window if it is
  // being inspected and the inspector is closed.
  registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED,
      content::Source<content::BrowserContext>(host->profile()));
}

ExtensionPopup::~ExtensionPopup() {
  views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);
}

void ExtensionPopup::Observe(int type,
                             const content::NotificationSource& source,
                             const content::NotificationDetails& details) {
  switch (type) {
    case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:
      DCHECK(content::Source<WebContents>(host()->host_contents()) == source);
      // Show when the content finishes loading and its width is computed.
      ShowBubble();
      break;
    case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:
      // If we aren't the host of the popup, then disregard the notification.
      if (content::Details<extensions::ExtensionHost>(host()) == details)
        GetWidget()->Close();
      break;
    case content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED:
      // Make sure it's the devtools window that inspecting our popup.
      // Widget::Close posts a task, which should give the devtools window a
      // chance to finish detaching from the inspected RenderViewHost.
      if (content::Details<RenderViewHost>(host()->render_view_host()) ==
          details) {
        GetWidget()->Close();
      }
      break;
    case content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED:
      // First check that the devtools are being opened on this popup.
      if (content::Details<RenderViewHost>(host()->render_view_host()) ==
          details) {
        // Set inspect_with_devtools_ so the popup will be kept open while
        // the devtools are open.
        inspect_with_devtools_ = true;
      }
      break;
    default:
      NOTREACHED() << L"Received unexpected notification";
  }
}

void ExtensionPopup::OnExtensionSizeChanged(ExtensionViewViews* view) {
  SizeToContents();
}

gfx::Size ExtensionPopup::GetPreferredSize() {
  // Constrain the size to popup min/max.
  gfx::Size sz = views::View::GetPreferredSize();
  sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));
  sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
  return sz;
}

void ExtensionPopup::OnNativeFocusChange(gfx::NativeView focused_before,
                                         gfx::NativeView focused_now) {
  // Don't close if a child of this window is activated (only needed on Win).
  // ExtensionPopups can create Javascipt dialogs; see crbug.com/106723.
  gfx::NativeView this_window = GetWidget()->GetNativeView();
  if (inspect_with_devtools_ || focused_now == this_window ||
      IsParent(focused_now, this_window))
    return;
  // Delay closing the widget because on Aura, closing right away makes the
  // activation controller trigger another focus change before the current focus
  // change is complete.
  if (!close_bubble_factory_.HasWeakPtrs()) {
    MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&ExtensionPopup::CloseBubble,
                   close_bubble_factory_.GetWeakPtr()));
  }
}

// static
ExtensionPopup* ExtensionPopup::ShowPopup(
    const GURL& url,
    Browser* browser,
    views::View* anchor_view,
    views::BubbleBorder::ArrowLocation arrow_location,
    ShowAction show_action) {
  ExtensionProcessManager* manager =
      extensions::ExtensionSystem::Get(browser->profile())->process_manager();
  extensions::ExtensionHost* host = manager->CreatePopupHost(url, browser);
  ExtensionPopup* popup = new ExtensionPopup(browser, host, anchor_view,
      arrow_location, show_action);
  views::BubbleDelegateView::CreateBubble(popup);

#if defined(USE_AURA)
  gfx::NativeView native_view = popup->GetWidget()->GetNativeView();
  views::corewm::SetWindowVisibilityAnimationType(
      native_view,
      views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL);
  views::corewm::SetWindowVisibilityAnimationVerticalPosition(
      native_view,
      -3.0f);
#endif

  // If the host had somehow finished loading, then we'd miss the notification
  // and not show.  This seems to happen in single-process mode.
  if (host->did_stop_loading())
    popup->ShowBubble();

  return popup;
}

void ExtensionPopup::ShowBubble() {
  Show();

  // Focus on the host contents when the bubble is first shown.
  host()->host_contents()->GetView()->Focus();

  // Listen for widget focus changes after showing (used for non-aura win).
  views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);

  if (inspect_with_devtools_) {
    DevToolsWindow::ToggleDevToolsWindow(host()->render_view_host(),
        true,
        DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE);
  }
}

void ExtensionPopup::CloseBubble() {
  GetWidget()->Close();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {

	return 0;
}
<commit_msg>adding<commit_after>#include <bits/stdc++.h>
using namespace std;

inline int in() { int x; scanf("%d", &x); return x; }
const long long N = 1200021;

int cntP[N], isP[N];

int main()
{
	for(int i = 2; i < N; i++)
		if(!isP[i])
			for(int j = i; j < N; j += i)
				isP[j] = i;
	int n = in(), k = in();
	for(int i = 0; i < n; i++)
	{
		int x = in();
		while(x > 1)
		{
			int p = isP[x];
			int cnt = 0;
			while(x % p == 0)
			{
				cnt++;
				x /= p;
			}
			cntP[p] = max(cntP[p], cnt);
		}
	}
	bool ok = 1;
	while(k > 1)
	{
		ok &= (cntP[isP[k]] > 0);
		cntP[isP[k]]--;
		k /= isP[k];
	}
	cout << (ok ? "Yes\n" : "No\n");
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "BaseTestFile.hpp"

#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>

#include <ctime>
#include <boost/filesystem.hpp>

using namespace std;
using namespace nix;
using namespace valid;

void BaseTestFile::testOpen() {
    CPPUNIT_ASSERT_THROW(File::open("dummy", FileMode::Overwrite, "grewe"), runtime_error);

}

void BaseTestFile::testValidate() {
    valid::Result result = validate(file_open);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
}

void BaseTestFile::testFormat() {
    CPPUNIT_ASSERT(file_open.format() == "nix");
    CPPUNIT_ASSERT(file_fs.format() == "nix");
}

void BaseTestFile::testLocation() {
    CPPUNIT_ASSERT(file_open.location() == "test_file.h5");
    CPPUNIT_ASSERT(file_other.location() == "test_file_other.h5");
    boost::filesystem::path p = boost::filesystem::current_path();
    boost::filesystem::path p_file("test_file");
    boost::filesystem::path p_other("other_file");
    CPPUNIT_ASSERT(file_fs.location() ==  (p / p_file).string());
    CPPUNIT_ASSERT(file_other_fs.location() == (p / p_other).string());
}

void BaseTestFile::testVersion() {
    vector<int> version{1, 0, 0};
    CPPUNIT_ASSERT(file_open.version() == version);
    CPPUNIT_ASSERT(file_fs.version() == version);
}

void BaseTestFile::testCreatedAt() {
    CPPUNIT_ASSERT(file_open.createdAt() >= statup_time);
    time_t past_time = time(NULL) - 10000000;
    file_open.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(file_open.createdAt() == past_time);

    CPPUNIT_ASSERT(file_fs.createdAt() >= startup_time);
    file_fs.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(file_fs.createdAt() == past_time);
}

void BaseTestFile::testUpdatedAt() {
    CPPUNIT_ASSERT(file_open.updatedAt() >= statup_time);
}

void BaseTestFile::testBlockAccess() {
    vector<string> names = { "block_a", "block_b", "block_c", "block_d", "block_e" };
    Block b;
    CPPUNIT_ASSERT(file_open.blockCount() == 0);
    CPPUNIT_ASSERT(file_open.blocks().size() == 0);
    CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
    CPPUNIT_ASSERT_EQUAL(false, file_open.hasBlock("invalid_id"));
    CPPUNIT_ASSERT(!file_open.hasBlock(b));

    vector<string> ids;
    for (const auto &name : names) {
        Block bl = file_open.createBlock(name, "dataset");
        CPPUNIT_ASSERT(bl.name() == name);
        CPPUNIT_ASSERT(file_open.hasBlock(bl));
        CPPUNIT_ASSERT(file_open.hasBlock(name));

        ids.push_back(bl.id());
    }
    CPPUNIT_ASSERT_THROW(file_open.createBlock(names[0], "dataset"),
                         DuplicateName);
    CPPUNIT_ASSERT(file_open.blockCount() == names.size());
    CPPUNIT_ASSERT(file_open.blocks().size() == names.size());

    for (const auto &name : names) {
        Block bl_name = file_open.getBlock(name);
        CPPUNIT_ASSERT(bl_name);

        Block bl_id = file_open.getBlock(bl_name.id());
        CPPUNIT_ASSERT(bl_id);
        CPPUNIT_ASSERT_EQUAL(bl_name.name(), bl_id.name());
    }

    for (const auto &id: ids) {
        Block bl = file_open.getBlock(id);
        CPPUNIT_ASSERT(file_open.hasBlock(id) == true);
        CPPUNIT_ASSERT(bl.id() == id);

        file_open.deleteBlock(id);
    }

    CPPUNIT_ASSERT(!file_open.deleteBlock(b));
    b = file_open.createBlock("test","test");
    CPPUNIT_ASSERT_NO_THROW(file_open.getBlock(0));
    CPPUNIT_ASSERT_THROW(file_open.getBlock(file_open.blockCount()), nix::OutOfBounds);
    CPPUNIT_ASSERT(file_open.deleteBlock(b));
    CPPUNIT_ASSERT(file_open.blockCount() == 0);
    CPPUNIT_ASSERT(file_open.blocks().size() == 0);
    CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
}

void BaseTestFile::testSectionAccess() {
    vector<string> names = {"section_a", "section_b", "section_c", "section_d", "section_e" };
    Section s;
    CPPUNIT_ASSERT(file_open.sectionCount() == 0);
    CPPUNIT_ASSERT(file_open.sections().size() == 0);
    CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
    CPPUNIT_ASSERT(!file_open.hasSection(s));

    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); it++) {
        Section sec = file_open.createSection(*it, "root section");
        CPPUNIT_ASSERT(sec.name() == *it);

        ids.push_back(sec.id());
    }
    CPPUNIT_ASSERT_THROW(file_open.createSection(names[0], "root section"),
                         DuplicateName);

    CPPUNIT_ASSERT(file_open.sectionCount() == names.size());
    CPPUNIT_ASSERT(file_open.sections().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); it++) {
        Section sec = file_open.getSection(*it);
        CPPUNIT_ASSERT(file_open.hasSection(*it) == true);
        CPPUNIT_ASSERT(sec.id() == *it);

        file_open.deleteSection(*it);
    }
    CPPUNIT_ASSERT(!file_open.deleteSection(s));
    s = file_open.createSection("test","test");
    CPPUNIT_ASSERT_NO_THROW(file_open.getSection(0));
    CPPUNIT_ASSERT_THROW(file_open.getSection(file_open.sectionCount()), nix::OutOfBounds);
    CPPUNIT_ASSERT(file_open.hasSection(s));
    CPPUNIT_ASSERT(file_open.deleteSection(s));
    CPPUNIT_ASSERT(file_open.sectionCount() == 0);
    CPPUNIT_ASSERT(file_open.sections().size() == 0);
    CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
}

void BaseTestFile::testOperators(){
    CPPUNIT_ASSERT(file_null == false);
    CPPUNIT_ASSERT(file_null == none);

    CPPUNIT_ASSERT(file_open != false);
    CPPUNIT_ASSERT(file_open != none);

    CPPUNIT_ASSERT(file_open == file_open);
    CPPUNIT_ASSERT(file_open != file_other);

    file_other = file_open;
    CPPUNIT_ASSERT(file_other == file_open);

    file_other = none;
    CPPUNIT_ASSERT(file_null == false);
    CPPUNIT_ASSERT(file_null == none);

    CPPUNIT_ASSERT(file_fs != file_other_fs);
    CPPUNIT_ASSERT(!(file_fs == file_other_fs));

    CPPUNIT_ASSERT(file_fs != false);
    CPPUNIT_ASSERT(file_fs != none);
}

void BaseTestFile::testReopen() {
    //file_open is currently open
    Block b = file_open.createBlock("a", "a");
    b = none;
    file_open.close();

    file_open = nix::File::open("test_file_b.h5", FileMode::Overwrite);
    b = file_open.createBlock("b", "b");
}

<commit_msg>[file_backend] cover force updated at in TestFile<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "BaseTestFile.hpp"

#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>

#include <ctime>
#include <boost/filesystem.hpp>

using namespace std;
using namespace nix;
using namespace valid;

void BaseTestFile::testOpen() {
    CPPUNIT_ASSERT_THROW(File::open("dummy", FileMode::Overwrite, "grewe"), runtime_error);

}

void BaseTestFile::testValidate() {
    valid::Result result = validate(file_open);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
}

void BaseTestFile::testFormat() {
    CPPUNIT_ASSERT(file_open.format() == "nix");
    CPPUNIT_ASSERT(file_fs.format() == "nix");
}

void BaseTestFile::testLocation() {
    CPPUNIT_ASSERT(file_open.location() == "test_file.h5");
    CPPUNIT_ASSERT(file_other.location() == "test_file_other.h5");
    boost::filesystem::path p = boost::filesystem::current_path();
    boost::filesystem::path p_file("test_file");
    boost::filesystem::path p_other("other_file");
    CPPUNIT_ASSERT(file_fs.location() ==  (p / p_file).string());
    CPPUNIT_ASSERT(file_other_fs.location() == (p / p_other).string());
}

void BaseTestFile::testVersion() {
    vector<int> version{1, 0, 0};
    CPPUNIT_ASSERT(file_open.version() == version);
    CPPUNIT_ASSERT(file_fs.version() == version);
}

void BaseTestFile::testCreatedAt() {
    CPPUNIT_ASSERT(file_open.createdAt() >= statup_time);
    time_t past_time = time(NULL) - 10000000;
    file_open.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(file_open.createdAt() == past_time);

    CPPUNIT_ASSERT(file_fs.createdAt() >= startup_time);
    file_fs.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(file_fs.createdAt() == past_time);
}

void BaseTestFile::testUpdatedAt() {
    CPPUNIT_ASSERT(file_open.updatedAt() >= statup_time);
    time_t now = time(NULL);
    file_open.forceUpdatedAt();
    CPPUNIT_ASSERT(file_open.updatedAt() >= now);
}

void BaseTestFile::testBlockAccess() {
    vector<string> names = { "block_a", "block_b", "block_c", "block_d", "block_e" };
    Block b;
    CPPUNIT_ASSERT(file_open.blockCount() == 0);
    CPPUNIT_ASSERT(file_open.blocks().size() == 0);
    CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
    CPPUNIT_ASSERT_EQUAL(false, file_open.hasBlock("invalid_id"));
    CPPUNIT_ASSERT(!file_open.hasBlock(b));

    vector<string> ids;
    for (const auto &name : names) {
        Block bl = file_open.createBlock(name, "dataset");
        CPPUNIT_ASSERT(bl.name() == name);
        CPPUNIT_ASSERT(file_open.hasBlock(bl));
        CPPUNIT_ASSERT(file_open.hasBlock(name));

        ids.push_back(bl.id());
    }
    CPPUNIT_ASSERT_THROW(file_open.createBlock(names[0], "dataset"),
                         DuplicateName);
    CPPUNIT_ASSERT(file_open.blockCount() == names.size());
    CPPUNIT_ASSERT(file_open.blocks().size() == names.size());

    for (const auto &name : names) {
        Block bl_name = file_open.getBlock(name);
        CPPUNIT_ASSERT(bl_name);

        Block bl_id = file_open.getBlock(bl_name.id());
        CPPUNIT_ASSERT(bl_id);
        CPPUNIT_ASSERT_EQUAL(bl_name.name(), bl_id.name());
    }

    for (const auto &id: ids) {
        Block bl = file_open.getBlock(id);
        CPPUNIT_ASSERT(file_open.hasBlock(id) == true);
        CPPUNIT_ASSERT(bl.id() == id);

        file_open.deleteBlock(id);
    }

    CPPUNIT_ASSERT(!file_open.deleteBlock(b));
    b = file_open.createBlock("test","test");
    CPPUNIT_ASSERT_NO_THROW(file_open.getBlock(0));
    CPPUNIT_ASSERT_THROW(file_open.getBlock(file_open.blockCount()), nix::OutOfBounds);
    CPPUNIT_ASSERT(file_open.deleteBlock(b));
    CPPUNIT_ASSERT(file_open.blockCount() == 0);
    CPPUNIT_ASSERT(file_open.blocks().size() == 0);
    CPPUNIT_ASSERT(file_open.getBlock("invalid_id") == false);
}

void BaseTestFile::testSectionAccess() {
    vector<string> names = {"section_a", "section_b", "section_c", "section_d", "section_e" };
    Section s;
    CPPUNIT_ASSERT(file_open.sectionCount() == 0);
    CPPUNIT_ASSERT(file_open.sections().size() == 0);
    CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
    CPPUNIT_ASSERT(!file_open.hasSection(s));

    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); it++) {
        Section sec = file_open.createSection(*it, "root section");
        CPPUNIT_ASSERT(sec.name() == *it);

        ids.push_back(sec.id());
    }
    CPPUNIT_ASSERT_THROW(file_open.createSection(names[0], "root section"),
                         DuplicateName);

    CPPUNIT_ASSERT(file_open.sectionCount() == names.size());
    CPPUNIT_ASSERT(file_open.sections().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); it++) {
        Section sec = file_open.getSection(*it);
        CPPUNIT_ASSERT(file_open.hasSection(*it) == true);
        CPPUNIT_ASSERT(sec.id() == *it);

        file_open.deleteSection(*it);
    }
    CPPUNIT_ASSERT(!file_open.deleteSection(s));
    s = file_open.createSection("test","test");
    CPPUNIT_ASSERT_NO_THROW(file_open.getSection(0));
    CPPUNIT_ASSERT_THROW(file_open.getSection(file_open.sectionCount()), nix::OutOfBounds);
    CPPUNIT_ASSERT(file_open.hasSection(s));
    CPPUNIT_ASSERT(file_open.deleteSection(s));
    CPPUNIT_ASSERT(file_open.sectionCount() == 0);
    CPPUNIT_ASSERT(file_open.sections().size() == 0);
    CPPUNIT_ASSERT(file_open.getSection("invalid_id") == false);
}

void BaseTestFile::testOperators(){
    CPPUNIT_ASSERT(file_null == false);
    CPPUNIT_ASSERT(file_null == none);

    CPPUNIT_ASSERT(file_open != false);
    CPPUNIT_ASSERT(file_open != none);

    CPPUNIT_ASSERT(file_open == file_open);
    CPPUNIT_ASSERT(file_open != file_other);

    file_other = file_open;
    CPPUNIT_ASSERT(file_other == file_open);

    file_other = none;
    CPPUNIT_ASSERT(file_null == false);
    CPPUNIT_ASSERT(file_null == none);

    CPPUNIT_ASSERT(file_fs != file_other_fs);
    CPPUNIT_ASSERT(!(file_fs == file_other_fs));

    CPPUNIT_ASSERT(file_fs != false);
    CPPUNIT_ASSERT(file_fs != none);
}

void BaseTestFile::testReopen() {
    //file_open is currently open
    Block b = file_open.createBlock("a", "a");
    b = none;
    file_open.close();

    file_open = nix::File::open("test_file_b.h5", FileMode::Overwrite);
    b = file_open.createBlock("b", "b");
}

<|endoftext|>


<commit_before>#include "view/SceneView.h"

#include "DotSceneLoader.h"

#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreConfigFile.h>
#include <OgreEntity.h>
#include <OgreWindowEventUtilities.h>

#include <sstream>

SceneView::SceneView(Rally::Model::World& world) :
        world(world),
        camera(NULL),
        sceneManager(NULL),
        renderWindow(NULL) {
}

SceneView::~SceneView() {
    Ogre::Root* root = Ogre::Root::getSingletonPtr();
    delete root;
}

void SceneView::initialize(std::string resourceConfigPath, std::string pluginConfigPath) {
    Ogre::Root* root = new Ogre::Root(pluginConfigPath);

    this->loadResourceConfig(resourceConfigPath);
    // (The actual precaching is done below, once there is a render context)

    if(!root->restoreConfig() && !root->showConfigDialog()) {
        throw std::runtime_error("Could neither restore Ogre config, nor read it from the user.");
    }

    renderWindow = root->initialise(
        true, // auto-create the render window now
        "Rally Sport Racing Game");

    sceneManager = root->createSceneManager("OctreeSceneManager"); // Todo: Research a good scene manager

    // This should be done after creating a scene manager, so that there is a render context (GL/D3D)
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    camera = this->addCamera("MainCamera");
    Ogre::Viewport* viewport = this->addViewport(camera);
    camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));

    // TODO: Fix this to follow car...
    camera->setPosition(Ogre::Vector3(0, 100, -250));
    camera->lookAt(Ogre::Vector3(0, 0, 0));

    // TODO: Implement separate scene loading (how do we do with lights?)
    //Ogre::Entity* ogreHead = sceneManager->createEntity("Head", "ogrehead.mesh");
    Ogre::SceneNode* sceneNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    //headNode->attachObject(ogreHead);
	sceneManager->setAmbientLight(Ogre::ColourValue(1, 1, 1));
	Ogre::Light* light = sceneManager->createLight("MainLight");
	light->setPosition(20, 80, 50);

	// Load the scene.
	DotSceneLoader loader;
	loader.parseDotScene("chalmers1d.scene", "General", sceneManager, sceneNode);

	// Todo: Move to appropriate view
	Ogre::Entity* playerCarEntity = sceneManager->createEntity("PlayerCar", "ogrehead.mesh");
	playerCarNode = sceneManager->getRootSceneNode()->createChildSceneNode();
	playerCarNode->attachObject(playerCarEntity);
}

Ogre::Viewport* SceneView::addViewport(Ogre::Camera* followedCamera) {
    Ogre::Viewport* viewport = renderWindow->addViewport(camera);
    viewport->setBackgroundColour(Ogre::ColourValue(0, 0, 0));

    return viewport;
}

Ogre::Camera* SceneView::addCamera(Ogre::String cameraName) {
    // Setup camera to match viewport
    Ogre::Camera* camera = sceneManager->createCamera(cameraName);
    camera->setNearClipDistance(5);

    return camera;
}

void SceneView::loadResourceConfig(Ogre::String resourceConfigPath) {
    Ogre::ResourceGroupManager& resourceGroupManager = Ogre::ResourceGroupManager::getSingleton();

    Ogre::ConfigFile resourceConfig;
    resourceConfig.load(resourceConfigPath);

    for(Ogre::ConfigFile::SectionIterator sectionIterator = resourceConfig.getSectionIterator();
            sectionIterator.hasMoreElements();
            sectionIterator.moveNext()) {
        Ogre::ConfigFile::SettingsMultiMap* settings = sectionIterator.peekNextValue();

        // Now load all the resources for this resource group
        for(Ogre::ConfigFile::SettingsMultiMap::iterator resource = settings->begin();
                resource != settings->end();
                ++resource) {
            resourceGroupManager.addResourceLocation(
                resource->second, // filename of directory
                resource->first, // resource type
                sectionIterator.peekNextKey()); // resource group
        }
    }
}

bool SceneView::renderFrame() {
    Ogre::WindowEventUtilities::messagePump();

    if(renderWindow->isClosed())  {
        return false;
    } else {
        updatePlayerCar();

        Ogre::Root& root = Ogre::Root::getSingleton();
        if(!root.renderOneFrame()) {
            return false;
        }
    }
    return true;
}

void SceneView::updatePlayerCar() {
    // Todo: Move to separate view
    Rally::Model::Car& playerCar = world.getPlayerCar();
    playerCarNode->setPosition(playerCar.getPosition());
    playerCarNode->setDirection(playerCar.getOrientation());
}
<commit_msg>Fixed 'car' crazy-spin render bug.<commit_after>#include "view/SceneView.h"

#include "DotSceneLoader.h"

#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreConfigFile.h>
#include <OgreEntity.h>
#include <OgreWindowEventUtilities.h>

#include <sstream>

SceneView::SceneView(Rally::Model::World& world) :
        world(world),
        camera(NULL),
        sceneManager(NULL),
        renderWindow(NULL) {
}

SceneView::~SceneView() {
    Ogre::Root* root = Ogre::Root::getSingletonPtr();
    delete root;
}

void SceneView::initialize(std::string resourceConfigPath, std::string pluginConfigPath) {
    Ogre::Root* root = new Ogre::Root(pluginConfigPath);

    this->loadResourceConfig(resourceConfigPath);
    // (The actual precaching is done below, once there is a render context)

    if(!root->restoreConfig() && !root->showConfigDialog()) {
        throw std::runtime_error("Could neither restore Ogre config, nor read it from the user.");
    }

    renderWindow = root->initialise(
        true, // auto-create the render window now
        "Rally Sport Racing Game");

    sceneManager = root->createSceneManager("OctreeSceneManager"); // Todo: Research a good scene manager

    // This should be done after creating a scene manager, so that there is a render context (GL/D3D)
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    camera = this->addCamera("MainCamera");
    Ogre::Viewport* viewport = this->addViewport(camera);
    camera->setAspectRatio(Ogre::Real(viewport->getActualWidth()) / Ogre::Real(viewport->getActualHeight()));

    // TODO: Fix this to follow car...
    camera->setPosition(Ogre::Vector3(0, 100, -250));
    camera->lookAt(Ogre::Vector3(0, 0, 0));

    // TODO: Implement separate scene loading (how do we do with lights?)
    //Ogre::Entity* ogreHead = sceneManager->createEntity("Head", "ogrehead.mesh");
    Ogre::SceneNode* sceneNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    //headNode->attachObject(ogreHead);
	sceneManager->setAmbientLight(Ogre::ColourValue(1, 1, 1));
	Ogre::Light* light = sceneManager->createLight("MainLight");
	light->setPosition(20, 80, 50);

	// Load the scene.
	DotSceneLoader loader;
	loader.parseDotScene("chalmers1d.scene", "General", sceneManager, sceneNode);

	// Todo: Move to appropriate view
	Ogre::Entity* playerCarEntity = sceneManager->createEntity("PlayerCar", "ogrehead.mesh");
	playerCarNode = sceneManager->getRootSceneNode()->createChildSceneNode();
	playerCarNode->attachObject(playerCarEntity);
}

Ogre::Viewport* SceneView::addViewport(Ogre::Camera* followedCamera) {
    Ogre::Viewport* viewport = renderWindow->addViewport(camera);
    viewport->setBackgroundColour(Ogre::ColourValue(0, 0, 0));

    return viewport;
}

Ogre::Camera* SceneView::addCamera(Ogre::String cameraName) {
    // Setup camera to match viewport
    Ogre::Camera* camera = sceneManager->createCamera(cameraName);
    camera->setNearClipDistance(5);

    return camera;
}

void SceneView::loadResourceConfig(Ogre::String resourceConfigPath) {
    Ogre::ResourceGroupManager& resourceGroupManager = Ogre::ResourceGroupManager::getSingleton();

    Ogre::ConfigFile resourceConfig;
    resourceConfig.load(resourceConfigPath);

    for(Ogre::ConfigFile::SectionIterator sectionIterator = resourceConfig.getSectionIterator();
            sectionIterator.hasMoreElements();
            sectionIterator.moveNext()) {
        Ogre::ConfigFile::SettingsMultiMap* settings = sectionIterator.peekNextValue();

        // Now load all the resources for this resource group
        for(Ogre::ConfigFile::SettingsMultiMap::iterator resource = settings->begin();
                resource != settings->end();
                ++resource) {
            resourceGroupManager.addResourceLocation(
                resource->second, // filename of directory
                resource->first, // resource type
                sectionIterator.peekNextKey()); // resource group
        }
    }
}

bool SceneView::renderFrame() {
    Ogre::WindowEventUtilities::messagePump();

    if(renderWindow->isClosed())  {
        return false;
    } else {
        updatePlayerCar();

        Ogre::Root& root = Ogre::Root::getSingleton();
        if(!root.renderOneFrame()) {
            return false;
        }
    }
    return true;
}

void SceneView::updatePlayerCar() {
    // Todo: Move to separate view
    Rally::Model::Car& playerCar = world.getPlayerCar();
    playerCarNode->setPosition(playerCar.getPosition());
    playerCarNode->setDirection(playerCar.getOrientation(), Ogre::Node::TS_PARENT);
}
<|endoftext|>


<commit_before>/*
 *  einit-gui-gtk.c++
 *  einit
 *
 *  Created by Magnus Deininger on 01/08/2007.
 *  Copyright 2006, 2007 Magnus Deininger. All rights reserved.
 *
 */

/*
Copyright (c) 2007, Magnus Deininger
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 project 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 <einit/einit++.h>

#include <gtkmm.h>
#include <iostream>

#include <libnotify/notify.h>

Einit einit;

void einit_feedback_event_handler (struct einit_remote_event *ev) {
 if ((ev->type == einit_feedback_notice) && ev->string) {
  gint to = 3000;
  NotifyNotification *nitem = notify_notification_new("eINIT Notification", ev->string, USHAREDIR "/images/einit.png", NULL);

  if (ev->flag < 4) { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_CRITICAL); to = 60000; }
  else if (ev->flag < 6) { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL); to = 20000; }
  else { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_LOW); }

  notify_notification_set_timeout(nitem, to);
  notify_notification_show (nitem, NULL);
 }
}

void einit_core_event_handler (struct einit_remote_event *ev) {
 if ((ev->type == einit_core_service_update) && ev->string) {
  if (ev->status & status_failed) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Service Command Failed", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_CRITICAL);

   notify_notification_set_timeout(nitem, 30000);
   notify_notification_show (nitem, NULL);
  } else if (ev->status & status_enabled) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Module Enabled", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL);

   notify_notification_set_timeout(nitem, 5000);
   notify_notification_show (nitem, NULL);
  } else  if (ev->status & status_disabled) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Module Disabled", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL);

   notify_notification_set_timeout(nitem, 5000);
   notify_notification_show (nitem, NULL);
  }

 }
}

class EinitGTK : public Gtk::Window {
 public:
  EinitGTK();
  virtual ~EinitGTK();

 protected:
  //Signal handlers:
  static void     on_statusicon_popup  (GtkStatusIcon* widget,
				        guint          button,
				        guint            time,
				        gpointer       object);
  static  void on_menuitem_selected (const Glib::ustring& item_name);

  Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer1;

  Glib::RefPtr<Gtk::StatusIcon> m_refStatusIcon;
  Glib::RefPtr<Gtk::UIManager> m_refUIManager;
};

EinitGTK::EinitGTK() {

 Glib::RefPtr<Gtk::ActionGroup> refActionGroup = Gtk::ActionGroup::create();
 refActionGroup->add( Gtk::Action::create("Power Down", "Power Down"),
	       sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Power Down") );
 refActionGroup->add( Gtk::Action::create("Reboot", "Reboot"),
	       sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Reboot") );
 refActionGroup->add( Gtk::Action::create("Quit", Gtk::Stock::QUIT),
                      sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Quit") );

 m_refUIManager = Gtk::UIManager::create();
 m_refUIManager->insert_action_group(refActionGroup);

 Glib::ustring ui_info =
  "<ui>"
  "  <popup name='Popup'>"
  "    <menuitem action='Power Down' />"
  "    <menuitem action='Reboot' />"
  "    <separator/>"
  "    <menuitem action='Quit' />"
  "  </popup>"
  "</ui>";

 m_refUIManager->add_ui_from_string(ui_info);

 m_refStatusIcon = Gtk::StatusIcon::create(Gdk::Pixbuf::create_from_file(USHAREDIR "/images/einit.png", 80, 80, true));
 m_refStatusIcon->set_tooltip("eINIT");
 GtkStatusIcon* gobj_StatusIcon = m_refStatusIcon->gobj();
 g_signal_connect(G_OBJECT(gobj_StatusIcon), "popup-menu", G_CALLBACK(on_statusicon_popup), this);

 einit.listen (einit_event_subsystem_feedback, einit_feedback_event_handler);
 einit.listen (einit_event_subsystem_core, einit_core_event_handler);
}

void EinitGTK::on_statusicon_popup(GtkStatusIcon* status_icon, guint button,
					guint time, gpointer object)
{
	EinitGTK* win = static_cast<EinitGTK*>(object);
	Gtk::Menu* pMenu = static_cast<Gtk::Menu*>( win->m_refUIManager->get_widget("/Popup") );

	if(pMenu)
		pMenu->popup(button, time);
}

void EinitGTK::on_menuitem_selected(const Glib::ustring& item)
{
 if (item == "Quit") {
  Gtk::Main::quit();
 } else if (item == "Power Down") {
  einit.powerDown();
 } else if (item == "Reboot") {
  einit.powerReset();
 } else {
  g_print("Unknown action: %s\n", item.data());
 }
}

EinitGTK::~EinitGTK() {
}

int main (int argc, char *argv[]) {
 notify_init ("eINIT");

 {
  Gtk::Main kit(argc, argv);

  EinitGTK trayicon;
  Gtk::Main::run();
 }

 return 0;
}
<commit_msg>added mutexes around notification-creations (seems to fix a sudden-death issue)<commit_after>/*
 *  einit-gui-gtk.c++
 *  einit
 *
 *  Created by Magnus Deininger on 01/08/2007.
 *  Copyright 2006, 2007 Magnus Deininger. All rights reserved.
 *
 */

/*
Copyright (c) 2007, Magnus Deininger
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 project 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 <einit/einit++.h>

#include <gtkmm.h>
#include <iostream>

#include <libnotify/notify.h>
#include <pthread.h>

Einit einit;
pthread_mutex_t notificationmutex = PTHREAD_MUTEX_INITIALIZER;

void einit_feedback_event_handler (struct einit_remote_event *ev) {
 if ((ev->type == einit_feedback_notice) && ev->string) {
  pthread_mutex_lock (&notificationmutex);

  gint to = 3000;
  NotifyNotification *nitem = notify_notification_new("eINIT Notification", ev->string, USHAREDIR "/images/einit.png", NULL);

  if (ev->flag < 4) { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_CRITICAL); to = 60000; }
  else if (ev->flag < 6) { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL); to = 20000; }
  else { notify_notification_set_urgency (nitem, NOTIFY_URGENCY_LOW); }

  notify_notification_set_timeout(nitem, to);
  notify_notification_show (nitem, NULL);

  pthread_mutex_unlock (&notificationmutex);
 }
}

void einit_core_event_handler (struct einit_remote_event *ev) {
 if ((ev->type == einit_core_service_update) && ev->string) {
  pthread_mutex_lock (&notificationmutex);

  if (ev->status & status_failed) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Service Command Failed", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_CRITICAL);

   notify_notification_set_timeout(nitem, 30000);
   notify_notification_show (nitem, NULL);
  } else if (ev->status & status_enabled) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Module Enabled", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL);

   notify_notification_set_timeout(nitem, 5000);
   notify_notification_show (nitem, NULL);
  } else  if (ev->status & status_disabled) {
   NotifyNotification *nitem = notify_notification_new("eINIT: Module Disabled", ev->string, USHAREDIR "/images/einit.png", NULL);

   notify_notification_set_urgency (nitem, NOTIFY_URGENCY_NORMAL);

   notify_notification_set_timeout(nitem, 5000);
   notify_notification_show (nitem, NULL);
  }

  pthread_mutex_unlock (&notificationmutex);
 }
}

class EinitGTK : public Gtk::Window {
 public:
  EinitGTK();
  virtual ~EinitGTK();

 protected:
  //Signal handlers:
  static void     on_statusicon_popup  (GtkStatusIcon* widget,
				        guint          button,
				        guint            time,
				        gpointer       object);
  static  void on_menuitem_selected (const Glib::ustring& item_name);

  Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer1;

  Glib::RefPtr<Gtk::StatusIcon> m_refStatusIcon;
  Glib::RefPtr<Gtk::UIManager> m_refUIManager;
};

EinitGTK::EinitGTK() {

 Glib::RefPtr<Gtk::ActionGroup> refActionGroup = Gtk::ActionGroup::create();
 refActionGroup->add( Gtk::Action::create("Power Down", "Power Down"),
	       sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Power Down") );
 refActionGroup->add( Gtk::Action::create("Reboot", "Reboot"),
	       sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Reboot") );
 refActionGroup->add( Gtk::Action::create("Quit", Gtk::Stock::QUIT),
                      sigc::bind(sigc::ptr_fun(&EinitGTK::on_menuitem_selected), "Quit") );

 m_refUIManager = Gtk::UIManager::create();
 m_refUIManager->insert_action_group(refActionGroup);

 Glib::ustring ui_info =
  "<ui>"
  "  <popup name='Popup'>"
  "    <menuitem action='Power Down' />"
  "    <menuitem action='Reboot' />"
  "    <separator/>"
  "    <menuitem action='Quit' />"
  "  </popup>"
  "</ui>";

 m_refUIManager->add_ui_from_string(ui_info);

 m_refStatusIcon = Gtk::StatusIcon::create(Gdk::Pixbuf::create_from_file(USHAREDIR "/images/einit.png", 80, 80, true));
 m_refStatusIcon->set_tooltip("eINIT");
 GtkStatusIcon* gobj_StatusIcon = m_refStatusIcon->gobj();
 g_signal_connect(G_OBJECT(gobj_StatusIcon), "popup-menu", G_CALLBACK(on_statusicon_popup), this);

 einit.listen (einit_event_subsystem_feedback, einit_feedback_event_handler);
 einit.listen (einit_event_subsystem_core, einit_core_event_handler);
}

void EinitGTK::on_statusicon_popup(GtkStatusIcon* status_icon, guint button,
					guint time, gpointer object)
{
	EinitGTK* win = static_cast<EinitGTK*>(object);
	Gtk::Menu* pMenu = static_cast<Gtk::Menu*>( win->m_refUIManager->get_widget("/Popup") );

	if(pMenu)
		pMenu->popup(button, time);
}

void EinitGTK::on_menuitem_selected(const Glib::ustring& item)
{
 if (item == "Quit") {
  Gtk::Main::quit();
 } else if (item == "Power Down") {
  einit.powerDown();
 } else if (item == "Reboot") {
  einit.powerReset();
 } else {
  g_print("Unknown action: %s\n", item.data());
 }
}

EinitGTK::~EinitGTK() {
}

int main (int argc, char *argv[]) {
 notify_init ("eINIT");

 {
  Gtk::Main kit(argc, argv);

  EinitGTK trayicon;
  Gtk::Main::run();
 }

 return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2015, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 * Class with reduced jet information for the reduced jet tree
 *
 * Author:
 *   Markus Fasel <markus.fasel@cern.ch>
 */

#include <TLorentzVector.h>
#include <TObjArray.h>

#include "AliReducedJetConstituent.h"
#include "AliReducedJetInfo.h"
#include "AliReducedJetParticle.h"

ClassImp(HighPtTracks::AliReducedJetInfo)

namespace HighPtTracks {

AliReducedJetInfo::AliReducedJetInfo() :
	TObject(),
	fPx(0.),
	fPy(0.),
	fPz(0.),
	fE(0),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
}

AliReducedJetInfo::AliReducedJetInfo(double px, double py, double pz, double e) :
	TObject(),
	fPx(px),
	fPy(py),
	fPz(pz),
	fE(e),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
	fParticlesInCone = new TObjArray;
	fParticlesInCone->SetOwner(true);
	fConstituents = new TObjArray;
	fConstituents->SetOwner(true);
}

AliReducedJetInfo::AliReducedJetInfo(const AliReducedJetInfo& ref) :
	TObject(ref),
	fPx(ref.fPx),
	fPy(ref.fPy),
	fPz(ref.fPz),
	fE(ref.fE),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
	fParticlesInCone = new TObjArray();
	fParticlesInCone->SetOwner(true);
	fConstituents = new TObjArray;
	fConstituents->SetOwner(true);

	AliReducedJetParticle *mypart(NULL);
	TIter particleIter(ref.fParticlesInCone);
	while((mypart = dynamic_cast<AliReducedJetParticle *>(particleIter()))){
		fParticlesInCone->Add(new AliReducedJetParticle(*mypart));
	}
	AliReducedJetConstituent *myconst(NULL);
	TIter constIter(ref.fConstituents);
	while((myconst = dynamic_cast<AliReducedJetConstituent *>(constIter()))){
		fConstituents->Add(new AliReducedJetConstituent(*myconst));
	}
}

AliReducedJetInfo& AliReducedJetInfo::operator=(const AliReducedJetInfo& ref) {
	TObject::operator=(ref);
	if(&ref != this){
		fPx = ref.fPx;
		fPy = ref.fPy;
		fPz = ref.fPz;
		fE = ref.fE;

		fParticlesInCone->Clear();
		AliReducedJetParticle *mypart(NULL);
		TIter particleIter(ref.fParticlesInCone);
		while((mypart = dynamic_cast<AliReducedJetParticle *>(particleIter()))){
			fParticlesInCone->Add(new AliReducedJetParticle(*mypart));
		}

		fConstituents->Clear();
		AliReducedJetConstituent *myconst(NULL);
		TIter constIter(ref.fConstituents);
		while((myconst = dynamic_cast<AliReducedJetConstituent *>(constIter()))){
			fConstituents->Add(new AliReducedJetConstituent(*myconst));
		}
	}
	return *this;
}

AliReducedJetInfo::~AliReducedJetInfo() {
	delete fParticlesInCone;
}

void AliReducedJetInfo::AddParticleInCone(AliReducedJetParticle* part) {
	if(fParticlesInCone) fParticlesInCone->Add(part);
}

void AliReducedJetInfo::FillLorentzVector(TLorentzVector& vec) const {
	vec.SetPxPyPzE(fPx, fPy, fPx, fE);
}

int AliReducedJetInfo::GetNumberOfMatchedParticles() const {
	if(!fParticlesInCone) return 0;
	return fParticlesInCone->GetEntries();
}

void AliReducedJetInfo::AddConstituent(AliReducedJetConstituent* con) {
	if(fConstituents) fConstituents->Add(con);
}

AliReducedJetParticle* AliReducedJetInfo::GetMatchedParticle(int ipart) const {
	if(!fParticlesInCone || ipart >= fParticlesInCone->GetEntries()) return NULL;
	return dynamic_cast<AliReducedJetParticle *>(fParticlesInCone->At(ipart));
}

} /* namespace HighPtTracks */
<commit_msg>Fixing memory leak<commit_after>/**************************************************************************
 * Copyright(c) 1998-2015, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 * Class with reduced jet information for the reduced jet tree
 *
 * Author:
 *   Markus Fasel <markus.fasel@cern.ch>
 */

#include <TLorentzVector.h>
#include <TObjArray.h>

#include "AliReducedJetConstituent.h"
#include "AliReducedJetInfo.h"
#include "AliReducedJetParticle.h"

ClassImp(HighPtTracks::AliReducedJetInfo)

namespace HighPtTracks {

AliReducedJetInfo::AliReducedJetInfo() :
	TObject(),
	fPx(0.),
	fPy(0.),
	fPz(0.),
	fE(0),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
}

AliReducedJetInfo::AliReducedJetInfo(double px, double py, double pz, double e) :
	TObject(),
	fPx(px),
	fPy(py),
	fPz(pz),
	fE(e),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
	fParticlesInCone = new TObjArray;
	fParticlesInCone->SetOwner(true);
	fConstituents = new TObjArray;
	fConstituents->SetOwner(true);
}

AliReducedJetInfo::AliReducedJetInfo(const AliReducedJetInfo& ref) :
	TObject(ref),
	fPx(ref.fPx),
	fPy(ref.fPy),
	fPz(ref.fPz),
	fE(ref.fE),
	fConstituents(NULL),
	fParticlesInCone(NULL)
{
	fParticlesInCone = new TObjArray();
	fParticlesInCone->SetOwner(true);
	fConstituents = new TObjArray;
	fConstituents->SetOwner(true);

	AliReducedJetParticle *mypart(NULL);
	TIter particleIter(ref.fParticlesInCone);
	while((mypart = dynamic_cast<AliReducedJetParticle *>(particleIter()))){
		fParticlesInCone->Add(new AliReducedJetParticle(*mypart));
	}
	AliReducedJetConstituent *myconst(NULL);
	TIter constIter(ref.fConstituents);
	while((myconst = dynamic_cast<AliReducedJetConstituent *>(constIter()))){
		fConstituents->Add(new AliReducedJetConstituent(*myconst));
	}
}

AliReducedJetInfo& AliReducedJetInfo::operator=(const AliReducedJetInfo& ref) {
	TObject::operator=(ref);
	if(&ref != this){
		fPx = ref.fPx;
		fPy = ref.fPy;
		fPz = ref.fPz;
		fE = ref.fE;

		fParticlesInCone->Clear();
		AliReducedJetParticle *mypart(NULL);
		TIter particleIter(ref.fParticlesInCone);
		while((mypart = dynamic_cast<AliReducedJetParticle *>(particleIter()))){
			fParticlesInCone->Add(new AliReducedJetParticle(*mypart));
		}

		fConstituents->Clear();
		AliReducedJetConstituent *myconst(NULL);
		TIter constIter(ref.fConstituents);
		while((myconst = dynamic_cast<AliReducedJetConstituent *>(constIter()))){
			fConstituents->Add(new AliReducedJetConstituent(*myconst));
		}
	}
	return *this;
}

AliReducedJetInfo::~AliReducedJetInfo() {
	delete fParticlesInCone;
	delete fConstituents;
}

void AliReducedJetInfo::AddParticleInCone(AliReducedJetParticle* part) {
	if(fParticlesInCone) fParticlesInCone->Add(part);
}

void AliReducedJetInfo::FillLorentzVector(TLorentzVector& vec) const {
	vec.SetPxPyPzE(fPx, fPy, fPx, fE);
}

int AliReducedJetInfo::GetNumberOfMatchedParticles() const {
	if(!fParticlesInCone) return 0;
	return fParticlesInCone->GetEntries();
}

void AliReducedJetInfo::AddConstituent(AliReducedJetConstituent* con) {
	if(fConstituents) fConstituents->Add(con);
}

AliReducedJetParticle* AliReducedJetInfo::GetMatchedParticle(int ipart) const {
	if(!fParticlesInCone || ipart >= fParticlesInCone->GetEntries()) return NULL;
	return dynamic_cast<AliReducedJetParticle *>(fParticlesInCone->At(ipart));
}

} /* namespace HighPtTracks */
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "BlackArea.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) :
offset(_offset), size(_size), isVertical(isVertical)
{

}

BlackArea::~BlackArea(void)
{
}

} // namespace RawSpeed
<commit_msg>Fix orientation of black areas (value left uninitialized).<commit_after>#include "StdAfx.h"
#include "BlackArea.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) :
offset(_offset), size(_size), isVertical(_isVertical)
{

}

BlackArea::~BlackArea(void)
{
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Google Inc.
 *
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 */

#include "SkExample.h"

#include "gl/GrGLUtil.h"
#include "gl/GrGLDefines.h"
#include "gl/GrGLInterface.h"
#include "SkApplication.h"
#include "SkCommandLineFlags.h"
#include "SkGpuDevice.h"
#include "SkGraphics.h"

DEFINE_string2(match, m, NULL, "[~][^]substring[$] [...] of test name to run.\n" \
                               "Multiple matches may be separated by spaces.\n" \
                               "~ causes a matching test to always be skipped\n" \
                               "^ requires the start of the test to match\n" \
                               "$ requires the end of the test to match\n" \
                               "^ and $ requires an exact match\n" \
                               "If a test does not match any list entry,\n" \
                               "it is skipped unless some list entry starts with ~");

void application_init() {
    SkGraphics::Init();
    SkEvent::Init();
}

void application_term() {
    SkEvent::Term();
    SkGraphics::Term();
}

SkExampleWindow::SkExampleWindow(void* hwnd)
    : INHERITED(hwnd) {
    fRegistry = SkExample::Registry::Head();
    fCurrExample = fRegistry->factory()(this);

    if (FLAGS_match.count()) {
        // Start with the a matching sample if possible.
        bool found = this->findNextMatch();
        if (!found) {
            SkDebugf("No matching SkExample found.\n");
        }
    }
}

void SkExampleWindow::tearDownBackend() {
  if (kGPU_DeviceType == fType) {
        SkSafeUnref(fContext);
        fContext = NULL;

        SkSafeUnref(fInterface);
        fInterface = NULL;

        SkSafeUnref(fRenderTarget);
        fRenderTarget = NULL;

        detach();
    }
}

bool SkExampleWindow::setupBackend(DeviceType type) {
    fType = type;

    this->setConfig(SkBitmap::kARGB_8888_Config);
    this->setVisibleP(true);
    this->setClipToBounds(false);

    bool result = attach(kNativeGL_BackEndType, 0 /*msaa*/, &fAttachmentInfo);
    if (false == result) {
        SkDebugf("Not possible to create backend.\n");
        detach();
        return false;
    }

    fInterface = GrGLCreateNativeInterface();

    SkASSERT(NULL != fInterface);

    fContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)fInterface);
    SkASSERT(NULL != fContext);

    setupRenderTarget();

    return true;
}

void SkExampleWindow::setupRenderTarget() {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(width());
    desc.fHeight = SkScalarRoundToInt(height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    desc.fSampleCnt = fAttachmentInfo.fSampleCount;
    desc.fStencilBits = fAttachmentInfo.fStencilBits;

    GrGLint buffer;
    GR_GL_GetIntegerv(fInterface, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    fRenderTarget = fContext->wrapBackendRenderTarget(desc);

    fContext->setRenderTarget(fRenderTarget);
}

SkCanvas* SkExampleWindow::createCanvas() {
    if (fType == kGPU_DeviceType) {
        if (NULL != fContext && NULL != fRenderTarget) {
            SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fContext, fRenderTarget));
            return new SkCanvas(device);
        }
        tearDownBackend();
        setupBackend(kRaster_DeviceType);
    }
    return INHERITED::createCanvas();
}

void SkExampleWindow::draw(SkCanvas* canvas) {
    if (NULL != fCurrExample) {
        fCurrExample->draw(canvas);
    }
    if (fType == kGPU_DeviceType) {

        SkASSERT(NULL != fContext);
        fContext->flush();
    }
    if (fType == kRaster_DeviceType) {
        // need to send the raster bits to the (gpu) window
        fContext->setRenderTarget(fRenderTarget);
        const SkBitmap& bm = getBitmap();
        fRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
                                      kSkia8888_GrPixelConfig,
                                      bm.getPixels(),
                                      bm.rowBytes());
    }
    INHERITED::present();
}

void SkExampleWindow::onSizeChange() {
    setupRenderTarget();
}

#ifdef SK_BUILD_FOR_WIN
void SkExampleWindow::onHandleInval(const SkIRect& rect) {
    RECT winRect;
    winRect.top = rect.top();
    winRect.bottom = rect.bottom();
    winRect.right = rect.right();
    winRect.left = rect.left();
    InvalidateRect((HWND)this->getHWND(), &winRect, false);
}
#endif

bool SkExampleWindow::findNextMatch() {
    bool found = false;
    // Avoid infinite loop by knowing where we started.
    const SkExample::Registry* begin = fRegistry;
    while (!found) {
        fRegistry = fRegistry->next();
        if (NULL == fRegistry) {  // Reached the end of the registered samples. GOTO head.
            fRegistry = SkExample::Registry::Head();
        }
        SkExample* next = fRegistry->factory()(this);
        if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, next->getName().c_str())) {
            fCurrExample = next;
            found = true;
        }
        if (begin == fRegistry) {  // We looped through every sample without finding anything.
            break;
        }
    }
    return found;
}

bool SkExampleWindow::onHandleChar(SkUnichar unichar) {
    if ('n' == unichar) {
        bool found = findNextMatch();
        if (!found) {
            SkDebugf("No SkExample that matches your query\n");
        }
    }
    return true;
}

SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
    SkCommandLineFlags::Parse(argc, argv);
    return new SkExampleWindow(hwnd);
}
<commit_msg>fix the build error of SkiaExample -- use setColorType, not setConfig<commit_after>/*
 * Copyright 2013 Google Inc.
 *
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 */

#include "SkExample.h"

#include "gl/GrGLUtil.h"
#include "gl/GrGLDefines.h"
#include "gl/GrGLInterface.h"
#include "SkApplication.h"
#include "SkCommandLineFlags.h"
#include "SkGpuDevice.h"
#include "SkGraphics.h"

DEFINE_string2(match, m, NULL, "[~][^]substring[$] [...] of test name to run.\n" \
                               "Multiple matches may be separated by spaces.\n" \
                               "~ causes a matching test to always be skipped\n" \
                               "^ requires the start of the test to match\n" \
                               "$ requires the end of the test to match\n" \
                               "^ and $ requires an exact match\n" \
                               "If a test does not match any list entry,\n" \
                               "it is skipped unless some list entry starts with ~");

void application_init() {
    SkGraphics::Init();
    SkEvent::Init();
}

void application_term() {
    SkEvent::Term();
    SkGraphics::Term();
}

SkExampleWindow::SkExampleWindow(void* hwnd)
    : INHERITED(hwnd) {
    fRegistry = SkExample::Registry::Head();
    fCurrExample = fRegistry->factory()(this);

    if (FLAGS_match.count()) {
        // Start with the a matching sample if possible.
        bool found = this->findNextMatch();
        if (!found) {
            SkDebugf("No matching SkExample found.\n");
        }
    }
}

void SkExampleWindow::tearDownBackend() {
  if (kGPU_DeviceType == fType) {
        SkSafeUnref(fContext);
        fContext = NULL;

        SkSafeUnref(fInterface);
        fInterface = NULL;

        SkSafeUnref(fRenderTarget);
        fRenderTarget = NULL;

        detach();
    }
}

bool SkExampleWindow::setupBackend(DeviceType type) {
    fType = type;

    this->setColorType(kRGBA_8888_SkColorType);
    this->setVisibleP(true);
    this->setClipToBounds(false);

    bool result = attach(kNativeGL_BackEndType, 0 /*msaa*/, &fAttachmentInfo);
    if (false == result) {
        SkDebugf("Not possible to create backend.\n");
        detach();
        return false;
    }

    fInterface = GrGLCreateNativeInterface();

    SkASSERT(NULL != fInterface);

    fContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext)fInterface);
    SkASSERT(NULL != fContext);

    setupRenderTarget();

    return true;
}

void SkExampleWindow::setupRenderTarget() {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(width());
    desc.fHeight = SkScalarRoundToInt(height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    desc.fSampleCnt = fAttachmentInfo.fSampleCount;
    desc.fStencilBits = fAttachmentInfo.fStencilBits;

    GrGLint buffer;
    GR_GL_GetIntegerv(fInterface, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    fRenderTarget = fContext->wrapBackendRenderTarget(desc);

    fContext->setRenderTarget(fRenderTarget);
}

SkCanvas* SkExampleWindow::createCanvas() {
    if (fType == kGPU_DeviceType) {
        if (NULL != fContext && NULL != fRenderTarget) {
            SkAutoTUnref<SkBaseDevice> device(new SkGpuDevice(fContext, fRenderTarget));
            return new SkCanvas(device);
        }
        tearDownBackend();
        setupBackend(kRaster_DeviceType);
    }
    return INHERITED::createCanvas();
}

void SkExampleWindow::draw(SkCanvas* canvas) {
    if (NULL != fCurrExample) {
        fCurrExample->draw(canvas);
    }
    if (fType == kGPU_DeviceType) {

        SkASSERT(NULL != fContext);
        fContext->flush();
    }
    if (fType == kRaster_DeviceType) {
        // need to send the raster bits to the (gpu) window
        fContext->setRenderTarget(fRenderTarget);
        const SkBitmap& bm = getBitmap();
        fRenderTarget->writePixels(0, 0, bm.width(), bm.height(),
                                      kSkia8888_GrPixelConfig,
                                      bm.getPixels(),
                                      bm.rowBytes());
    }
    INHERITED::present();
}

void SkExampleWindow::onSizeChange() {
    setupRenderTarget();
}

#ifdef SK_BUILD_FOR_WIN
void SkExampleWindow::onHandleInval(const SkIRect& rect) {
    RECT winRect;
    winRect.top = rect.top();
    winRect.bottom = rect.bottom();
    winRect.right = rect.right();
    winRect.left = rect.left();
    InvalidateRect((HWND)this->getHWND(), &winRect, false);
}
#endif

bool SkExampleWindow::findNextMatch() {
    bool found = false;
    // Avoid infinite loop by knowing where we started.
    const SkExample::Registry* begin = fRegistry;
    while (!found) {
        fRegistry = fRegistry->next();
        if (NULL == fRegistry) {  // Reached the end of the registered samples. GOTO head.
            fRegistry = SkExample::Registry::Head();
        }
        SkExample* next = fRegistry->factory()(this);
        if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, next->getName().c_str())) {
            fCurrExample = next;
            found = true;
        }
        if (begin == fRegistry) {  // We looped through every sample without finding anything.
            break;
        }
    }
    return found;
}

bool SkExampleWindow::onHandleChar(SkUnichar unichar) {
    if ('n' == unichar) {
        bool found = findNextMatch();
        if (!found) {
            SkDebugf("No SkExample that matches your query\n");
        }
    }
    return true;
}

SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
    SkCommandLineFlags::Parse(argc, argv);
    return new SkExampleWindow(hwnd);
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkCommon.h>
#include <chrono>
#include <mitkIOUtil.h>
#include <mitkCommandLineParser.h>
#include <mitkException.h>

#include <mitkPhotoacousticImage.h>
#include <mitkPhotoacousticBeamformingSettings.h>

#include <itksys/SystemTools.hxx>

struct InputParameters
{
  mitk::Image::Pointer inputImage;
  std::string outputFilename;
  bool verbose;
  int speedOfSound;
  int cutoff;
  float angle;
  int samples;
  mitk::BeamformingSettings::BeamformingAlgorithm algorithm;
};

InputParameters parseInput(int argc, char* argv[])
{
  mitkCommandLineParser parser;
  parser.setCategory("MITK-Photoacoustics");
  parser.setTitle("Mitk Photoacoustics Beamforming Tool");
  parser.setDescription("Reads a nrrd file as an input and applies a beamforming method as set with the parameters.");
  parser.setContributor("Computer Assisted Medical Interventions, DKFZ");

  parser.setArgumentPrefix("--", "-");

  parser.beginGroup("Required parameters");
  parser.addArgument(
    "inputImage", "i", mitkCommandLineParser::InputImage,
    "Input image (mitk::Image)", "input image (.nrrd file)",
    us::Any(), false);
  parser.addArgument(
    "output", "o", mitkCommandLineParser::OutputFile,
    "Output filename", "output image (.nrrd file)",
    us::Any(), false);
  parser.endGroup();

  parser.beginGroup("Optional parameters");
  parser.addArgument(
    "verbose", "v", mitkCommandLineParser::Bool,
    "Verbose Output", "Whether to produce verbose, or rather debug output. (default: false)");
  parser.addArgument(
    "speed-of-sound", "sos", mitkCommandLineParser::Int,
    "Speed of Sound [m/s]", "The average speed of sound as assumed for the reconstruction in [m/s]. (default: 1500)");
  parser.addArgument(
    "cutoff", "co", mitkCommandLineParser::Int,
    "cutoff margin on the top of the image [pixels]", "The number of pixels to be ignored for this filter in [pixels] (default: 0).");
  parser.addArgument(
    "angle", "a", mitkCommandLineParser::Float,
    "field of view of the transducer elements [degrees]", "The field of view of each individual transducer element [degrees] (default: 27).");
  parser.addArgument(
    "samples", "s", mitkCommandLineParser::Int,
    "samples per reconstruction line [pixels]", "The pixels along the y axis in the beamformed image [pixels] (default: 2048).");
  parser.addArgument(
    "algorithm", "alg", mitkCommandLineParser::String,
    "one of [\"DAS\", \"DMAS\", \"sDMAS\"]", "The beamforming algorithm to be used for reconstruction (default: DAS).");
  parser.endGroup();

  InputParameters input;

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
  if (parsedArgs.size() == 0)
    exit(-1);

  if (parsedArgs.count("verbose"))
  {
    input.verbose = true;
  }
  else
  {
    input.verbose = false;
  }
  MITK_INFO(input.verbose) << "### VERBOSE OUTPUT ENABLED ###";

  if (parsedArgs.count("inputImage"))
  {
    MITK_INFO(input.verbose) << "Reading input image...";
    input.inputImage = mitk::IOUtil::Load<mitk::Image>(us::any_cast<std::string>(parsedArgs["inputImage"]));
    MITK_INFO(input.verbose) << "Reading input image...[Done]";
  }
  else
  {
    mitkThrow() << "No input image given.";
  }

  if (parsedArgs.count("output"))
  {
    input.outputFilename = us::any_cast<std::string>(parsedArgs["output"]);
  }
  else
  {
    mitkThrow() << "No output image path given..";
  }

  if (parsedArgs.count("speed-of-sound"))
  {
    input.speedOfSound = us::any_cast<int>(parsedArgs["speed-of-sound"]);
  }
  else
  {
    input.speedOfSound = 1500;
  }

  if (parsedArgs.count("cutoff"))
  {
    input.cutoff = us::any_cast<int>(parsedArgs["cutoff"]);
  }
  else
  {
    input.cutoff = 0;
  }

  if (parsedArgs.count("angle"))
  {
    input.angle = us::any_cast<float>(parsedArgs["angle"]);
  }
  else
  {
    input.angle = 27;
  }

  if (parsedArgs.count("samples"))
  {
    input.samples = us::any_cast<int>(parsedArgs["samples"]);
  }
  else
  {
    input.samples = 2048;
  }

  if (parsedArgs.count("algorithm"))
  {
    std::string algorithm = us::any_cast<std::string>(parsedArgs["algorithm"]);
    MITK_INFO(input.verbose) << "Parsing algorithm: " << algorithm;
    if (algorithm == "DAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    else if (algorithm == "DMAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DMAS;
    else if (algorithm == "sDMAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS;
    else
    {
      MITK_INFO(input.verbose) << "Not a valid beamforming algorithm: " << algorithm << " Reverting to DAS";
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    }

    MITK_INFO(input.verbose) << "Sucessfully set algorithm: " << algorithm;
  }
  else
  {
    input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    MITK_INFO(input.verbose) << "No matching algorithm found. Using DAS.";
  }

  return input;
}

mitk::BeamformingSettings ParseSettings(InputParameters &input)
{
  mitk::BeamformingSettings outputSettings;

  outputSettings.Algorithm = input.algorithm;
  outputSettings.Apod = mitk::BeamformingSettings::Apodization::Box;
  outputSettings.SpeedOfSound = input.speedOfSound;
  outputSettings.TimeSpacing = input.inputImage->GetGeometry()->GetSpacing()[1] / 1000000;
  outputSettings.RecordTime = input.inputImage->GetDimension(1)*input.inputImage->GetGeometry()->GetSpacing()[1] / 1000000; // [s]
  outputSettings.UseGPU = false;
  outputSettings.upperCutoff = input.cutoff;
  outputSettings.DelayCalculationMethod = mitk::BeamformingSettings::DelayCalc::Spherical;
  outputSettings.Angle = input.angle;
  outputSettings.Pitch = input.inputImage->GetGeometry()->GetSpacing()[0] / 1000;
  outputSettings.TransducerElements = input.inputImage->GetDimension(0);
  outputSettings.ReconstructionLines = input.inputImage->GetDimension(0);
  outputSettings.SamplesPerLine = input.samples;
  outputSettings.isPhotoacousticImage = true;
  outputSettings.partial = false;
  outputSettings.apodizationArraySize = input.inputImage->GetDimension(0);
  outputSettings.UseBP = false;

  return outputSettings;
}

int main(int argc, char * argv[])
{
  auto input = parseInput(argc, argv);

  MITK_INFO(input.verbose) << "Beamforming input image...";

  mitk::PhotoacousticImage::Pointer m_BeamformingFilter = mitk::PhotoacousticImage::New();

  mitk::BeamformingSettings settings = ParseSettings(input);

  std::string message = "Test";

  auto output = m_BeamformingFilter->ApplyBeamforming(input.inputImage, settings, message);
  MITK_INFO(input.verbose) << "Applying BModeFilter to image...";
  output = m_BeamformingFilter->ApplyBmodeFilter(output, mitk::PhotoacousticImage::Abs, false, false, 0.3);
  MITK_INFO(input.verbose) << "Applying BModeFilter to image...[Done]";

  MITK_INFO(input.verbose) << "Saving image...";
  mitk::IOUtil::Save(output, input.outputFilename);
  MITK_INFO(input.verbose) << "Saving image...[Done]";

  MITK_INFO(input.verbose) << "Beamforming input image...[Done]";
}
<commit_msg>rename changes from photoacousticimage to photoacousticFilterservice<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkCommon.h>
#include <chrono>
#include <mitkIOUtil.h>
#include <mitkCommandLineParser.h>
#include <mitkException.h>

#include <mitkPhotoacousticFilterService.h>
#include <mitkPhotoacousticBeamformingSettings.h>

#include <itksys/SystemTools.hxx>

struct InputParameters
{
  mitk::Image::Pointer inputImage;
  std::string outputFilename;
  bool verbose;
  int speedOfSound;
  int cutoff;
  float angle;
  int samples;
  mitk::BeamformingSettings::BeamformingAlgorithm algorithm;
};

InputParameters parseInput(int argc, char* argv[])
{
  mitkCommandLineParser parser;
  parser.setCategory("MITK-Photoacoustics");
  parser.setTitle("Mitk Photoacoustics Beamforming Tool");
  parser.setDescription("Reads a nrrd file as an input and applies a beamforming method as set with the parameters.");
  parser.setContributor("Computer Assisted Medical Interventions, DKFZ");

  parser.setArgumentPrefix("--", "-");

  parser.beginGroup("Required parameters");
  parser.addArgument(
    "inputImage", "i", mitkCommandLineParser::InputImage,
    "Input image (mitk::Image)", "input image (.nrrd file)",
    us::Any(), false);
  parser.addArgument(
    "output", "o", mitkCommandLineParser::OutputFile,
    "Output filename", "output image (.nrrd file)",
    us::Any(), false);
  parser.endGroup();

  parser.beginGroup("Optional parameters");
  parser.addArgument(
    "verbose", "v", mitkCommandLineParser::Bool,
    "Verbose Output", "Whether to produce verbose, or rather debug output. (default: false)");
  parser.addArgument(
    "speed-of-sound", "sos", mitkCommandLineParser::Int,
    "Speed of Sound [m/s]", "The average speed of sound as assumed for the reconstruction in [m/s]. (default: 1500)");
  parser.addArgument(
    "cutoff", "co", mitkCommandLineParser::Int,
    "cutoff margin on the top of the image [pixels]", "The number of pixels to be ignored for this filter in [pixels] (default: 0).");
  parser.addArgument(
    "angle", "a", mitkCommandLineParser::Float,
    "field of view of the transducer elements [degrees]", "The field of view of each individual transducer element [degrees] (default: 27).");
  parser.addArgument(
    "samples", "s", mitkCommandLineParser::Int,
    "samples per reconstruction line [pixels]", "The pixels along the y axis in the beamformed image [pixels] (default: 2048).");
  parser.addArgument(
    "algorithm", "alg", mitkCommandLineParser::String,
    "one of [\"DAS\", \"DMAS\", \"sDMAS\"]", "The beamforming algorithm to be used for reconstruction (default: DAS).");
  parser.endGroup();

  InputParameters input;

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
  if (parsedArgs.size() == 0)
    exit(-1);

  if (parsedArgs.count("verbose"))
  {
    input.verbose = true;
  }
  else
  {
    input.verbose = false;
  }
  MITK_INFO(input.verbose) << "### VERBOSE OUTPUT ENABLED ###";

  if (parsedArgs.count("inputImage"))
  {
    MITK_INFO(input.verbose) << "Reading input image...";
    input.inputImage = mitk::IOUtil::Load<mitk::Image>(us::any_cast<std::string>(parsedArgs["inputImage"]));
    MITK_INFO(input.verbose) << "Reading input image...[Done]";
  }
  else
  {
    mitkThrow() << "No input image given.";
  }

  if (parsedArgs.count("output"))
  {
    input.outputFilename = us::any_cast<std::string>(parsedArgs["output"]);
  }
  else
  {
    mitkThrow() << "No output image path given..";
  }

  if (parsedArgs.count("speed-of-sound"))
  {
    input.speedOfSound = us::any_cast<int>(parsedArgs["speed-of-sound"]);
  }
  else
  {
    input.speedOfSound = 1500;
  }

  if (parsedArgs.count("cutoff"))
  {
    input.cutoff = us::any_cast<int>(parsedArgs["cutoff"]);
  }
  else
  {
    input.cutoff = 0;
  }

  if (parsedArgs.count("angle"))
  {
    input.angle = us::any_cast<float>(parsedArgs["angle"]);
  }
  else
  {
    input.angle = 27;
  }

  if (parsedArgs.count("samples"))
  {
    input.samples = us::any_cast<int>(parsedArgs["samples"]);
  }
  else
  {
    input.samples = 2048;
  }

  if (parsedArgs.count("algorithm"))
  {
    std::string algorithm = us::any_cast<std::string>(parsedArgs["algorithm"]);
    MITK_INFO(input.verbose) << "Parsing algorithm: " << algorithm;
    if (algorithm == "DAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    else if (algorithm == "DMAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DMAS;
    else if (algorithm == "sDMAS")
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS;
    else
    {
      MITK_INFO(input.verbose) << "Not a valid beamforming algorithm: " << algorithm << " Reverting to DAS";
      input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    }

    MITK_INFO(input.verbose) << "Sucessfully set algorithm: " << algorithm;
  }
  else
  {
    input.algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;
    MITK_INFO(input.verbose) << "No matching algorithm found. Using DAS.";
  }

  return input;
}

mitk::BeamformingSettings ParseSettings(InputParameters &input)
{
  mitk::BeamformingSettings outputSettings;

  outputSettings.Algorithm = input.algorithm;
  outputSettings.Apod = mitk::BeamformingSettings::Apodization::Box;
  outputSettings.SpeedOfSound = input.speedOfSound;
  outputSettings.TimeSpacing = input.inputImage->GetGeometry()->GetSpacing()[1] / 1000000;
  outputSettings.RecordTime = input.inputImage->GetDimension(1)*input.inputImage->GetGeometry()->GetSpacing()[1] / 1000000; // [s]
  outputSettings.UseGPU = false;
  outputSettings.upperCutoff = input.cutoff;
  outputSettings.DelayCalculationMethod = mitk::BeamformingSettings::DelayCalc::Spherical;
  outputSettings.Angle = input.angle;
  outputSettings.Pitch = input.inputImage->GetGeometry()->GetSpacing()[0] / 1000;
  outputSettings.TransducerElements = input.inputImage->GetDimension(0);
  outputSettings.ReconstructionLines = input.inputImage->GetDimension(0);
  outputSettings.SamplesPerLine = input.samples;
  outputSettings.isPhotoacousticImage = true;
  outputSettings.partial = false;
  outputSettings.apodizationArraySize = input.inputImage->GetDimension(0);
  outputSettings.UseBP = false;

  return outputSettings;
}

int main(int argc, char * argv[])
{
  auto input = parseInput(argc, argv);

  MITK_INFO(input.verbose) << "Beamforming input image...";

  mitk::PhotoacousticFilterService::Pointer m_BeamformingService = mitk::PhotoacousticFilterService::New();

  mitk::BeamformingSettings settings = ParseSettings(input);

  std::string message = "Test";

  auto output = m_BeamformingService->ApplyBeamforming(input.inputImage, settings, message);
  MITK_INFO(input.verbose) << "Applying BModeFilter to image...";
  output = m_BeamformingService->ApplyBmodeFilter(output, mitk::PhotoacousticFilterService::Abs, false, false, 0.3);
  MITK_INFO(input.verbose) << "Applying BModeFilter to image...[Done]";

  MITK_INFO(input.verbose) << "Saving image...";
  mitk::IOUtil::Save(output, input.outputFilename);
  MITK_INFO(input.verbose) << "Saving image...[Done]";

  MITK_INFO(input.verbose) << "Beamforming input image...[Done]";
}
<|endoftext|>


<commit_before>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the ‘Software’), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 *****************************************************************************/
#include <_mapnik_geometry.rb.h>

// Rice
#include <rice/Data_Type.hpp>
#include <rice/Constructor.hpp>
#include <rice/Class.hpp>
#include <rice/Enum.hpp>

// Mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/wkt/wkt_factory.hpp>

namespace{
  // Borrowed from the python bindings...
  mapnik::geometry_type * make_from_wkt(std::string const& wkt) {
    std::pair<bool,mapnik::geometry_type*> result = mapnik::from_wkt(wkt);
    if (result.first){
      return result.second;
    }
    throw std::runtime_error("Failed to parse WKT");
  }

}

Rice::Enum<mapnik::eGeomType> geometry_enum;

template<>
mapnik::eGeomType from_ruby<mapnik::eGeomType>(Rice::Object x) {
  Rice::Data_Object<mapnik::eGeomType> d(x, geometry_enum);
  return *d;
}

void register_geometry(Rice::Module rb_mapnik){
  /*
    @@Module_var rb_mapnik = Mapnik
  */
  geometry_enum = Rice::define_enum<mapnik::eGeomType>("GeometryType", rb_mapnik);
  geometry_enum.define_value("Point",mapnik::Point);
  geometry_enum.define_value("LineString",mapnik::LineString);
  geometry_enum.define_value("Polygon",mapnik::Polygon);
  geometry_enum.define_value("MultiPoint",mapnik::MultiPoint);
  geometry_enum.define_value("MultiLineString",mapnik::MultiLineString);
  geometry_enum.define_value("MultiPolygon",mapnik::MultiPolygon);

  Rice::Data_Type< mapnik::geometry_type > rb_cgeometry2d = Rice::define_class_under< mapnik::geometry_type >(rb_mapnik, "Geometry2d");
  rb_cgeometry2d.define_singleton_method("from_wkt", &make_from_wkt, Rice::Arg("wkt"));
  rb_cgeometry2d.define_method("envelope", &mapnik::geometry_type::envelope);
  rb_cgeometry2d.define_method("type", &mapnik::geometry_type::type);
  rb_cgeometry2d.define_method("area", &mapnik::geometry_type::area);
}

<commit_msg>fix geometry compile (TODO - fix tests once its is clear where the mapnik.Path/Geometry api is going in Mapnik 2.1) - closes #5<commit_after>/*****************************************************************************
Copyright (C) 2011 Elliot Laster

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the ‘Software’), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 *****************************************************************************/
#include <_mapnik_geometry.rb.h>

// Rice
#include <rice/Data_Type.hpp>
#include <rice/Constructor.hpp>
#include <rice/Class.hpp>
#include <rice/Enum.hpp>

// Mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/wkt/wkt_factory.hpp>

namespace{

  typedef boost::ptr_vector<mapnik::geometry_type> path_type;

  // Borrowed from the python bindings...
  void from_wkt_impl(path_type& p, std::string const& wkt)
  {
      bool result = mapnik::from_wkt(wkt, p);
      if (!result) throw std::runtime_error("Failed to parse WKT");
  }

/*
  mapnik::geometry_type * from_wkt_impl(std::string const& wkt) {
    std::pair<bool,mapnik::geometry_type*> result = mapnik::from_wkt(wkt);
    if (result.first){
      return result.second;
    }
    throw std::runtime_error("Failed to parse WKT");
  }
*/

}

Rice::Enum<mapnik::eGeomType> geometry_enum;

template<>
mapnik::eGeomType from_ruby<mapnik::eGeomType>(Rice::Object x) {
  Rice::Data_Object<mapnik::eGeomType> d(x, geometry_enum);
  return *d;
}

void register_geometry(Rice::Module rb_mapnik){
  /*
    @@Module_var rb_mapnik = Mapnik
  */
  geometry_enum = Rice::define_enum<mapnik::eGeomType>("GeometryType", rb_mapnik);
  geometry_enum.define_value("Point",mapnik::Point);
  geometry_enum.define_value("LineString",mapnik::LineString);
  geometry_enum.define_value("Polygon",mapnik::Polygon);
  geometry_enum.define_value("MultiPoint",mapnik::MultiPoint);
  geometry_enum.define_value("MultiLineString",mapnik::MultiLineString);
  geometry_enum.define_value("MultiPolygon",mapnik::MultiPolygon);

  Rice::Data_Type< mapnik::geometry_type > rb_cgeometry2d = Rice::define_class_under< mapnik::geometry_type >(rb_mapnik, "Geometry2d");
  rb_cgeometry2d.define_method("envelope", &mapnik::geometry_type::envelope);
  rb_cgeometry2d.define_method("type", &mapnik::geometry_type::type);
  rb_cgeometry2d.define_method("area", &mapnik::geometry_type::area);

  Rice::Data_Type< path_type > rb_cpath = Rice::define_class_under< path_type >(rb_mapnik, "Path");
  rb_cpath.define_singleton_method("from_wkt", &from_wkt_impl, Rice::Arg("wkt"));
}

<|endoftext|>