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

#include "base/keyboard_codes.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/find_bar_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_unittest.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"

namespace {

// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const wchar_t kDocRoot[] = L"chrome/test/data";
static const wchar_t kSimplePage[] = L"404_is_enough_for_us.html";

class FindInPageTest : public InProcessBrowserTest {
 public:
  FindInPageTest() {
    set_show_window(true);
    FindBarHost::disable_animations_during_testing_ = true;
  }

  void ClickOnView(ViewID view_id) {
    BrowserWindow* browser_window = browser()->window();
    ASSERT_TRUE(browser_window);
#if defined(TOOLKIT_VIEWS)
    views::View* view =
        reinterpret_cast<BrowserView*>(browser_window)->GetViewByID(view_id);
#elif defined(OS_LINUX)
    gfx::NativeWindow window = browser_window->GetNativeHandle();
    ASSERT_TRUE(window);
    GtkWidget* view = ViewIDUtil::GetWidget(GTK_WIDGET(window), view_id);
#endif
    ASSERT_TRUE(view);
    ui_controls::MoveMouseToCenterAndPress(view,
                                           ui_controls::LEFT,
                                           ui_controls::DOWN | ui_controls::UP,
                                           new MessageLoop::QuitTask());
    ui_test_utils::RunMessageLoop();
  }

  int GetFocusedViewID() {
#if defined(TOOLKIT_VIEWS)
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManagerForNativeView(
            browser()->window()->GetNativeHandle());
    if (!focus_manager) {
      NOTREACHED();
      return -1;
    }
    views::View* focused_view = focus_manager->GetFocusedView();
    if (!focused_view)
      return -1;
    return focused_view->GetID();
#else
    return -1;
#endif
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  // First we navigate to our test page (tab A).
  GURL url = server->TestServerPageW(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();

  // Open another tab (tab B).
  browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, -1,
                           false, NULL);

  browser()->Find();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());

  // Select tab A.
  browser()->SelectTabContentsAt(0, true);

  // Close tab B.
  browser()->CloseTabContents(browser()->GetTabContentsAt(1));

  // Click on the location bar so that Find box loses focus.
  ClickOnView(VIEW_ID_LOCATION_BAR);
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
  // Check the location bar is focused.
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
#endif

  // This used to crash until bug 1303709 was fixed.
  ui_controls::SendKeyPressNotifyWhenDone(
      browser()->window()->GetNativeHandle(), base::VKEY_ESCAPE,
      true, false, false, new MessageLoop::QuitTask());
  ui_test_utils::RunMessageLoop();
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  GURL url = server->TestServerPageW(L"title1.html");
  ui_test_utils::NavigateToURL(browser(), url);

  // Focus the location bar, open and close the find-in-page, focus should
  // return to the location bar.
  browser()->FocusLocationBar();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
  browser()->find_bar()->Show();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());

  // Focus the location bar, find something on the page, close the find box,
  // focus should go to the page.
  browser()->FocusLocationBar();
  browser()->Find();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  ui_test_utils::FindInPage(browser()->GetSelectedTabContents(),
                            L"a", true, false, NULL);
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW, GetFocusedViewID());

  // Focus the location bar, open and close the find box, focus should return to
  // the location bar (same as before, just checking that http://crbug.com/23599
  // is fixed).
  browser()->FocusLocationBar();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
  browser()->find_bar()->Show();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
}
<commit_msg>Disable FindInPageTest.FocusRestore, which is killing the Interactive Tests bot<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/keyboard_codes.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/find_bar_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_unittest.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"

namespace {

// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const wchar_t kDocRoot[] = L"chrome/test/data";
static const wchar_t kSimplePage[] = L"404_is_enough_for_us.html";

class FindInPageTest : public InProcessBrowserTest {
 public:
  FindInPageTest() {
    set_show_window(true);
    FindBarHost::disable_animations_during_testing_ = true;
  }

  void ClickOnView(ViewID view_id) {
    BrowserWindow* browser_window = browser()->window();
    ASSERT_TRUE(browser_window);
#if defined(TOOLKIT_VIEWS)
    views::View* view =
        reinterpret_cast<BrowserView*>(browser_window)->GetViewByID(view_id);
#elif defined(OS_LINUX)
    gfx::NativeWindow window = browser_window->GetNativeHandle();
    ASSERT_TRUE(window);
    GtkWidget* view = ViewIDUtil::GetWidget(GTK_WIDGET(window), view_id);
#endif
    ASSERT_TRUE(view);
    ui_controls::MoveMouseToCenterAndPress(view,
                                           ui_controls::LEFT,
                                           ui_controls::DOWN | ui_controls::UP,
                                           new MessageLoop::QuitTask());
    ui_test_utils::RunMessageLoop();
  }

  int GetFocusedViewID() {
#if defined(TOOLKIT_VIEWS)
    views::FocusManager* focus_manager =
        views::FocusManager::GetFocusManagerForNativeView(
            browser()->window()->GetNativeHandle());
    if (!focus_manager) {
      NOTREACHED();
      return -1;
    }
    views::View* focused_view = focus_manager->GetFocusedView();
    if (!focused_view)
      return -1;
    return focused_view->GetID();
#else
    return -1;
#endif
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  // First we navigate to our test page (tab A).
  GURL url = server->TestServerPageW(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();

  // Open another tab (tab B).
  browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED, true, -1,
                           false, NULL);

  browser()->Find();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());

  // Select tab A.
  browser()->SelectTabContentsAt(0, true);

  // Close tab B.
  browser()->CloseTabContents(browser()->GetTabContentsAt(1));

  // Click on the location bar so that Find box loses focus.
  ClickOnView(VIEW_ID_LOCATION_BAR);
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
  // Check the location bar is focused.
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
#endif

  // This used to crash until bug 1303709 was fixed.
  ui_controls::SendKeyPressNotifyWhenDone(
      browser()->window()->GetNativeHandle(), base::VKEY_ESCAPE,
      true, false, false, new MessageLoop::QuitTask());
  ui_test_utils::RunMessageLoop();
}

// TODO: http://crbug.com/26231
IN_PROC_BROWSER_TEST_F(FindInPageTest, DISABLED_FocusRestore) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  GURL url = server->TestServerPageW(L"title1.html");
  ui_test_utils::NavigateToURL(browser(), url);

  // Focus the location bar, open and close the find-in-page, focus should
  // return to the location bar.
  browser()->FocusLocationBar();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
  browser()->find_bar()->Show();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());

  // Focus the location bar, find something on the page, close the find box,
  // focus should go to the page.
  browser()->FocusLocationBar();
  browser()->Find();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  ui_test_utils::FindInPage(browser()->GetSelectedTabContents(),
                            L"a", true, false, NULL);
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW, GetFocusedViewID());

  // Focus the location bar, open and close the find box, focus should return to
  // the location bar (same as before, just checking that http://crbug.com/23599
  // is fixed).
  browser()->FocusLocationBar();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
  browser()->find_bar()->Show();
  EXPECT_EQ(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD, GetFocusedViewID());
  browser()->find_bar()->EndFindSession();
  EXPECT_EQ(VIEW_ID_LOCATION_BAR, GetFocusedViewID());
}
<|endoftext|>


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

  This file is distributed under the MIT License.
  See https://github.com/morzhovets/momo/blob/master/LICENSE
  for details.

  tests/SimpleTreeTester.cpp

\**********************************************************/

#include "pch.h"
#include "TestSettings.h"

#ifdef TEST_SIMPLE_TREE

#undef NDEBUG

#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"
#include "../../momo/stdish/pool_allocator.h"

#include <string>
#include <iostream>
#include <random>
#include <map>

class SimpleTreeTester
{
private:
	template<bool isNothrowMoveConstructible, bool isNothrowSwappable, bool isNothrowCopyAssignable>
	class TemplItem
	{
	public:
		explicit TemplItem(unsigned char c = unsigned char{0}) noexcept
			: mChar(c)
		{
		}

		TemplItem(TemplItem&& item) noexcept(isNothrowMoveConstructible)
			: mChar(item.mChar)
		{
		}

		TemplItem(const TemplItem& item) noexcept(false)
			: mChar(item.mChar)
		{
		}

		~TemplItem() = default;

		//TemplItem& operator=(TemplItem&& item) = delete;

		TemplItem& operator=(const TemplItem& item) noexcept(isNothrowCopyAssignable)
		{
			mChar = item.mChar;
			return *this;
		}

		friend void swap(TemplItem& item1, TemplItem& item2) noexcept(isNothrowSwappable)
		{
			std::swap(item1.mChar, item2.mChar);
		}

		bool operator==(const TemplItem& item) const noexcept
		{
			return mChar == item.mChar;
		}

		bool operator<(const TemplItem& item) const noexcept
		{
			return mChar < item.mChar;
		}

	private:
		unsigned char mChar;
	};

public:
	static void TestStrAll()
	{
		std::cout << "momo::TreeSet: " << std::flush;
		TestStrTreeSet();
		std::cout << "ok" << std::endl;

		std::cout << "momo::TreeMap: " << std::flush;
		TestStrTreeMap();
		std::cout << "ok" << std::endl;
	}

	static void TestStrTreeSet()
	{
		typedef momo::TreeSet<std::string> TreeSet;

		std::string s1 = "s1";
		std::string s2 = "s2";

		TreeSet set = { s2, "s3" };
		set.InsertVar(s1, "s1");

		assert(set.GetCount() == 3);
		assert(set.ContainsKey(s1));
		assert(set.ContainsKey("s2"));

		set.ResetKey(set.GetLowerBound("s1"), s1);
		set.ResetKey(set.GetUpperBound(s1), "s2");

		const auto es = set.Extract(set.Find("s1"));
		assert(es.GetItem() == s1);

		assert(set.GetCount() == 2);
		assert(*set.GetBegin() == s2);
		assert(*std::prev(set.GetEnd()) == "s3");

		TreeSet set2;
		set2 = set;
		assert(std::equal(set.GetBegin(), set.GetEnd(), set2.GetBegin()));
	}

	static void TestStrTreeMap()
	{
		typedef momo::TreeMap<std::string, std::string> TreeMap;
		typedef TreeMap::ConstIterator::Reference Reference;
		auto pred = [] (Reference ref1, Reference ref2)
			{ return ref1.key == ref2.key && ref1.value == ref2.value; };

		std::string s1 = "s1";
		std::string s2 = "s2";
		std::string s3 = "s3";
		std::string s4 = "s4";

		TreeMap map = { { "s1", "s1" }, { "s2", s2 } };
		map.InsertCrt("s3", [] (void* ptr) { ::new(ptr) std::string("s3"); });
		map.InsertCrt(s4, [] (void* ptr) { ::new(ptr) std::string("s4"); });

		map.Insert("s1", "s2");
		map.Insert("s2", s3);
		map.Insert(s3, "s4");
		map.Insert(s4, s1);

		map.ResetKey(map.GetLowerBound("s1"), s1);
		map.ResetKey(map.GetUpperBound(s1), "s2");

		assert(map.GetCount() == 4);
		for (auto ref : map)
			assert(ref.key == ref.value);

		TreeMap map2;
		map2 = map;

		const auto ep = map.Extract(map.Find("s1"));
		assert(ep.GetKey() == s1 && ep.GetValue() == s1);
		assert(map.GetCount() == 3);

		map.Insert(map2.GetBegin(), std::next(map2.GetBegin()));
		assert(std::equal(map.GetBegin(), map.GetEnd(), map2.GetBegin(), pred));

		map.Clear();
		assert(map.IsEmpty());

		map.Add(map.GetLowerBound("s1"), s1, s1);
		map.Add(map.GetUpperBound("s2"), s2, "s2");
		map.Add(map.GetLowerBound(s3), "s3", s3);
		map.Add(map.GetUpperBound(s4), "s4", "s4");
		assert(std::equal(map.GetBegin(), map.GetEnd(), map2.GetBegin(), pred));
	}

	static void TestTemplAll()
	{
		std::mt19937 mt;

		TestTemplTreeNode<  1, 1, 127, 0, 0>(mt);
		TestTemplTreeNode<  2, 1,  66, 0, 1>(mt);
		TestTemplTreeNode<  3, 1,  32, 0, 2>(mt);
		TestTemplTreeNode<  4, 1,  15, 0, 3>(mt);
		TestTemplTreeNode<  5, 1,   1, 1, 0>(mt);
		TestTemplTreeNode< 10, 1,   3, 1, 1>(mt);
		TestTemplTreeNode<101, 1,   2, 1, 2>(mt);
		TestTemplTreeNode<255, 1,   1, 1, 3>(mt);

		TestTemplTreeNode<  4, 2, 127, 2, 0>(mt);
		TestTemplTreeNode<  5, 2,  66, 2, 1>(mt);
		TestTemplTreeNode<  6, 2,  32, 2, 2>(mt);
		TestTemplTreeNode<  7, 2,  15, 2, 3>(mt);
		TestTemplTreeNode< 14, 3,   1, 3, 0>(mt);
		TestTemplTreeNode< 77, 3,   3, 3, 1>(mt);
		TestTemplTreeNode<121, 3,   2, 3, 2>(mt);
		TestTemplTreeNode<255, 3,   1, 3, 3>(mt);

		TestTemplTreeNode< 37,   7, 127, 3, 3>(mt);
		TestTemplTreeNode< 42,  15,  66, 3, 3>(mt);
		TestTemplTreeNode< 65,  23,  32, 3, 3>(mt);
		TestTemplTreeNode< 77,  30,  15, 3, 3>(mt);
		TestTemplTreeNode< 88,  31,   1, 3, 3>(mt);
		TestTemplTreeNode<104,  33,   3, 3, 3>(mt);
		TestTemplTreeNode<204, 100,   2, 3, 3>(mt);
		TestTemplTreeNode<255, 127,   1, 3, 3>(mt);
	}

	template<size_t maxCapacity, size_t capacityStep, size_t memPoolBlockCount,
		size_t keyTraits, size_t valueTraits>
	static void TestTemplTreeNode(std::mt19937& mt)
	{
		std::cout << "momo::TreeNode<" << maxCapacity << ", " << capacityStep << ", "
			<< memPoolBlockCount << ">: " << std::flush;

		typedef momo::TreeNode<maxCapacity, capacityStep,
			momo::MemPoolParams<memPoolBlockCount>> TreeNode;

		static const size_t count = 256;
		static unsigned char array[count];
		for (size_t i = 0; i < count; ++i)
			array[i] = static_cast<unsigned char>(i);

		if (maxCapacity > 1)
		{
			typedef momo::TreeSet<unsigned char,
				momo::TreeTraits<unsigned char, false, TreeNode>> TreeSet;

			for (size_t i = 0; i <= count; ++i)
			{
				TreeSet set1, set2;
				set1.Insert(array, array + i);
				set2.Insert(array + i, array + count);
				if (i > 0)
					set1.Remove(array[i - 1]);
				if (mt() % 2 == 0)
					std::swap(set1, set2);
				set1.MergeFrom(set2);
				if (i > 0)
					set1.Insert(array[i - 1]);
				assert(set1.GetCount() == count);
				assert(set2.IsEmpty());
				assert(std::equal(set1.GetBegin(), set1.GetEnd(), array));
				set2.Insert(set1.GetBegin(), set1.GetEnd());
				assert(std::equal(set2.GetBegin(), set2.GetEnd(), array));
			}
		}

		{
			typedef TemplItem<(keyTraits < 2), (keyTraits % 2 == 0), false> Key;
			typedef TemplItem<(valueTraits < 2), (valueTraits % 2 == 0), false> Value;

			typedef momo::TreeTraits<Key, false, TreeNode, true> TreeTraits;
			typedef momo::TreeMap<Key, Value, TreeTraits> TreeMap;
			typedef typename TreeMap::ConstIterator::Reference ConstReference;

			std::map<Key, Value, std::less<Key>,
				momo::stdish::unsynchronized_pool_allocator<std::pair<const Key, Value>>> smap;
			TreeMap map;

			auto isEqual = [] (ConstReference ref, const std::pair<const Key, Value>& sref)
				{ return ref.key == sref.first && ref.value == sref.second; };

			for (int t = 0; t < 2; ++t)
			{
				std::shuffle(array, array + count, mt);
				for (unsigned char c : array)
				{
					smap.insert({ Key(c), Value(c) });
					assert(map.Insert(Key(c), Value(c)).inserted);
					assert(map.GetCount() == smap.size());
					assert(std::equal(map.GetBegin(), map.GetEnd(), smap.begin(), isEqual));
				}

				std::shuffle(array, array + count, mt);
				for (unsigned char c : array)
				{
					smap.erase(Key(c));
					auto iter = map.Find(Key(c));
					assert(iter != map.GetEnd());
					if (t == 0)
						map.Remove(iter);
					else
						map.Extract(iter);
					assert(map.GetCount() == smap.size());
					assert(std::equal(map.GetBegin(), map.GetEnd(), smap.begin(), isEqual));
				}
			}
		}

		std::cout << "ok" << std::endl;
	}
};

static int testSimpleTree = (SimpleTreeTester::TestStrAll(), SimpleTreeTester::TestTemplAll(), 0);

#endif // TEST_SIMPLE_TREE
<commit_msg>SimpleTreeTester<commit_after>/**********************************************************\

  This file is distributed under the MIT License.
  See https://github.com/morzhovets/momo/blob/master/LICENSE
  for details.

  tests/SimpleTreeTester.cpp

\**********************************************************/

#include "pch.h"
#include "TestSettings.h"

#ifdef TEST_SIMPLE_TREE

#undef NDEBUG

#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"
#include "../../momo/stdish/pool_allocator.h"

#include <string>
#include <iostream>
#include <random>
#include <map>

class SimpleTreeTester
{
private:
	template<bool isNothrowMoveConstructible, bool isNothrowSwappable,
		bool isNothrowCopyAssignable = false>
	class TemplItem
	{
	public:
		explicit TemplItem(uint8_t c = uint8_t{0}) noexcept
			: mItem(c)
		{
		}

		TemplItem(TemplItem&& item) noexcept(isNothrowMoveConstructible)
			: mItem(item.mItem)
		{
		}

		TemplItem(const TemplItem& item) noexcept(false)
			: mItem(item.mItem)
		{
		}

		~TemplItem() = default;

		//TemplItem& operator=(TemplItem&& item) = delete;

		TemplItem& operator=(const TemplItem& item) noexcept(isNothrowCopyAssignable)
		{
			mItem = item.mItem;
			return *this;
		}

		friend void swap(TemplItem& item1, TemplItem& item2) noexcept(isNothrowSwappable)
		{
			std::swap(item1.mItem, item2.mItem);
		}

		bool operator==(const TemplItem& item) const noexcept
		{
			return mItem == item.mItem;
		}

		bool operator<(const TemplItem& item) const noexcept
		{
			return mItem < item.mItem;
		}

	private:
		uint8_t mItem;
	};

public:
	static void TestStrAll()
	{
		std::cout << "momo::TreeSet: " << std::flush;
		TestStrTreeSet();
		std::cout << "ok" << std::endl;

		std::cout << "momo::TreeMap: " << std::flush;
		TestStrTreeMap();
		std::cout << "ok" << std::endl;
	}

	static void TestStrTreeSet()
	{
		typedef momo::TreeSet<std::string> TreeSet;

		std::string s1 = "s1";
		std::string s2 = "s2";

		TreeSet set = { s2, "s3" };
		set.InsertVar(s1, "s1");

		assert(set.GetCount() == 3);
		assert(set.ContainsKey(s1));
		assert(set.ContainsKey("s2"));

		set.ResetKey(set.GetLowerBound("s1"), s1);
		set.ResetKey(set.GetUpperBound(s1), "s2");

		const auto es = set.Extract(set.Find("s1"));
		assert(es.GetItem() == s1);

		assert(set.GetCount() == 2);
		assert(*set.GetBegin() == s2);
		assert(*std::prev(set.GetEnd()) == "s3");

		TreeSet set2;
		set2 = set;
		assert(std::equal(set.GetBegin(), set.GetEnd(), set2.GetBegin()));
	}

	static void TestStrTreeMap()
	{
		typedef momo::TreeMap<std::string, std::string> TreeMap;
		typedef TreeMap::ConstIterator::Reference Reference;
		auto pred = [] (Reference ref1, Reference ref2)
			{ return ref1.key == ref2.key && ref1.value == ref2.value; };

		std::string s1 = "s1";
		std::string s2 = "s2";
		std::string s3 = "s3";
		std::string s4 = "s4";

		TreeMap map = { { "s1", "s1" }, { "s2", s2 } };
		map.InsertCrt("s3", [] (void* ptr) { ::new(ptr) std::string("s3"); });
		map.InsertCrt(s4, [] (void* ptr) { ::new(ptr) std::string("s4"); });

		map.Insert("s1", "s2");
		map.Insert("s2", s3);
		map.Insert(s3, "s4");
		map.Insert(s4, s1);

		map.ResetKey(map.GetLowerBound("s1"), s1);
		map.ResetKey(map.GetUpperBound(s1), "s2");

		assert(map.GetCount() == 4);
		for (auto ref : map)
			assert(ref.key == ref.value);

		TreeMap map2;
		map2 = map;

		const auto ep = map.Extract(map.Find("s1"));
		assert(ep.GetKey() == s1 && ep.GetValue() == s1);
		assert(map.GetCount() == 3);

		map.Insert(map2.GetBegin(), std::next(map2.GetBegin()));
		assert(std::equal(map.GetBegin(), map.GetEnd(), map2.GetBegin(), pred));

		map.Clear();
		assert(map.IsEmpty());

		map.Add(map.GetLowerBound("s1"), s1, s1);
		map.Add(map.GetUpperBound("s2"), s2, "s2");
		map.Add(map.GetLowerBound(s3), "s3", s3);
		map.Add(map.GetUpperBound(s4), "s4", "s4");
		assert(std::equal(map.GetBegin(), map.GetEnd(), map2.GetBegin(), pred));
	}

	static void TestTemplAll()
	{
		std::mt19937 mt;

		TestTemplTreeNode<  1, 1, 127, 0, 0>(mt);
		TestTemplTreeNode<  2, 1,  66, 0, 1>(mt);
		TestTemplTreeNode<  3, 1,  32, 0, 2>(mt);
		TestTemplTreeNode<  4, 1,  15, 0, 3>(mt);
		TestTemplTreeNode<  5, 1,   1, 1, 0>(mt);
		TestTemplTreeNode< 10, 1,   3, 1, 1>(mt);
		TestTemplTreeNode<101, 1,   2, 1, 2>(mt);
		TestTemplTreeNode<255, 1,   1, 1, 3>(mt);

		TestTemplTreeNode<  4, 2, 127, 2, 0>(mt);
		TestTemplTreeNode<  5, 2,  66, 2, 1>(mt);
		TestTemplTreeNode<  6, 2,  32, 2, 2>(mt);
		TestTemplTreeNode<  7, 2,  15, 2, 3>(mt);
		TestTemplTreeNode< 14, 3,   1, 3, 0>(mt);
		TestTemplTreeNode< 77, 3,   3, 3, 1>(mt);
		TestTemplTreeNode<121, 3,   2, 3, 2>(mt);
		TestTemplTreeNode<255, 3,   1, 3, 3>(mt);

		TestTemplTreeNode< 37,   7, 127, 3, 3>(mt);
		TestTemplTreeNode< 42,  15,  66, 3, 3>(mt);
		TestTemplTreeNode< 65,  23,  32, 3, 3>(mt);
		TestTemplTreeNode< 77,  30,  15, 3, 3>(mt);
		TestTemplTreeNode< 88,  31,   1, 3, 3>(mt);
		TestTemplTreeNode<104,  33,   3, 3, 3>(mt);
		TestTemplTreeNode<204, 100,   2, 3, 3>(mt);
		TestTemplTreeNode<255, 127,   1, 3, 3>(mt);
	}

	template<size_t maxCapacity, size_t capacityStep, size_t memPoolBlockCount,
		size_t keyTraits, size_t valueTraits>
	static void TestTemplTreeNode(std::mt19937& mt)
	{
		std::cout << "momo::TreeNode<" << maxCapacity << ", " << capacityStep << ", "
			<< memPoolBlockCount << ">: " << std::flush;

		typedef momo::TreeNode<maxCapacity, capacityStep,
			momo::MemPoolParams<memPoolBlockCount>> TreeNode;

		static const size_t count = 256;
		static uint8_t array[count];
		for (size_t i = 0; i < count; ++i)
			array[i] = static_cast<uint8_t>(i);

		if (maxCapacity > 1)
		{
			typedef momo::TreeSet<uint8_t, momo::TreeTraits<uint8_t, false, TreeNode>> TreeSet;

			for (size_t i = 0; i <= count; ++i)
			{
				TreeSet set1, set2;
				set1.Insert(array, array + i);
				set2.Insert(array + i, array + count);
				if (i > 0)
					set1.Remove(array[i - 1]);
				if (mt() % 2 == 0)
					std::swap(set1, set2);
				set1.MergeFrom(set2);
				if (i > 0)
					set1.Insert(array[i - 1]);
				assert(set1.GetCount() == count);
				assert(set2.IsEmpty());
				assert(std::equal(set1.GetBegin(), set1.GetEnd(), array));
				set2.Insert(set1.GetBegin(), set1.GetEnd());
				assert(std::equal(set2.GetBegin(), set2.GetEnd(), array));
			}
		}

		{
			typedef TemplItem<(keyTraits < 2), (keyTraits % 2 == 0)> Key;
			typedef TemplItem<(valueTraits < 2), (valueTraits % 2 == 0)> Value;

			typedef momo::TreeTraits<Key, false, TreeNode, true> TreeTraits;
			typedef momo::TreeMap<Key, Value, TreeTraits> TreeMap;
			typedef typename TreeMap::ConstIterator::Reference ConstReference;

			std::map<Key, Value, std::less<Key>,
				momo::stdish::unsynchronized_pool_allocator<std::pair<const Key, Value>>> smap;
			TreeMap map;

			auto isEqual = [] (ConstReference ref, const std::pair<const Key, Value>& sref)
				{ return ref.key == sref.first && ref.value == sref.second; };

			for (bool e : { false, true })
			{
				std::shuffle(array, array + count, mt);
				for (uint8_t c : array)
				{
					smap.insert({ Key(c), Value(c) });
					assert(map.Insert(Key(c), Value(c)).inserted);
					assert(map.GetCount() == smap.size());
					assert(std::equal(map.GetBegin(), map.GetEnd(), smap.begin(), isEqual));
				}

				std::shuffle(array, array + count, mt);
				for (uint8_t c : array)
				{
					smap.erase(Key(c));
					auto iter = map.Find(Key(c));
					assert(iter != map.GetEnd());
					if (e)
						map.Extract(iter);
					else
						map.Remove(iter);
					assert(map.GetCount() == smap.size());
					assert(std::equal(map.GetBegin(), map.GetEnd(), smap.begin(), isEqual));
				}
			}
		}

		std::cout << "ok" << std::endl;
	}
};

static int testSimpleTree = (SimpleTreeTester::TestStrAll(), SimpleTreeTester::TestTemplAll(), 0);

#endif // TEST_SIMPLE_TREE
<|endoftext|>


<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <compressor.h>
#include <test/setup_common.h>

#include <stdint.h>

#include <boost/test/unit_test.hpp>

// amounts 0.00000001 .. 0.00100000
#define NUM_MULTIPLES_UNIT 100000

// amounts 0.01 .. 100.00
#define NUM_MULTIPLES_CENT 10000

// amounts 1 .. 10000
#define NUM_MULTIPLES_1BTC 10000

// amounts 50 .. 21000000
#define NUM_MULTIPLES_50BTC 420000

BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)

bool static TestEncode(uint64_t in) {
    return in == DecompressAmount(CompressAmount(in));
}

bool static TestDecode(uint64_t in) {
    return in == CompressAmount(DecompressAmount(in));
}

bool static TestPair(uint64_t dec, uint64_t enc) {
    return CompressAmount(dec) == enc &&
           DecompressAmount(enc) == dec;
}

BOOST_AUTO_TEST_CASE(compress_amounts)
{
    BOOST_CHECK(TestPair(            0,       0x0));
    BOOST_CHECK(TestPair(            1,       0x1));
    BOOST_CHECK(TestPair(         CENT,       0x7));
    BOOST_CHECK(TestPair(         COIN,       0x9));
    BOOST_CHECK(TestPair(      50*COIN,      0x32));
    BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++)
        BOOST_CHECK(TestEncode(i));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++)
        BOOST_CHECK(TestEncode(i * CENT));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_1BTC; i++)
        BOOST_CHECK(TestEncode(i * COIN));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_50BTC; i++)
        BOOST_CHECK(TestEncode(i * 50 * COIN));

    for (uint64_t i = 0; i < 100000; i++)
        BOOST_CHECK(TestDecode(i));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add unit testing for the CompressScript functions<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <compressor.h>
#include <test/setup_common.h>
#include <script/standard.h>

#include <stdint.h>

#include <boost/test/unit_test.hpp>

// amounts 0.00000001 .. 0.00100000
#define NUM_MULTIPLES_UNIT 100000

// amounts 0.01 .. 100.00
#define NUM_MULTIPLES_CENT 10000

// amounts 1 .. 10000
#define NUM_MULTIPLES_1BTC 10000

// amounts 50 .. 21000000
#define NUM_MULTIPLES_50BTC 420000

BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)

bool static TestEncode(uint64_t in) {
    return in == DecompressAmount(CompressAmount(in));
}

bool static TestDecode(uint64_t in) {
    return in == CompressAmount(DecompressAmount(in));
}

bool static TestPair(uint64_t dec, uint64_t enc) {
    return CompressAmount(dec) == enc &&
           DecompressAmount(enc) == dec;
}

BOOST_AUTO_TEST_CASE(compress_amounts)
{
    BOOST_CHECK(TestPair(            0,       0x0));
    BOOST_CHECK(TestPair(            1,       0x1));
    BOOST_CHECK(TestPair(         CENT,       0x7));
    BOOST_CHECK(TestPair(         COIN,       0x9));
    BOOST_CHECK(TestPair(      50*COIN,      0x32));
    BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++)
        BOOST_CHECK(TestEncode(i));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++)
        BOOST_CHECK(TestEncode(i * CENT));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_1BTC; i++)
        BOOST_CHECK(TestEncode(i * COIN));

    for (uint64_t i = 1; i <= NUM_MULTIPLES_50BTC; i++)
        BOOST_CHECK(TestEncode(i * 50 * COIN));

    for (uint64_t i = 0; i < 100000; i++)
        BOOST_CHECK(TestDecode(i));
}

BOOST_AUTO_TEST_CASE(compress_script_to_ckey_id)
{
    // case CKeyID
    CKey key;
    key.MakeNewKey(true);
    CPubKey pubkey = key.GetPubKey();

    CScript script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
    BOOST_CHECK_EQUAL(script.size(), 25);

    std::vector<unsigned char> out;
    bool done = CompressScript(script, out);
    BOOST_CHECK_EQUAL(done, true);

    // Check compressed script
    BOOST_CHECK_EQUAL(out.size(), 21);
    BOOST_CHECK_EQUAL(out[0], 0x00);
    BOOST_CHECK_EQUAL(memcmp(&out[1], &script[3], 20), 0); // compare the 20 relevant chars of the CKeyId in the script
}

BOOST_AUTO_TEST_CASE(compress_script_to_cscript_id)
{
    // case CScriptID
    CScript script, redeemScript;
    script << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL;
    BOOST_CHECK_EQUAL(script.size(), 23);

    std::vector<unsigned char> out;
    bool done = CompressScript(script, out);
    BOOST_CHECK_EQUAL(done, true);

    // Check compressed script
    BOOST_CHECK_EQUAL(out.size(), 21);
    BOOST_CHECK_EQUAL(out[0], 0x01);
    BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 20), 0); // compare the 20 relevant chars of the CScriptId in the script
}

BOOST_AUTO_TEST_CASE(compress_script_to_compressed_pubkey_id)
{
    CKey key;
    key.MakeNewKey(true); // case compressed PubKeyID

    CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // COMPRESSED_PUBLIC_KEY_SIZE (33)
    BOOST_CHECK_EQUAL(script.size(), 35);

    std::vector<unsigned char> out;
    bool done = CompressScript(script, out);
    BOOST_CHECK_EQUAL(done, true);

    // Check compressed script
    BOOST_CHECK_EQUAL(out.size(), 33);
    BOOST_CHECK_EQUAL(memcmp(&out[0], &script[1], 1), 0);
    BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // compare the 32 chars of the compressed CPubKey
}

BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id)
{
    CKey key;
    key.MakeNewKey(false); // case uncompressed PubKeyID
    CScript script =  CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // PUBLIC_KEY_SIZE (65)
    BOOST_CHECK_EQUAL(script.size(), 67);                   // 1 char code + 65 char pubkey + OP_CHECKSIG

    std::vector<unsigned char> out;
    bool done = CompressScript(script, out);
    BOOST_CHECK_EQUAL(done, true);

    // Check compressed script
    BOOST_CHECK_EQUAL(out.size(), 33);
    BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // first 32 chars of CPubKey are copied into out[1:]
    BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0]
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//Benoit CHAPEROT 2003 www.jstarlab.com
//some code inspired by Magic Software
#include <ode/common.h>
#include <ode/collision.h>
#include <ode/matrix.h>
#include <ode/rotation.h>
#include <ode/odemath.h>
#include "collision_kernel.h"
#include "collision_std.h"
#include "collision_std_internal.h"
#include "collision_util.h"
//#include <drawstuff/drawstuff.h>
#include "windows.h"
#include "ode\ode.h"

#define CONTACT(p,skip) ((dContactGeom*) (((char*)p) + (skip)))
#define MAXCONTACT 10
#define TERRAINTOL 0.0f

static bool IsAPowerOfTwo(int f)
{
	while ((f&1) != 1)
		f >>= 1;

	return (f == 1);
}

static int GetPowerOfTwo(int f)
{
	int n = 0;
	while ((f&1) != 1)
	{
		n++;
		f >>= 1;
	}

	return n;
}

dxTerrain::dxTerrain (dSpaceID space, dReal *pHeights,dReal vLength,int nNumNodesPerSide) :
dxGeom (space,0)
{
	dIASSERT(IsAPowerOfTwo(nNumNodesPerSide));
	dIASSERT(pHeights);
	dIASSERT(vLength > 0.f);
	dIASSERT(nNumNodesPerSide > 0);
	type = dTerrainClass;
	m_vLength = vLength;
	m_pHeights = new dReal[nNumNodesPerSide * nNumNodesPerSide];
	dIASSERT(m_pHeights);
	m_nNumNodesPerSide = nNumNodesPerSide;
	m_vNodeLength = m_vLength / m_nNumNodesPerSide;
	m_nNumNodesPerSideShift = GetPowerOfTwo(m_nNumNodesPerSide);
	m_nNumNodesPerSideMask  = m_nNumNodesPerSide - 1;
	m_vMinHeight = dInfinity;
	m_vMaxHeight = -dInfinity;

	for (int i=0;i<nNumNodesPerSide * nNumNodesPerSide;i++)
	{
		m_pHeights[i] = pHeights[i];
		if (m_pHeights[i] < m_vMinHeight)	m_vMinHeight = m_pHeights[i];
		if (m_pHeights[i] > m_vMaxHeight)	m_vMaxHeight = m_pHeights[i];
	}
}

dxTerrain::~dxTerrain()
{
	dIASSERT(m_pHeights);
	delete [] m_pHeights;
}

void dxTerrain::computeAABB()
{
	aabb[0] = -dInfinity;
	aabb[1] = dInfinity;
	aabb[2] = -dInfinity;
	aabb[3] = dInfinity;
	aabb[4] = m_vMinHeight;
	aabb[5] = m_vMaxHeight;
}

dReal dxTerrain::GetHeight(int x,int y)
{
	return m_pHeights[	(((unsigned int)(y) & m_nNumNodesPerSideMask) << m_nNumNodesPerSideShift)
					+	 ((unsigned int)(x) & m_nNumNodesPerSideMask)];
}
/*
void dxTerrain::Draw(int x,int y)
{
	dVector3 A,B,C,D;	//,E,F,G,N;
	dMatrix3 R;
	dRSetIdentity(R);
	dVector3 pos;
	pos[0] = pos[1] = pos[2] = 0.f;
	dReal vx,vy;
	vx = m_vLength * x;
	vy = m_vLength * y;

	int i;
	for (i=0;i<m_nNumNodesPerSide;i++)
	{
		for (int j=0;j<m_nNumNodesPerSide;j++)
		{
			A[0] = i * m_vNodeLength + vx;
			A[1] = j * m_vNodeLength + vy;
			A[2] = GetHeight(i,j);
			B[0] = (i+1) * m_vNodeLength + vx;
			B[1] = j * m_vNodeLength + vy;
			B[2] = GetHeight(i+1,j);
			C[0] = i * m_vNodeLength + vx;
			C[1] = (j+1) * m_vNodeLength + vy;
			C[2] = GetHeight(i,j+1);
			D[0] = (i+1) * m_vNodeLength + vx;
			D[1] = (j+1) * m_vNodeLength + vy;
			D[2] = GetHeight(i+1,j+1);
			dsDrawTriangle(pos,R,C,A,B);
			dsDrawTriangle(pos,R,D,C,B);
		}
	}
}
*/
dReal dxTerrain::GetHeight(dReal x,dReal y)
{
	int nX		= int(floor(x / m_vNodeLength));
	int nY		= int(floor(y / m_vNodeLength));
	dReal dx	= (x - (dReal(nX) * m_vNodeLength)) / m_vNodeLength;
	dReal dy	= (y - (dReal(nY) * m_vNodeLength)) / m_vNodeLength;
	dIASSERT((dx >= 0.f) && (dx <= 1.f));
	dIASSERT((dy >= 0.f) && (dy <= 1.f));

	dReal z,z0;

	if (dx + dy < 1.f)
	{
		z0	= GetHeight(nX,nY);
		z	= z0
			+ (GetHeight(nX+1,nY) - z0) * dx
			+ (GetHeight(nX,nY+1) - z0) * dy;
	}
	else
	{
		z0	= GetHeight(nX+1,nY+1);
		z	= z0
			+ (GetHeight(nX+1,nY) - z0) * (1.f - dy)
			+ (GetHeight(nX,nY+1) - z0) * (1.f - dx);
	}

	return z;
}

bool dxTerrain::IsOnTerrain(int nx,int ny,int w,dReal *pos)
{
	dVector3 Min,Max;
	Min[0] = nx * m_vNodeLength;
	Min[1] = ny * m_vNodeLength;
	Max[0] = (nx+1) * m_vNodeLength;
	Max[1] = (ny+1) * m_vNodeLength;
	dReal Tol = m_vNodeLength * TERRAINTOL;

	if ((pos[0]<Min[0]-Tol) || (pos[0]>Max[0]+Tol))
		return false;

	if ((pos[1]<Min[1]-Tol) || (pos[1]>Max[1]+Tol))
		return false;

	dReal dx	= (pos[0] - (dReal(nx) * m_vNodeLength)) / m_vNodeLength;
	dReal dy	= (pos[1] - (dReal(ny) * m_vNodeLength)) / m_vNodeLength;

	if ((w == 0) && (dx + dy > 1.f+TERRAINTOL))
		return false;

	if ((w == 1) && (dx + dy < 1.f-TERRAINTOL))
		return false;

	return true;
}

dGeomID dCreateTerrain(dSpaceID space, dReal *pHeights,dReal vLength,int nNumNodesPerSide)
{
	return new dxTerrain(space, pHeights,vLength,nNumNodesPerSide);
}

dReal dGeomTerrainPointDepth (dGeomID g, dReal x, dReal y, dReal z)
{
	dUASSERT (g && g->type == dTerrainClass,"argument not a terrain");
	dxTerrain *t = (dxTerrain*) g;
	return t->GetHeight(x,y) - z;
}

int CompareContactGeom(const void *p1,const void *p2)
{
	dContactGeom *pC1 = (dContactGeom*)p1;
	dContactGeom *pC2 = (dContactGeom*)p2;
	if (pC1->depth > pC2->depth)	return -1;
	if (pC2->depth > pC1->depth)	return 1;
	return 0;
}

typedef dReal dGetDepthFn(dGeomID g, dReal x, dReal y, dReal z);
#define RECOMPUTE_RAYNORMAL
//#define DO_RAYDEPTH

#define DMESS(A)	\
			dMessage(0,"Contact Plane (%d %d %d) %.5e %.5e (%.5e %.5e %.5e)(%.5e %.5e %.5e)).",	\
					x,y,A,	\
					pContact[numContacts].depth,	\
					dGeomSphereGetRadius(o2),		\
					pContact[numContacts].pos[0],	\
					pContact[numContacts].pos[1],	\
					pContact[numContacts].pos[2],	\
					pContact[numContacts].normal[0],	\
					pContact[numContacts].normal[1],	\
					pContact[numContacts].normal[2]);

int dxTerrain::dCollideTerrainUnit(
	int x,int y,dxGeom *o2,int numMaxContacts,
	int flags,dContactGeom *pContact)
{
	dColliderFn *CollideRayN;
	dColliderFn *CollideNPlane;
	dGetDepthFn *GetDepth;
	int numContacts = 0;
	int numPlaneContacts = 0;
	int i;
	dContactGeom PlaneContact[MAXCONTACT];

	if (numContacts == numMaxContacts)
		return numContacts;

	switch (o2->type)
	{
	case dSphereClass:
		CollideRayN		= dCollideRaySphere;
		CollideNPlane	= dCollideSpherePlane;
		GetDepth		= dGeomSpherePointDepth;
		break;
	case dBoxClass:
		CollideRayN		= dCollideRayBox;
		CollideNPlane	= dCollideBoxPlane;
		GetDepth		= dGeomBoxPointDepth;
		break;
	case dCCylinderClass:
		CollideRayN		= dCollideRayCCylinder;
		CollideNPlane	= dCollideCCylinderPlane;
		GetDepth		= dGeomCCylinderPointDepth;
		break;
	case dRayClass:
		CollideRayN		= NULL;
		CollideNPlane	= dCollideRayPlane;
		GetDepth		= NULL;
		break;
	case dConeClass:
		CollideRayN		= dCollideRayCone;
		CollideNPlane	= dCollideConePlane;
		GetDepth		= dGeomConePointDepth;
		break;
	default:
		dIASSERT(0);
	}

	dReal Plane[4],lBD,lCD,lBC;
	dVector3 A,B,C,D,BD,CD,BC,AB,AC;
	A[0] = x * m_vNodeLength;
	A[1] = y * m_vNodeLength;
	A[2] = GetHeight(x,y);
	B[0] = (x+1) * m_vNodeLength;
	B[1] = y * m_vNodeLength;
	B[2] = GetHeight(x+1,y);
	C[0] = x * m_vNodeLength;
	C[1] = (y+1) * m_vNodeLength;
	C[2] = GetHeight(x,y+1);
	D[0] = (x+1) * m_vNodeLength;
	D[1] = (y+1) * m_vNodeLength;
	D[2] = GetHeight(x+1,y+1);

	dOP(BC,-,C,B);
	lBC = dLENGTH(BC);
	dOPEC(BC,/=,lBC);

	dOP(BD,-,D,B);
	lBD = dLENGTH(BD);
	dOPEC(BD,/=,lBD);

	dOP(CD,-,D,C);
	lCD = dLENGTH(CD);
	dOPEC(CD,/=,lCD);

	dOP(AB,-,B,A);
	dNormalize3(AB);

	dOP(AC,-,C,A);
	dNormalize3(AC);

	if (CollideRayN)
	{
#ifdef RECOMPUTE_RAYNORMAL
		dVector3 E,F;
		dVector3 CE,FB,AD;
		dVector3 Normal[3];
		E[0] = (x+2) * m_vNodeLength;
		E[1] = y * m_vNodeLength;
		E[2] = GetHeight(x+2,y);
		F[0] = x * m_vNodeLength;
		F[1] = (y+2) * m_vNodeLength;
		F[2] = GetHeight(x,y+2);
		dOP(AD,-,D,A);
		dNormalize3(AD);
		dOP(CE,-,E,C);
		dNormalize3(CE);
		dOP(FB,-,B,F);
		dNormalize3(FB);

		//BC
		dCROSS(Normal[0],=,AD,BC);
		dNormalize3(Normal[0]);

		//BD
		dCROSS(Normal[1],=,CE,BD);
		dNormalize3(Normal[1]);

		//CD
		dCROSS(Normal[2],=,FB,CD);
		dNormalize3(Normal[2]);
#endif
		int nA[3],nB[3];
		dContactGeom ContactA[3],ContactB[3];
		dxRay rayBC(0,lBC);
		dGeomRaySet(&rayBC, B[0], B[1], B[2], BC[0], BC[1], BC[2]);
		nA[0] = CollideRayN(&rayBC,o2,flags,&ContactA[0],sizeof(dContactGeom));
		dGeomRaySet(&rayBC, C[0], C[1], C[2], -BC[0], -BC[1], -BC[2]);
		nB[0] = CollideRayN(&rayBC,o2,flags,&ContactB[0],sizeof(dContactGeom));

		dxRay rayBD(0,lBD);
		dGeomRaySet(&rayBD, B[0], B[1], B[2], BD[0], BD[1], BD[2]);
		nA[1] = CollideRayN(&rayBD,o2,flags,&ContactA[1],sizeof(dContactGeom));
		dGeomRaySet(&rayBD, D[0], D[1], D[2], -BD[0], -BD[1], -BD[2]);
		nB[1] = CollideRayN(&rayBD,o2,flags,&ContactB[1],sizeof(dContactGeom));

		dxRay rayCD(0,lCD);
		dGeomRaySet(&rayCD, C[0], C[1], C[2], CD[0], CD[1], CD[2]);
		nA[2] = CollideRayN(&rayCD,o2,flags,&ContactA[2],sizeof(dContactGeom));
		dGeomRaySet(&rayCD, D[0], D[1], D[2], -CD[0], -CD[1], -CD[2]);
		nB[2] = CollideRayN(&rayCD,o2,flags,&ContactB[2],sizeof(dContactGeom));

		for (i=0;i<3;i++)
		{
			if (nA[i] & nB[i])
			{
				pContact[numContacts].pos[0] = (ContactA[i].pos[0] + ContactB[i].pos[0])/2;
				pContact[numContacts].pos[1] = (ContactA[i].pos[1] + ContactB[i].pos[1])/2;
				pContact[numContacts].pos[2] = (ContactA[i].pos[2] + ContactB[i].pos[2])/2;
#ifdef RECOMPUTE_RAYNORMAL
				pContact[numContacts].normal[0] = -Normal[i][0];
				pContact[numContacts].normal[1] = -Normal[i][1];
				pContact[numContacts].normal[2] = -Normal[i][2];
#else
				pContact[numContacts].normal[0] = (ContactA[i].normal[0] + ContactB[i].normal[0])/2;	//0.f;
				pContact[numContacts].normal[1] = (ContactA[i].normal[1] + ContactB[i].normal[1])/2;	//0.f;
				pContact[numContacts].normal[2] = (ContactA[i].normal[2] + ContactB[i].normal[2])/2;	//-1.f;
				dNormalize3(pContact[numContacts].normal);
#endif
#ifdef DO_RAYDEPTH
				dxRay rayV(0,1000.f);
				dGeomRaySet(&rayV,	pContact[numContacts].pos[0],
									pContact[numContacts].pos[1],
									pContact[numContacts].pos[2],
									-pContact[numContacts].normal[0],
									-pContact[numContacts].normal[1],
									-pContact[numContacts].normal[2]);

				dContactGeom ContactV;
				if (CollideRayN(&rayV,o2,flags,&ContactV,sizeof(dContactGeom)))
				{
					pContact[numContacts].depth = ContactV.depth;
					numContacts++;
				}
#else
				pContact[numContacts].depth =  GetDepth(o2,
				pContact[numContacts].pos[0],
				pContact[numContacts].pos[1],
				pContact[numContacts].pos[2]);
				numContacts++;
#endif
				if (numContacts == numMaxContacts)
					return numContacts;

			}
		}
	}

	dCROSS(Plane,=,AB,AC);
	dNormalize3(Plane);
	Plane[3] = Plane[0] * A[0] + Plane[1] * A[1] + Plane[2] * A[2];
	dxPlane planeABC(0,Plane[0],Plane[1],Plane[2],Plane[3]);
	numPlaneContacts = CollideNPlane(o2,&planeABC,flags,PlaneContact,sizeof(dContactGeom));

	for (i=0;i<numPlaneContacts;i++)
	{
		if (IsOnTerrain(x,y,0,PlaneContact[i].pos))
		{
			pContact[numContacts].pos[0] = PlaneContact[i].pos[0];
			pContact[numContacts].pos[1] = PlaneContact[i].pos[1];
			pContact[numContacts].pos[2] = PlaneContact[i].pos[2];
			pContact[numContacts].normal[0] = -PlaneContact[i].normal[0];
			pContact[numContacts].normal[1] = -PlaneContact[i].normal[1];
			pContact[numContacts].normal[2] = -PlaneContact[i].normal[2];
			pContact[numContacts].depth = PlaneContact[i].depth;

			//DMESS(0);
			numContacts++;

			if (numContacts == numMaxContacts)
					return numContacts;
		}
	}

	dCROSS(Plane,=,CD,BD);
	dNormalize3(Plane);
	Plane[3] = Plane[0] * D[0] + Plane[1] * D[1] + Plane[2] * D[2];
	dxPlane planeDCB(0,Plane[0],Plane[1],Plane[2],Plane[3]);
	numPlaneContacts = CollideNPlane(o2,&planeDCB,flags,PlaneContact,sizeof(dContactGeom));

	for (i=0;i<numPlaneContacts;i++)
	{
		if (IsOnTerrain(x,y,1,PlaneContact[i].pos))
		{
			pContact[numContacts].pos[0] = PlaneContact[i].pos[0];
			pContact[numContacts].pos[1] = PlaneContact[i].pos[1];
			pContact[numContacts].pos[2] = PlaneContact[i].pos[2];
			pContact[numContacts].normal[0] = -PlaneContact[i].normal[0];
			pContact[numContacts].normal[1] = -PlaneContact[i].normal[1];
			pContact[numContacts].normal[2] = -PlaneContact[i].normal[2];
			pContact[numContacts].depth = PlaneContact[i].depth;
			//DMESS(1);
			numContacts++;

			if (numContacts == numMaxContacts)
					return numContacts;
		}
	}

	return numContacts;
}

int dCollideTerrain(dxGeom *o1, dxGeom *o2, int flags,dContactGeom *contact, int skip)
{
	dIASSERT (skip >= (int)sizeof(dContactGeom));
	dIASSERT (o1->type == dTerrainClass);
	int i,j;

	if ((flags & 0xffff) > MAXCONTACT)
		flags = (flags & 0xffff0000) | MAXCONTACT;

	if ((flags & 0xffff) == 0)
		flags = (flags & 0xffff0000) | 1;

	dxTerrain *terrain = (dxTerrain*) o1;
	dVector3 AabbTop;
	AabbTop[0] = (o2->aabb[0]+o2->aabb[1]) / 2;
	AabbTop[1] = (o2->aabb[2]+o2->aabb[3]) / 2;
	AabbTop[2] = o2->aabb[5];
	dReal AabbTopDepth = terrain->GetHeight(AabbTop[0],AabbTop[1]) - AabbTop[2];
	if (AabbTopDepth > 0.f)
	{
		contact->depth = AabbTopDepth;
		dReal MaxDepth = (o2->aabb[5]-o2->aabb[4]) / 2;
		if (contact->depth > MaxDepth)
			contact->depth = MaxDepth;
		contact->g1 = o1;
		contact->g2 = o2;
		dOPE(contact->pos,=,AabbTop);
		contact->normal[0] = 0.f;
		contact->normal[1] = 0.f;
		contact->normal[2] = -1.f;
		return 1;
	}

	dContactGeom TerrainContact[MAXCONTACT];
	int nMinX	= int(floor(o2->aabb[0] / terrain->m_vNodeLength));
	int nMaxX	= int(floor(o2->aabb[1] / terrain->m_vNodeLength)) + 1;
	int nMinY	= int(floor(o2->aabb[2] / terrain->m_vNodeLength));
	int nMaxY	= int(floor(o2->aabb[3] / terrain->m_vNodeLength)) + 1;

	//TO FIX
	int numTerrainContacts = 0;

	for (i=nMinX;i<nMaxX;i++)
	{
		for (j=nMinY;j<nMaxY;j++)
		{
			numTerrainContacts += terrain->dCollideTerrainUnit(
				i,j,o2,MAXCONTACT - numTerrainContacts,
				flags,&TerrainContact[numTerrainContacts]);

		}
	}

	dIASSERT(numTerrainContacts <= MAXCONTACT);

	qsort(&TerrainContact[0],numTerrainContacts,sizeof(dContactGeom),CompareContactGeom);

	if (numTerrainContacts > (flags & 0xffff))
		numTerrainContacts = (flags & 0xffff);

	for (i=0; i<numTerrainContacts; i++)
	{
		*(CONTACT(contact,i*skip)) = TerrainContact[i];
		CONTACT(contact,i*skip)->g1 = o1;
		CONTACT(contact,i*skip)->g2 = o2;
		CONTACT(contact,i*skip)->depth /= numTerrainContacts;
	}

	return numTerrainContacts;
}

/*
void dDrawTerrain(dGeomID g,int x,int y)
{
	dUASSERT (g && g->type == dTerrainClass,"argument not a terrain");
	dxTerrain *t = (dxTerrain*) g;
	t->Draw(x,y);
}
*/<commit_msg>removed<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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/extensions/extension_util.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/sync_helper.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/browser/site_instance.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/features/behavior_feature.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_handlers/app_isolation_info.h"
#include "extensions/common/manifest_handlers/incognito_info.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/grit/extensions_browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace extensions {
namespace util {

namespace {

const char kSupervisedUserExtensionPermissionIncreaseFieldTrialName[] =
    "SupervisedUserExtensionPermissionIncrease";

// The entry into the prefs used to flag an extension as installed by custodian.
// It is relevant only for supervised users.
const char kWasInstalledByCustodianPrefName[] = "was_installed_by_custodian";

// Returns true if |extension| should always be enabled in incognito mode.
bool IsWhitelistedForIncognito(const Extension* extension) {
  const Feature* feature = FeatureProvider::GetBehaviorFeature(
      behavior_feature::kWhitelistedForIncognito);
  return feature && feature->IsAvailableToExtension(extension).is_available();
}

}  // namespace

bool IsIncognitoEnabled(const std::string& extension_id,
                        content::BrowserContext* context) {
  const Extension* extension = ExtensionRegistry::Get(context)->
      GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
  if (extension) {
    if (!util::CanBeIncognitoEnabled(extension))
      return false;
    // If this is an existing component extension we always allow it to
    // work in incognito mode.
    if (extension->location() == Manifest::COMPONENT ||
        extension->location() == Manifest::EXTERNAL_COMPONENT) {
      return true;
    }
    if (IsWhitelistedForIncognito(extension))
      return true;
  }
  return ExtensionPrefs::Get(context)->IsIncognitoEnabled(extension_id);
}

void SetIsIncognitoEnabled(const std::string& extension_id,
                           content::BrowserContext* context,
                           bool enabled) {
  NOTIMPLEMENTED();
}

bool CanCrossIncognito(const Extension* extension,
                       content::BrowserContext* context) {
  // We allow the extension to see events and data from another profile iff it
  // uses "spanning" behavior and it has incognito access. "split" mode
  // extensions only see events for a matching profile.
  CHECK(extension);
  return IsIncognitoEnabled(extension->id(), context) &&
         !IncognitoInfo::IsSplitMode(extension);
}

bool CanLoadInIncognito(const Extension* extension,
                        content::BrowserContext* context) {
  CHECK(extension);
  if (extension->is_hosted_app())
    return true;
  // Packaged apps and regular extensions need to be enabled specifically for
  // incognito (and split mode should be set).
  return IncognitoInfo::IsSplitMode(extension) &&
         IsIncognitoEnabled(extension->id(), context);
}

bool AllowFileAccess(const std::string& extension_id,
                     content::BrowserContext* context) {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
             switches::kDisableExtensionsFileAccessCheck) ||
         ExtensionPrefs::Get(context)->AllowFileAccess(extension_id);
}

void SetAllowFileAccess(const std::string& extension_id,
                        content::BrowserContext* context,
                        bool allow) {
  NOTIMPLEMENTED();
}

void SetWasInstalledByCustodian(const std::string& extension_id,
                                content::BrowserContext* context,
                                bool installed_by_custodian) {
  NOTIMPLEMENTED();
}

bool WasInstalledByCustodian(const std::string& extension_id,
                             content::BrowserContext* context) {
  bool installed_by_custodian = false;
  ExtensionPrefs* prefs = ExtensionPrefs::Get(context);
  prefs->ReadPrefAsBoolean(extension_id, kWasInstalledByCustodianPrefName,
                           &installed_by_custodian);
  return installed_by_custodian;
}

bool IsAppLaunchable(const std::string& extension_id,
                     content::BrowserContext* context) {
  int reason = ExtensionPrefs::Get(context)->GetDisableReasons(extension_id);
  return !((reason & Extension::DISABLE_UNSUPPORTED_REQUIREMENT) ||
           (reason & Extension::DISABLE_CORRUPTED));
}

bool IsAppLaunchableWithoutEnabling(const std::string& extension_id,
                                    content::BrowserContext* context) {
  return ExtensionRegistry::Get(context)->GetExtensionById(
      extension_id, ExtensionRegistry::ENABLED) != NULL;
}

bool ShouldSync(const Extension* extension,
                content::BrowserContext* context) {
  return sync_helper::IsSyncable(extension) &&
         !ExtensionPrefs::Get(context)->DoNotSync(extension->id());
}

bool IsExtensionIdle(const std::string& extension_id,
                     content::BrowserContext* context) {
  std::vector<std::string> ids_to_check;
  ids_to_check.push_back(extension_id);

  const Extension* extension =
      ExtensionRegistry::Get(context)
          ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
  if (extension && extension->is_shared_module()) {
    // We have to check all the extensions that use this shared module for idle
    // to tell whether it is really 'idle'.
    NOTIMPLEMENTED();
  }

  ProcessManager* process_manager = ProcessManager::Get(context);
  for (std::vector<std::string>::const_iterator i = ids_to_check.begin();
       i != ids_to_check.end();
       i++) {
    const std::string id = (*i);
    ExtensionHost* host = process_manager->GetBackgroundHostForExtension(id);
    if (host)
      return false;

    scoped_refptr<content::SiteInstance> site_instance =
        process_manager->GetSiteInstanceForURL(
            Extension::GetBaseURLFromExtensionId(id));
    if (site_instance && site_instance->HasProcess())
      return false;

    if (!process_manager->GetRenderFrameHostsForExtension(id).empty())
      return false;
  }
  return true;
}

GURL GetSiteForExtensionId(const std::string& extension_id,
                           content::BrowserContext* context) {
  return content::SiteInstance::GetSiteForURL(
      context, Extension::GetBaseURLFromExtensionId(extension_id));
}

std::unique_ptr<base::DictionaryValue> GetExtensionInfo(
    const Extension* extension) {
  DCHECK(extension);
  std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);

  dict->SetString("id", extension->id());
  dict->SetString("name", extension->name());

  // TODO(bridiver)
  // GURL icon = extensions::ExtensionIconSource::GetIconURL(
  //     extension,
  //     extension_misc::EXTENSION_ICON_SMALLISH,
  //     ExtensionIconSet::MATCH_BIGGER,
  //     false,  // Not grayscale.
  //     NULL);  // Don't set bool if exists.
  // dict->SetString("icon", icon.spec());

  return dict;
}

const gfx::ImageSkia& GetDefaultAppIcon() {
  return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_APP_DEFAULT_ICON);
}

const gfx::ImageSkia& GetDefaultExtensionIcon() {
  return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_EXTENSION_DEFAULT_ICON);
}

bool IsNewBookmarkAppsEnabled() {
#if defined(OS_MACOSX)
  return base::FeatureList::IsEnabled(features::kBookmarkApps);
#else
  return true;
#endif
}

bool CanHostedAppsOpenInWindows() {
#if defined(OS_MACOSX)
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableHostedAppsInWindows);
#else
  return true;
#endif
}

bool IsExtensionSupervised(const Extension* extension, Profile* profile) {
  NOTIMPLEMENTED();
  return false;
}

bool NeedCustodianApprovalForPermissionIncrease(const Profile* profile) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace util
}  // namespace extensions
<commit_msg>Fix IsIncognitoEnabled duplicate symbol linking error<commit_after>// Copyright 2013 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/extensions/extension_util.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/sync_helper.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/browser/site_instance.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_icon_set.h"
#include "extensions/common/features/behavior_feature.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_handlers/app_isolation_info.h"
#include "extensions/common/manifest_handlers/incognito_info.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/grit/extensions_browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace extensions {
namespace util {

namespace {

const char kSupervisedUserExtensionPermissionIncreaseFieldTrialName[] =
    "SupervisedUserExtensionPermissionIncrease";

// The entry into the prefs used to flag an extension as installed by custodian.
// It is relevant only for supervised users.
const char kWasInstalledByCustodianPrefName[] = "was_installed_by_custodian";

// Returns true if |extension| should always be enabled in incognito mode.
bool IsWhitelistedForIncognito(const Extension* extension) {
  const Feature* feature = FeatureProvider::GetBehaviorFeature(
      behavior_feature::kWhitelistedForIncognito);
  return feature && feature->IsAvailableToExtension(extension).is_available();
}

}  // namespace

void SetIsIncognitoEnabled(const std::string& extension_id,
                           content::BrowserContext* context,
                           bool enabled) {
  NOTIMPLEMENTED();
}

bool CanCrossIncognito(const Extension* extension,
                       content::BrowserContext* context) {
  // We allow the extension to see events and data from another profile iff it
  // uses "spanning" behavior and it has incognito access. "split" mode
  // extensions only see events for a matching profile.
  CHECK(extension);
  return IsIncognitoEnabled(extension->id(), context) &&
         !IncognitoInfo::IsSplitMode(extension);
}

bool CanLoadInIncognito(const Extension* extension,
                        content::BrowserContext* context) {
  CHECK(extension);
  if (extension->is_hosted_app())
    return true;
  // Packaged apps and regular extensions need to be enabled specifically for
  // incognito (and split mode should be set).
  return IncognitoInfo::IsSplitMode(extension) &&
         IsIncognitoEnabled(extension->id(), context);
}

bool AllowFileAccess(const std::string& extension_id,
                     content::BrowserContext* context) {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
             switches::kDisableExtensionsFileAccessCheck) ||
         ExtensionPrefs::Get(context)->AllowFileAccess(extension_id);
}

void SetAllowFileAccess(const std::string& extension_id,
                        content::BrowserContext* context,
                        bool allow) {
  NOTIMPLEMENTED();
}

void SetWasInstalledByCustodian(const std::string& extension_id,
                                content::BrowserContext* context,
                                bool installed_by_custodian) {
  NOTIMPLEMENTED();
}

bool WasInstalledByCustodian(const std::string& extension_id,
                             content::BrowserContext* context) {
  bool installed_by_custodian = false;
  ExtensionPrefs* prefs = ExtensionPrefs::Get(context);
  prefs->ReadPrefAsBoolean(extension_id, kWasInstalledByCustodianPrefName,
                           &installed_by_custodian);
  return installed_by_custodian;
}

bool IsAppLaunchable(const std::string& extension_id,
                     content::BrowserContext* context) {
  int reason = ExtensionPrefs::Get(context)->GetDisableReasons(extension_id);
  return !((reason & Extension::DISABLE_UNSUPPORTED_REQUIREMENT) ||
           (reason & Extension::DISABLE_CORRUPTED));
}

bool IsAppLaunchableWithoutEnabling(const std::string& extension_id,
                                    content::BrowserContext* context) {
  return ExtensionRegistry::Get(context)->GetExtensionById(
      extension_id, ExtensionRegistry::ENABLED) != NULL;
}

bool ShouldSync(const Extension* extension,
                content::BrowserContext* context) {
  return sync_helper::IsSyncable(extension) &&
         !ExtensionPrefs::Get(context)->DoNotSync(extension->id());
}

bool IsExtensionIdle(const std::string& extension_id,
                     content::BrowserContext* context) {
  std::vector<std::string> ids_to_check;
  ids_to_check.push_back(extension_id);

  const Extension* extension =
      ExtensionRegistry::Get(context)
          ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
  if (extension && extension->is_shared_module()) {
    // We have to check all the extensions that use this shared module for idle
    // to tell whether it is really 'idle'.
    NOTIMPLEMENTED();
  }

  ProcessManager* process_manager = ProcessManager::Get(context);
  for (std::vector<std::string>::const_iterator i = ids_to_check.begin();
       i != ids_to_check.end();
       i++) {
    const std::string id = (*i);
    ExtensionHost* host = process_manager->GetBackgroundHostForExtension(id);
    if (host)
      return false;

    scoped_refptr<content::SiteInstance> site_instance =
        process_manager->GetSiteInstanceForURL(
            Extension::GetBaseURLFromExtensionId(id));
    if (site_instance && site_instance->HasProcess())
      return false;

    if (!process_manager->GetRenderFrameHostsForExtension(id).empty())
      return false;
  }
  return true;
}

GURL GetSiteForExtensionId(const std::string& extension_id,
                           content::BrowserContext* context) {
  return content::SiteInstance::GetSiteForURL(
      context, Extension::GetBaseURLFromExtensionId(extension_id));
}

std::unique_ptr<base::DictionaryValue> GetExtensionInfo(
    const Extension* extension) {
  DCHECK(extension);
  std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);

  dict->SetString("id", extension->id());
  dict->SetString("name", extension->name());

  // TODO(bridiver)
  // GURL icon = extensions::ExtensionIconSource::GetIconURL(
  //     extension,
  //     extension_misc::EXTENSION_ICON_SMALLISH,
  //     ExtensionIconSet::MATCH_BIGGER,
  //     false,  // Not grayscale.
  //     NULL);  // Don't set bool if exists.
  // dict->SetString("icon", icon.spec());

  return dict;
}

const gfx::ImageSkia& GetDefaultAppIcon() {
  return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_APP_DEFAULT_ICON);
}

const gfx::ImageSkia& GetDefaultExtensionIcon() {
  return *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_EXTENSION_DEFAULT_ICON);
}

bool IsNewBookmarkAppsEnabled() {
#if defined(OS_MACOSX)
  return base::FeatureList::IsEnabled(features::kBookmarkApps);
#else
  return true;
#endif
}

bool CanHostedAppsOpenInWindows() {
#if defined(OS_MACOSX)
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableHostedAppsInWindows);
#else
  return true;
#endif
}

bool IsExtensionSupervised(const Extension* extension, Profile* profile) {
  NOTIMPLEMENTED();
  return false;
}

bool NeedCustodianApprovalForPermissionIncrease(const Profile* profile) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace util
}  // namespace extensions
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __TEST_CONTAINERIZER_HPP__
#define __TEST_CONTAINERIZER_HPP__

#ifndef __WINDOWS__
#include <unistd.h>
#endif // __WINDOWS__

#include <map>
#include <memory>
#include <string>

#include <mesos/executor.hpp>
#include <mesos/mesos.hpp>
#include <mesos/resources.hpp>
#include <mesos/type_utils.hpp>

#include <mesos/v1/executor.hpp>

#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <process/http.hpp>
#include <process/pid.hpp>

#include <stout/hashmap.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/uuid.hpp>

#include "slave/containerizer/containerizer.hpp"

#include "slave/slave.hpp"
#include "slave/state.hpp"

#include "tests/mesos.hpp"

namespace mesos {
namespace internal {
namespace tests {

// Forward declaration.
class MockExecutor;
class TestContainerizerProcess;

class TestContainerizer : public slave::Containerizer
{
public:
  // TODO(bmahler): These constructors assume that ExecutorIDs are
  // unique across FrameworkIDs, which is not the case.
  TestContainerizer(
      const ExecutorID& executorId,
      const std::shared_ptr<v1::MockHTTPExecutor>& executor);

  TestContainerizer(const hashmap<ExecutorID, Executor*>& executors);

  TestContainerizer(const ExecutorID& executorId, Executor* executor);

  explicit TestContainerizer(MockExecutor* executor);

  TestContainerizer();

  virtual ~TestContainerizer();

  virtual process::Future<hashset<ContainerID>> containers();

  MOCK_METHOD1(
      recover,
      process::Future<Nothing>(const Option<slave::state::SlaveState>&));

  MOCK_METHOD4(
      launch,
      process::Future<slave::Containerizer::LaunchResult>(
          const ContainerID&,
          const mesos::slave::ContainerConfig&,
          const std::map<std::string, std::string>&,
          const Option<std::string>&));

  MOCK_METHOD1(
      attach,
      process::Future<process::http::Connection>(
          const ContainerID& containerId));

  MOCK_METHOD2(
      update,
      process::Future<Nothing>(const ContainerID&, const Resources&));

  MOCK_METHOD1(
      usage,
      process::Future<ResourceStatistics>(const ContainerID&));

  MOCK_METHOD1(
      status,
      process::Future<ContainerStatus>(const ContainerID&));

  MOCK_METHOD1(
      wait,
      process::Future<Option<mesos::slave::ContainerTermination>>(
          const ContainerID&));

  MOCK_METHOD1(
      destroy,
      process::Future<bool>(const ContainerID&));

  MOCK_METHOD2(
      kill,
      process::Future<bool>(const ContainerID&, int));

  MOCK_METHOD1(
      pruneImages,
      process::Future<Nothing>(const std::vector<Image>&));

  // Additional destroy method for testing because we won't know the
  // ContainerID created for each container.
  process::Future<bool> destroy(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId);

private:
  void setup();

  // The following functions act as a level of indirection to
  // perform the dispatch while still allowing the above to be
  // mock functions.

  process::Future<Nothing> _recover(
      const Option<slave::state::SlaveState>& state);

  process::Future<slave::Containerizer::LaunchResult> _launch(
      const ContainerID& containerId,
      const mesos::slave::ContainerConfig& containerConfig,
      const std::map<std::string, std::string>& environment,
      const Option<std::string>& pidCheckpointPath);

  process::Future<process::http::Connection> _attach(
      const ContainerID& containerId);

  process::Future<Nothing> _update(
      const ContainerID& containerId,
      const Resources& resources);

  process::Future<ResourceStatistics> _usage(
      const ContainerID& containerId);

  process::Future<ContainerStatus> _status(
      const ContainerID& containerId);

  process::Future<Option<mesos::slave::ContainerTermination>> _wait(
      const ContainerID& containerId);

  process::Future<bool> _destroy(
      const ContainerID& containerId);

  process::Future<bool> _kill(
      const ContainerID& containerId,
      int status);

  process::Future<Nothing> _pruneImages(
      const std::vector<Image>& excludedImages);

  process::Owned<TestContainerizerProcess> process;
};

} // namespace tests {
} // namespace internal {
} // namespace mesos {

#endif // __TEST_CONTAINERIZER_HPP__
<commit_msg>Deleted a redundant line in test/containerizer.hpp.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __TEST_CONTAINERIZER_HPP__
#define __TEST_CONTAINERIZER_HPP__

#ifndef __WINDOWS__
#include <unistd.h>
#endif // __WINDOWS__

#include <map>
#include <memory>
#include <string>

#include <mesos/executor.hpp>
#include <mesos/mesos.hpp>
#include <mesos/resources.hpp>
#include <mesos/type_utils.hpp>

#include <mesos/v1/executor.hpp>

#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <process/http.hpp>
#include <process/pid.hpp>

#include <stout/hashmap.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/uuid.hpp>

#include "slave/containerizer/containerizer.hpp"

#include "slave/slave.hpp"
#include "slave/state.hpp"

#include "tests/mesos.hpp"

namespace mesos {
namespace internal {
namespace tests {

// Forward declaration.
class MockExecutor;
class TestContainerizerProcess;

class TestContainerizer : public slave::Containerizer
{
public:
  // TODO(bmahler): These constructors assume that ExecutorIDs are
  // unique across FrameworkIDs, which is not the case.
  TestContainerizer(
      const ExecutorID& executorId,
      const std::shared_ptr<v1::MockHTTPExecutor>& executor);

  TestContainerizer(const hashmap<ExecutorID, Executor*>& executors);

  TestContainerizer(const ExecutorID& executorId, Executor* executor);

  explicit TestContainerizer(MockExecutor* executor);

  TestContainerizer();

  virtual ~TestContainerizer();

  virtual process::Future<hashset<ContainerID>> containers();

  MOCK_METHOD1(
      recover,
      process::Future<Nothing>(const Option<slave::state::SlaveState>&));

  MOCK_METHOD4(
      launch,
      process::Future<slave::Containerizer::LaunchResult>(
          const ContainerID&,
          const mesos::slave::ContainerConfig&,
          const std::map<std::string, std::string>&,
          const Option<std::string>&));

  MOCK_METHOD1(
      attach,
      process::Future<process::http::Connection>(
          const ContainerID& containerId));

  MOCK_METHOD2(
      update,
      process::Future<Nothing>(const ContainerID&, const Resources&));

  MOCK_METHOD1(
      usage,
      process::Future<ResourceStatistics>(const ContainerID&));

  MOCK_METHOD1(
      status,
      process::Future<ContainerStatus>(const ContainerID&));

  MOCK_METHOD1(
      wait,
      process::Future<Option<mesos::slave::ContainerTermination>>(
          const ContainerID&));

  MOCK_METHOD1(
      destroy,
      process::Future<bool>(const ContainerID&));

  MOCK_METHOD2(
      kill,
      process::Future<bool>(const ContainerID&, int));

  MOCK_METHOD1(
      pruneImages,
      process::Future<Nothing>(const std::vector<Image>&));

  // Additional destroy method for testing because we won't know the
  // ContainerID created for each container.
  process::Future<bool> destroy(
      const FrameworkID& frameworkId,
      const ExecutorID& executorId);

private:
  void setup();

  // The following functions act as a level of indirection to
  // perform the dispatch while still allowing the above to be
  // mock functions.

  process::Future<Nothing> _recover(
      const Option<slave::state::SlaveState>& state);

  process::Future<slave::Containerizer::LaunchResult> _launch(
      const ContainerID& containerId,
      const mesos::slave::ContainerConfig& containerConfig,
      const std::map<std::string, std::string>& environment,
      const Option<std::string>& pidCheckpointPath);

  process::Future<process::http::Connection> _attach(
      const ContainerID& containerId);

  process::Future<Nothing> _update(
      const ContainerID& containerId,
      const Resources& resources);

  process::Future<ResourceStatistics> _usage(
      const ContainerID& containerId);

  process::Future<ContainerStatus> _status(
      const ContainerID& containerId);

  process::Future<Option<mesos::slave::ContainerTermination>> _wait(
      const ContainerID& containerId);

  process::Future<bool> _destroy(
      const ContainerID& containerId);

  process::Future<bool> _kill(
      const ContainerID& containerId,
      int status);

  process::Future<Nothing> _pruneImages(
      const std::vector<Image>& excludedImages);

  process::Owned<TestContainerizerProcess> process;
};

} // namespace tests {
} // namespace internal {
} // namespace mesos {

#endif // __TEST_CONTAINERIZER_HPP__
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE pdbreader_test
#include <boost/test/unit_test.hpp>

#include <votca/csg/topologyreader.h>
#include <votca/csg/bead.h>
#include <votca/tools/elements.h>
#include <string>
#include <fstream>
#include <cmath>

using namespace std;
using namespace votca::csg;

// used for rounding doubles so we can compare them
double ceil_(double v, int p)
{
  v *= pow(10, p);
  v = ceil(v);
  v /= pow(10, p);
}

BOOST_AUTO_TEST_SUITE(pdbreader_test)

BOOST_AUTO_TEST_CASE(test_topologyreader){

    // Create pdb test file
    ofstream outfile("Molecule1.pdb");
    outfile << "COMPND    UNNAMED" << endl;
    outfile << "AUTHOR    GENERATED BY OPEN BABEL 2.4.1" << endl;
    outfile << "HETATM    1  C   UNL     1      -5.249   1.055  -0.000  1.00  0.00           C" << endl;
    outfile << "HETATM    2  H   UNL     1      -6.202   1.521  -0.141  1.00  0.00           H" << endl;
    outfile << "HETATM    3  H   UNL     1      -5.390   0.026   0.255  1.00  0.00           H" << endl;
    outfile << "HETATM    4  H   UNL     1      -4.682   1.124  -0.904  1.00  0.00           H" << endl;
    outfile << "HETATM    5  H   UNL     1      -4.724   1.550   0.790  1.00  0.00           H" << endl;
    outfile << "HETATM    6  C   UNL     2      -2.248   1.671  -0.000  1.00  0.00           C" << endl;
    outfile << "HETATM    7  H   UNL     2      -1.518   2.451   0.051  1.00  0.00           H" << endl;
    outfile << "HETATM    8  H   UNL     2      -3.153   1.999   0.467  1.00  0.00           H" << endl;
    outfile << "HETATM    9  H   UNL     2      -2.442   1.430  -1.024  1.00  0.00           H" << endl;
    outfile << "HETATM   10  H   UNL     2      -1.880   0.804   0.507  1.00  0.00           H" << endl;
    outfile << "CONECT    1    2    3    4    5" << endl;
    outfile << "CONECT    2    1" << endl;
    outfile << "CONECT    3    1" << endl;
    outfile << "CONECT    4    1" << endl;
    outfile << "CONECT    5    1" << endl;
    outfile << "CONECT    6    7    8    9   10" << endl;
    outfile << "CONECT    7    6" << endl;
    outfile << "CONECT    8    6" << endl;
    outfile << "CONECT    9    6" << endl;
    outfile << "CONECT   10    6" << endl;
    outfile << "MASTER        0    0    0    0    0    0    0    0   10    0   10    0" << endl;
    outfile << "END" << endl;
    outfile.close();

    Elements ele;

    Topology top;
    TopologyReader::RegisterPlugins();
    TopologyReader * reader;
    string str = "Molecule1.pdb";
    reader = TopReaderFactory().Create(str);
    reader->ReadTopology(str,top);
    BOOST_CHECK_EQUAL(reader!=NULL,true);
    BOOST_CHECK_EQUAL(top.BeadCount(),10);

// TODO wait to check mass after switch to elements.h
    int ind = 0;
    Bead * bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),0);
    BOOST_CHECK_EQUAL(bd->getName(),"C");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    vec v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.5249,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1055,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.000,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),0);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.6202,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1521,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.0141,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),0);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.539,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.0026,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(0.0255,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),0);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.4682,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1124,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.0904,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),0);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.4724,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1550,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.079,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),1);
    BOOST_CHECK_EQUAL(bd->getName(),"C");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.2248,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1671,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.000,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),1);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.1518,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.2451,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.0051,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),1);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.3153,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1999,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.0467,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),1);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.2442,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.1430,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.1024,3));

    ind++;
    bd = top.getBead(ind);
    BOOST_CHECK_EQUAL(bd->getId(),ind);
    BOOST_CHECK_EQUAL(bd->getResnr(),1);
    BOOST_CHECK_EQUAL(bd->getName(),"H");
//    BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    BOOST_CHECK_EQUAL(bd->getQ(),0);
    v = bd->getPos();
// Units in pdb file are in Ang units in csg are in nm
    BOOST_CHECK_EQUAL(ceil_(v.getX(),3),ceil_(-0.1880,3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(),3),ceil_(0.0804,3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(),3),ceil_(-0.0507,3));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>style commit<commit_after>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE pdbreader_test
#include <boost/test/unit_test.hpp>

#include <cmath>
#include <fstream>
#include <string>
#include <votca/csg/bead.h>
#include <votca/csg/topologyreader.h>
#include <votca/tools/elements.h>

using namespace std;
using namespace votca::csg;

// used for rounding doubles so we can compare them
double ceil_(double v, int p) {
  v *= pow(10, p);
  v = ceil(v);
  v /= pow(10, p);
}

BOOST_AUTO_TEST_SUITE(pdbreader_test)

BOOST_AUTO_TEST_CASE(test_topologyreader) {

  // Create pdb test file
  ofstream outfile("Molecule1.pdb");
  outfile << "COMPND    UNNAMED" << endl;
  outfile << "AUTHOR    GENERATED BY OPEN BABEL 2.4.1" << endl;
  outfile << "HETATM    1  C   UNL     1      -5.249   1.055  -0.000  1.00  "
             "0.00           C"
          << endl;
  outfile << "HETATM    2  H   UNL     1      -6.202   1.521  -0.141  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    3  H   UNL     1      -5.390   0.026   0.255  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    4  H   UNL     1      -4.682   1.124  -0.904  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    5  H   UNL     1      -4.724   1.550   0.790  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    6  C   UNL     2      -2.248   1.671  -0.000  1.00  "
             "0.00           C"
          << endl;
  outfile << "HETATM    7  H   UNL     2      -1.518   2.451   0.051  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    8  H   UNL     2      -3.153   1.999   0.467  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM    9  H   UNL     2      -2.442   1.430  -1.024  1.00  "
             "0.00           H"
          << endl;
  outfile << "HETATM   10  H   UNL     2      -1.880   0.804   0.507  1.00  "
             "0.00           H"
          << endl;
  outfile << "CONECT    1    2    3    4    5" << endl;
  outfile << "CONECT    2    1" << endl;
  outfile << "CONECT    3    1" << endl;
  outfile << "CONECT    4    1" << endl;
  outfile << "CONECT    5    1" << endl;
  outfile << "CONECT    6    7    8    9   10" << endl;
  outfile << "CONECT    7    6" << endl;
  outfile << "CONECT    8    6" << endl;
  outfile << "CONECT    9    6" << endl;
  outfile << "CONECT   10    6" << endl;
  outfile << "MASTER        0    0    0    0    0    0    0    0   10    0   "
             "10    0"
          << endl;
  outfile << "END" << endl;
  outfile.close();

  Elements ele;

  Topology top;
  TopologyReader::RegisterPlugins();
  TopologyReader* reader;
  string          str = "Molecule1.pdb";
  reader              = TopReaderFactory().Create(str);
  reader->ReadTopology(str, top);
  BOOST_CHECK_EQUAL(reader != NULL, true);
  BOOST_CHECK_EQUAL(top.BeadCount(), 10);

  vector<int> resnr = { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1};
  vector<string> bd_name = { "C", "H", "H", "H", "H", "C", "H", "H", "H", "H"};
  vector<double> x = { -0.5249, -0.6202,-0.539, -0.4682,-0.4724,-0.2248,-0.1518,-0.3153,-0.2442,-0.1880 };
  vector<double> y = { 0.1055 ,  0.1521,-0.0026, 0.1124, 0.1550, 0.1671, 0.2451, 0.1999, 0.1430, 0.0804 };
  vector<double> z = { -0.000 , -0.0141, 0.0255,-0.0904,-0.079 ,-0.000 ,-0.0051,-0.0467,-0.1024,-0.0507 };
  Bead* bd;
  vec v;
  for(int i=0;i<10;i++){
    bd = top.getBead(i);
    BOOST_CHECK_EQUAL(bd->getId(),i);
    BOOST_CHECK_EQUAL(bd->getResnr(),resnr.at(i));
    BOOST_CHECK_EQUAL(bd->getName(),bd_name.at(i));
  //BOOST_CHECK_EQUAL(bd->getM(),ele.getMass(bd->getName()));
    v = bd->getPos();
    BOOST_CHECK_EQUAL(bd->getQ(), 0);
    BOOST_CHECK_EQUAL(ceil_(v.getX(), 3), ceil_(x.at(i), 3));
    BOOST_CHECK_EQUAL(ceil_(v.getY(), 3), ceil_(y.at(i), 3));
    BOOST_CHECK_EQUAL(ceil_(v.getZ(), 3), ceil_(z.at(i), 3));
  }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>