<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 <vector>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

// A mock implementation of ExtensionsServiceFrontendInterface for testing the
// backend.
class ExtensionsServiceTestFrontend
    : public ExtensionsServiceFrontendInterface {
 public:
  ~ExtensionsServiceTestFrontend() {
    for (ExtensionList::iterator iter = extensions_.begin();
         iter != extensions_.end(); ++iter) {
      delete *iter;
    }
  }

  std::vector<std::string>* errors() {
    return &errors_;
  }

  ExtensionList* extensions() {
    return &extensions_;
  }

  // ExtensionsServiceFrontendInterface
  virtual MessageLoop* GetMessageLoop() {
    return &message_loop_;
  }

  virtual void OnExtensionLoadError(const std::string& message) {
    errors_.push_back(message);
  }

  virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) {
    extensions_.insert(extensions_.end(), new_extensions->begin(),
                       new_extensions->end());
    delete new_extensions;
  }

 private:
  MessageLoop message_loop_;
  ExtensionList extensions_;
  std::vector<std::string> errors_;
};

// make the test a PlatformTest to setup autorelease pools properly on mac
typedef PlatformTest ExtensionsServiceTest;

// Test loading extensions from the profile directory.
TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) {
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append(
      FILE_PATH_LITERAL("extensions"));

  scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend);
  scoped_refptr<ExtensionsServiceTestFrontend> frontend(
      new ExtensionsServiceTestFrontend);

  std::vector<Extension*> extensions;
  EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path,
      scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get())));
  frontend->GetMessageLoop()->RunAllPending();

  // Note: There can be more errors if there are extra directories, like .svn
  // directories.
  EXPECT_TRUE(frontend->errors()->size() >= 2u);
  EXPECT_EQ(2u, frontend->extensions()->size());

  EXPECT_EQ(std::wstring(L"com.google.myextension1"),
            frontend->extensions()->at(0)->id());
  EXPECT_EQ(std::wstring(L"My extension 1"),
            frontend->extensions()->at(0)->name());
  EXPECT_EQ(std::wstring(L"The first extension that I made."),
            frontend->extensions()->at(0)->description());
  EXPECT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size());
  EXPECT_EQ(std::wstring(L"script1.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(0));
  EXPECT_EQ(std::wstring(L"script2.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(1));

  EXPECT_EQ(std::wstring(L"com.google.myextension2"),
            frontend->extensions()->at(1)->id());
  EXPECT_EQ(std::wstring(L"My extension 2"),
            frontend->extensions()->at(1)->name());
  EXPECT_EQ(std::wstring(L""),
            frontend->extensions()->at(1)->description());
  EXPECT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size());
};
<commit_msg>Fix extensions_service_unittest on Linux.<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 <algorithm>
#include <vector>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extension.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

struct ExtensionsOrder {
  bool operator()(const Extension* a, const Extension* b) {
    return a->name() < b->name();
  }
};

}  // namespace

// A mock implementation of ExtensionsServiceFrontendInterface for testing the
// backend.
class ExtensionsServiceTestFrontend
    : public ExtensionsServiceFrontendInterface {
 public:
  ~ExtensionsServiceTestFrontend() {
    for (ExtensionList::iterator iter = extensions_.begin();
         iter != extensions_.end(); ++iter) {
      delete *iter;
    }
  }

  std::vector<std::string>* errors() {
    return &errors_;
  }

  ExtensionList* extensions() {
    return &extensions_;
  }

  // ExtensionsServiceFrontendInterface
  virtual MessageLoop* GetMessageLoop() {
    return &message_loop_;
  }

  virtual void OnExtensionLoadError(const std::string& message) {
    errors_.push_back(message);
  }

  virtual void OnExtensionsLoadedFromDirectory(ExtensionList* new_extensions) {
    extensions_.insert(extensions_.end(), new_extensions->begin(),
                       new_extensions->end());
    delete new_extensions;
    // In the tests we rely on extensions being in particular order,
    // which is not always the case (and is not guaranteed by used APIs).
    std::stable_sort(extensions_.begin(), extensions_.end(), ExtensionsOrder());
  }

 private:
  MessageLoop message_loop_;
  ExtensionList extensions_;
  std::vector<std::string> errors_;
};

// make the test a PlatformTest to setup autorelease pools properly on mac
typedef PlatformTest ExtensionsServiceTest;

// Test loading extensions from the profile directory.
TEST_F(ExtensionsServiceTest, LoadAllExtensionsFromDirectory) {
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath manifest_path = FilePath::FromWStringHack(extensions_dir).Append(
      FILE_PATH_LITERAL("extensions"));

  scoped_refptr<ExtensionsServiceBackend> backend(new ExtensionsServiceBackend);
  scoped_refptr<ExtensionsServiceTestFrontend> frontend(
      new ExtensionsServiceTestFrontend);

  std::vector<Extension*> extensions;
  EXPECT_TRUE(backend->LoadExtensionsFromDirectory(manifest_path,
      scoped_refptr<ExtensionsServiceFrontendInterface>(frontend.get())));
  frontend->GetMessageLoop()->RunAllPending();

  // Note: There can be more errors if there are extra directories, like .svn
  // directories.
  EXPECT_TRUE(frontend->errors()->size() >= 2u);
  ASSERT_EQ(2u, frontend->extensions()->size());

  EXPECT_EQ(std::wstring(L"com.google.myextension1"),
            frontend->extensions()->at(0)->id());
  EXPECT_EQ(std::wstring(L"My extension 1"),
            frontend->extensions()->at(0)->name());
  EXPECT_EQ(std::wstring(L"The first extension that I made."),
            frontend->extensions()->at(0)->description());
  ASSERT_EQ(2u, frontend->extensions()->at(0)->content_scripts().size());
  EXPECT_EQ(std::wstring(L"script1.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(0));
  EXPECT_EQ(std::wstring(L"script2.user.js"),
            frontend->extensions()->at(0)->content_scripts().at(1));

  EXPECT_EQ(std::wstring(L"com.google.myextension2"),
            frontend->extensions()->at(1)->id());
  EXPECT_EQ(std::wstring(L"My extension 2"),
            frontend->extensions()->at(1)->name());
  EXPECT_EQ(std::wstring(L""),
            frontend->extensions()->at(1)->description());
  ASSERT_EQ(0u, frontend->extensions()->at(1)->content_scripts().size());
};
<|endoftext|>


<commit_before>/**
 * \file
 * \brief StaticRawMessageQueue class header
 *
 * \author Copyright (C) 2015-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_
#define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_

#include "distortos/RawMessageQueue.hpp"

#include "distortos/internal/memory/dummyDeleter.hpp"

namespace distortos
{

/**
 * \brief StaticRawMessageQueue class is a variant of RawMessageQueue that has automatic storage for queue's contents.
 *
 * This class is a replacement for StaticRawMessageQueue with old API and removed StaticRawMessageQueueFromSize. To use
 * this new API modify your code in following way:
 * - old `"StaticRawMessageQueue<T, QueueSize>"` -> `"StaticRawMessageQueue<sizeof(T), QueueSize>"`;
 * - removed `"StaticRawMessageQueueFromSize<ElementSize, QueueSize>"` ->
 * `"StaticRawMessageQueue<ElementSize, QueueSize>"`;
 *
 * Transition schedule:
 * 1. v0.5.0 - `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` are
 * converted to deprecated aliases to `StaticRawMessageQueue2<ElementSize, QueueSize>`;
 * 2. v0.6.0 - "old" `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>`
 * aliases are removed, `StaticRawMessageQueue2<ElementSize, QueueSize>` is renamed to
 * `StaticRawMessageQueue<ElementSize, QueueSize>`, deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is
 * added;
 * 3. v0.7.0 - deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is removed;
 *
 * \tparam ElementSize is the size of single queue element, bytes
 * \tparam QueueSize is the maximum number of elements in queue
 *
 * \ingroup queues
 */

template<size_t ElementSize, size_t QueueSize>
class StaticRawMessageQueue : public RawMessageQueue
{
public:

	/**
	 * \brief StaticRawMessageQueue's constructor
	 */

	explicit StaticRawMessageQueue() :
			RawMessageQueue{{entryStorage_.data(), internal::dummyDeleter<EntryStorage>},
					{valueStorage_.data(), internal::dummyDeleter<uint8_t>}, ElementSize, QueueSize}
	{

	}

private:

	/// storage for queue's entries
	std::array<EntryStorage, QueueSize> entryStorage_;

	/// storage for queue's contents
	std::array<uint8_t, ElementSize * QueueSize> valueStorage_;
};

/**
 * \brief StaticRawMessageQueue2 class is a variant of RawMessageQueue that has automatic storage for queue's contents.
 *
 * \deprecated scheduled to be removed after v0.6.0, use `StaticRawMessageQueue<ElementSize, QueueSize>`
 *
 * \tparam ElementSize is the size of single queue element, bytes
 * \tparam QueueSize is the maximum number of elements in queue
 *
 * \ingroup queues
 */

template<size_t ElementSize, size_t QueueSize>
using StaticRawMessageQueue2 __attribute__ ((deprecated("Use StaticRawMessageQueue<ElementSize, QueueSize>"))) =
		StaticRawMessageQueue<ElementSize, QueueSize>;

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_
<commit_msg>Add constexpr static StaticRawMessageQueue::getElementSize()<commit_after>/**
 * \file
 * \brief StaticRawMessageQueue class header
 *
 * \author Copyright (C) 2015-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_
#define INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_

#include "distortos/RawMessageQueue.hpp"

#include "distortos/internal/memory/dummyDeleter.hpp"

namespace distortos
{

/**
 * \brief StaticRawMessageQueue class is a variant of RawMessageQueue that has automatic storage for queue's contents.
 *
 * This class is a replacement for StaticRawMessageQueue with old API and removed StaticRawMessageQueueFromSize. To use
 * this new API modify your code in following way:
 * - old `"StaticRawMessageQueue<T, QueueSize>"` -> `"StaticRawMessageQueue<sizeof(T), QueueSize>"`;
 * - removed `"StaticRawMessageQueueFromSize<ElementSize, QueueSize>"` ->
 * `"StaticRawMessageQueue<ElementSize, QueueSize>"`;
 *
 * Transition schedule:
 * 1. v0.5.0 - `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>` are
 * converted to deprecated aliases to `StaticRawMessageQueue2<ElementSize, QueueSize>`;
 * 2. v0.6.0 - "old" `StaticRawMessageQueue<T, QueueSize>` and `StaticRawMessageQueueFromSize<ElementSize, QueueSize>`
 * aliases are removed, `StaticRawMessageQueue2<ElementSize, QueueSize>` is renamed to
 * `StaticRawMessageQueue<ElementSize, QueueSize>`, deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is
 * added;
 * 3. v0.7.0 - deprecated `StaticRawMessageQueue2<ElementSize, QueueSize>` alias is removed;
 *
 * \tparam ElementSize is the size of single queue element, bytes
 * \tparam QueueSize is the maximum number of elements in queue
 *
 * \ingroup queues
 */

template<size_t ElementSize, size_t QueueSize>
class StaticRawMessageQueue : public RawMessageQueue
{
public:

	/**
	 * \brief StaticRawMessageQueue's constructor
	 */

	explicit StaticRawMessageQueue() :
			RawMessageQueue{{entryStorage_.data(), internal::dummyDeleter<EntryStorage>},
					{valueStorage_.data(), internal::dummyDeleter<uint8_t>}, ElementSize, QueueSize}
	{

	}

	/**
	 * \return size of single queue element, bytes
	 */

	constexpr static size_t getElementSize()
	{
		return ElementSize;
	}

private:

	/// storage for queue's entries
	std::array<EntryStorage, QueueSize> entryStorage_;

	/// storage for queue's contents
	std::array<uint8_t, ElementSize * QueueSize> valueStorage_;
};

/**
 * \brief StaticRawMessageQueue2 class is a variant of RawMessageQueue that has automatic storage for queue's contents.
 *
 * \deprecated scheduled to be removed after v0.6.0, use `StaticRawMessageQueue<ElementSize, QueueSize>`
 *
 * \tparam ElementSize is the size of single queue element, bytes
 * \tparam QueueSize is the maximum number of elements in queue
 *
 * \ingroup queues
 */

template<size_t ElementSize, size_t QueueSize>
using StaticRawMessageQueue2 __attribute__ ((deprecated("Use StaticRawMessageQueue<ElementSize, QueueSize>"))) =
		StaticRawMessageQueue<ElementSize, QueueSize>;

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICRAWMESSAGEQUEUE_HPP_
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/app/chrome_dll_resource.h"
#include "chrome/test/automated_ui_tests/automated_ui_test_base.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#if defined(OS_MACOSX)
// The window pops up, but doesn't close.
#define MAYBE_IncognitoWindow DISABLED_IncognitoWindow
#define MAYBE_OpenCloseBrowserWindowWithAccelerator \
    DISABLED_OpenCloseBrowserWindowWithAccelerator
#else
// http://code.google.com/p/chromium/issues/detail?id=14731
#define MAYBE_IncognitoWindow DISABLED_IncognitoWindow
#define MAYBE_OpenCloseBrowserWindowWithAccelerator \
    OpenCloseBrowserWindowWithAccelerator
#endif

// http://code.google.com/p/chromium/issues/detail?id=14774
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_CloseTab DISABLED_CloseTab
#define MAYBE_CloseBrowserWindow DISABLED_CloseBrowserWindow
#else
#define MAYBE_CloseTab CloseTab
#define MAYBE_CloseBrowserWindow CloseBrowserWindow
#endif

TEST_F(AutomatedUITestBase, NewTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
}

TEST_F(AutomatedUITestBase, DuplicateTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  DuplicateTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  DuplicateTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
}

TEST_F(AutomatedUITestBase, DISABLED_RestoreTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  FilePath path_prefix(test_data_directory_.AppendASCII("session_history"));
  GURL test_url = net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"));
  GetActiveTab()->NavigateToURL(test_url);
  CloseActiveTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  RestoreTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
}

TEST_F(AutomatedUITestBase, MAYBE_CloseTab) {
  int num_browser_windows;
  int tab_count;
  NewTab();
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);

  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  num_browser_windows = 0;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);

  // The browser window is closed by closing this tab.
  ASSERT_TRUE(CloseActiveTab());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  // Active_browser_ is now the first created window.
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);

  // The last tab should not be closed.
  ASSERT_FALSE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
}

TEST_F(AutomatedUITestBase, OpenBrowserWindow) {
  int num_browser_windows;
  int tab_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);

  scoped_refptr<BrowserProxy> browser_1;
  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_1));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  browser_1->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  scoped_refptr<BrowserProxy> browser_2;
  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_2));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  NewTab();
  browser_1->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  browser_2->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);

  bool application_closed;
  CloseBrowser(browser_1.get(), &application_closed);
  ASSERT_FALSE(application_closed);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  CloseBrowser(browser_2.get(), &application_closed);
  ASSERT_FALSE(application_closed);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, MAYBE_CloseBrowserWindow) {
  int tab_count;
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(4, tab_count);

  ASSERT_TRUE(CloseActiveWindow());
  active_browser()->GetTabCount(&tab_count);

  if (tab_count == 2) {
    ASSERT_TRUE(CloseActiveWindow());
    active_browser()->GetTabCount(&tab_count);
    ASSERT_EQ(3, tab_count);
  } else {
    ASSERT_EQ(3, tab_count);
    ASSERT_TRUE(CloseActiveWindow());
    active_browser()->GetTabCount(&tab_count);
    ASSERT_EQ(2, tab_count);
  }

  ASSERT_FALSE(CloseActiveWindow());
}

TEST_F(AutomatedUITestBase, MAYBE_IncognitoWindow) {
  int num_browser_windows;
  int num_normal_browser_windows;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  ASSERT_TRUE(GoOffTheRecord());
  ASSERT_TRUE(GoOffTheRecord());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  // There is only one normal window so it will not be closed.
  ASSERT_FALSE(CloseActiveWindow());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, MAYBE_OpenCloseBrowserWindowWithAccelerator) {
  // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close
  // browser window in automated ui tests. Instead we use
  // OpenAndActivateNewBrowserWindow and CloseActiveWindow.
  // There are other parts of UI test that use the accelerators. This is
  // a unit test for those usage.
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  int num_browser_windows;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(7, num_browser_windows);

  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(6, num_browser_windows);
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, Navigate) {
  FilePath path_prefix(test_data_directory_.AppendASCII("session_history"));
  GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html")));
  GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html")));
  GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html")));
  GURL url;
  ASSERT_TRUE(Navigate(url1));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url1, url);
  ASSERT_TRUE(Navigate(url2));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(Navigate(url3));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url3, url);
  ASSERT_TRUE(BackButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(BackButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url1, url);
  ASSERT_TRUE(ForwardButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(ReloadPage());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
}
<commit_msg>Mark AutomatedUITestBase.OpenCloseBrowserWindowWithAccelerator as a flakey crash, as it has been failing on vista debug bots consistently.<commit_after>// Copyright (c) 2009 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/app/chrome_dll_resource.h"
#include "chrome/test/automated_ui_tests/automated_ui_test_base.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#if defined(OS_MACOSX)
// The window pops up, but doesn't close.
#define MAYBE_IncognitoWindow DISABLED_IncognitoWindow
#define MAYBE_OpenCloseBrowserWindowWithAccelerator \
    DISABLED_OpenCloseBrowserWindowWithAccelerator
#else
// http://code.google.com/p/chromium/issues/detail?id=14731
#define MAYBE_IncognitoWindow DISABLED_IncognitoWindow
// http://crbug.com/19394
#define MAYBE_OpenCloseBrowserWindowWithAccelerator \
    DISABLED_OpenCloseBrowserWindowWithAccelerator
#endif

// http://code.google.com/p/chromium/issues/detail?id=14774
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_CloseTab DISABLED_CloseTab
#define MAYBE_CloseBrowserWindow DISABLED_CloseBrowserWindow
#else
#define MAYBE_CloseTab CloseTab
#define MAYBE_CloseBrowserWindow CloseBrowserWindow
#endif

TEST_F(AutomatedUITestBase, NewTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
}

TEST_F(AutomatedUITestBase, DuplicateTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  DuplicateTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  DuplicateTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
}

TEST_F(AutomatedUITestBase, DISABLED_RestoreTab) {
  int tab_count;
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  FilePath path_prefix(test_data_directory_.AppendASCII("session_history"));
  GURL test_url = net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"));
  GetActiveTab()->NavigateToURL(test_url);
  CloseActiveTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  RestoreTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
}

TEST_F(AutomatedUITestBase, MAYBE_CloseTab) {
  int num_browser_windows;
  int tab_count;
  NewTab();
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);

  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  num_browser_windows = 0;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);

  // The browser window is closed by closing this tab.
  ASSERT_TRUE(CloseActiveTab());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  // Active_browser_ is now the first created window.
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  ASSERT_TRUE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);

  // The last tab should not be closed.
  ASSERT_FALSE(CloseActiveTab());
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
}

TEST_F(AutomatedUITestBase, OpenBrowserWindow) {
  int num_browser_windows;
  int tab_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);

  scoped_refptr<BrowserProxy> browser_1;
  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_1));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  browser_1->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  scoped_refptr<BrowserProxy> browser_2;
  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&browser_2));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  NewTab();
  NewTab();
  browser_1->GetTabCount(&tab_count);
  ASSERT_EQ(1, tab_count);
  browser_2->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);

  bool application_closed;
  CloseBrowser(browser_1.get(), &application_closed);
  ASSERT_FALSE(application_closed);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  CloseBrowser(browser_2.get(), &application_closed);
  ASSERT_FALSE(application_closed);
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, MAYBE_CloseBrowserWindow) {
  int tab_count;
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(2, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(3, tab_count);

  ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL));
  NewTab();
  NewTab();
  NewTab();
  active_browser()->GetTabCount(&tab_count);
  ASSERT_EQ(4, tab_count);

  ASSERT_TRUE(CloseActiveWindow());
  active_browser()->GetTabCount(&tab_count);

  if (tab_count == 2) {
    ASSERT_TRUE(CloseActiveWindow());
    active_browser()->GetTabCount(&tab_count);
    ASSERT_EQ(3, tab_count);
  } else {
    ASSERT_EQ(3, tab_count);
    ASSERT_TRUE(CloseActiveWindow());
    active_browser()->GetTabCount(&tab_count);
    ASSERT_EQ(2, tab_count);
  }

  ASSERT_FALSE(CloseActiveWindow());
}

TEST_F(AutomatedUITestBase, MAYBE_IncognitoWindow) {
  int num_browser_windows;
  int num_normal_browser_windows;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  ASSERT_TRUE(GoOffTheRecord());
  ASSERT_TRUE(GoOffTheRecord());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  // There is only one normal window so it will not be closed.
  ASSERT_FALSE(CloseActiveWindow());
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(3, num_browser_windows);
  automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows);
  ASSERT_EQ(1, num_normal_browser_windows);

  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, MAYBE_OpenCloseBrowserWindowWithAccelerator) {
  // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close
  // browser window in automated ui tests. Instead we use
  // OpenAndActivateNewBrowserWindow and CloseActiveWindow.
  // There are other parts of UI test that use the accelerators. This is
  // a unit test for those usage.
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  int num_browser_windows;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(2, num_browser_windows);
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(7, num_browser_windows);

  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(6, num_browser_windows);
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  set_active_browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&num_browser_windows));
  ASSERT_EQ(1, num_browser_windows);
}

TEST_F(AutomatedUITestBase, Navigate) {
  FilePath path_prefix(test_data_directory_.AppendASCII("session_history"));
  GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html")));
  GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html")));
  GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html")));
  GURL url;
  ASSERT_TRUE(Navigate(url1));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url1, url);
  ASSERT_TRUE(Navigate(url2));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(Navigate(url3));
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url3, url);
  ASSERT_TRUE(BackButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(BackButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url1, url);
  ASSERT_TRUE(ForwardButton());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
  ASSERT_TRUE(ReloadPage());
  ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url));
  ASSERT_EQ(url2, url);
}
<|endoftext|>


<commit_before>#ifndef INC_AL_UTIL_CUBE_MAP_FBO_HPP
#define INC_AL_UTIL_CUBE_MAP_FBO_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	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 University of California 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 HOLDER 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.

	File description:
	A collection of utilities that are specific to OpenGL

	File author(s):
	Graham Wakefield, 2010, grrrwaaa@gmail.com
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_DisplayList.hpp"
#include "alloutil/al_TextureGL.hpp"

#include <stdio.h>

/*!

*/

namespace al {

class CubeMapFBO : public CubeMapTexture {
public:
	CubeMapFBO(int resolution=1024)
	:	CubeMapTexture(resolution),
		mFboId(0),
		mRboId(0),
		mClearColor(0)
	{}

	virtual ~CubeMapFBO() {}

	virtual void onCreate() {
		CubeMapTexture::onCreate();

		// one FBO to rule them all...
		glGenFramebuffersEXT(1, &mFboId);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId);
		//Attach one of the faces of the Cubemap texture to this FBO
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, id(), 0);

		glGenRenderbuffersEXT(1, &mRboId);
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRboId);
		glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mResolution, mResolution);
		// Attach depth buffer to FBO
		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mRboId);

		// ...and in the darkness bind them:
		for (unsigned face=0; face<6; face++) {
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+face, GL_TEXTURE_CUBE_MAP_POSITIVE_X+face, id(), 0);
		}

		//Does the GPU support current FBO configuration?
		GLenum status;
		status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
		if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
			printf("GPU does not support required FBO configuration\n");
			exit(0);
		}

		// cleanup:
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	}

	virtual void onDestroy() {
		glDeleteRenderbuffersEXT(1, &mRboId);
		glDeleteFramebuffersEXT(1, &mFboId);
		mRboId = mFboId = 0;

		CubeMapTexture::onDestroy();
	}

	void capture(Graphics& gl, const Camera& cam, const Pose& pose, Drawable& draw) {
		validate();

		glPushAttrib(GL_ALL_ATTRIB_BITS);

		Vec3d pos = pose.pos();
		Vec3d ux, uy, uz;
		pose.unitVectors(ux, uy, uz);
		mProjection = Matrix4d::perspective(90, 1, cam.near(), cam.far());

		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId);
		for (int face=0; face<6; face++) {
			glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT+face);

			gl.viewport(0, 0, resolution(), resolution());
			gl.clearColor(clearColor());
			gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

			switch (face) {
				case 0:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_X
					mModelView = Matrix4d::lookAt(uz, uy, -ux, pos);
					break;
				case 1:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_X
					mModelView = Matrix4d::lookAt(-uz, uy, ux, pos);
					break;
				case 2:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_Y
					mModelView = Matrix4d::lookAt(ux, -uz, uy, pos);
					break;
				case 3:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
					mModelView = Matrix4d::lookAt(ux, uz, -uy, pos);
					break;
				case 4:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_Z
					mModelView = Matrix4d::lookAt(ux, uy, uz, pos);
					break;
				default:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
					mModelView = Matrix4d::lookAt(-ux, uy, -uz, pos);
					break;
			}

			// apply camera transform:
			gl.pushMatrix(gl.PROJECTION);
			gl.loadMatrix(mProjection);
			gl.pushMatrix(gl.MODELVIEW);
			gl.loadMatrix(mModelView);

			draw.onDraw(gl);

			gl.popMatrix(gl.PROJECTION);
			gl.popMatrix(gl.MODELVIEW);
		}
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

		glPopAttrib();
	}

	Color clearColor() const { return mClearColor; }
	Matrix4d projection() const { return mProjection; }
	Matrix4d modelView() const { return mModelView; }
	GLuint fbo() { return mFboId; }
	GLuint rbo() { return mRboId; }

	CubeMapFBO& clearColor(const Color& c) { mClearColor = c; return *this; }

protected:
	GLuint mFboId, mRboId;
	Color mClearColor;
	Matrix4d mProjection;
	Matrix4d mModelView;
};

} // al::

#endif<commit_msg>cubefbo tweak<commit_after>#ifndef INC_AL_UTIL_CUBE_MAP_FBO_HPP
#define INC_AL_UTIL_CUBE_MAP_FBO_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	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 University of California 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 HOLDER 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.

	File description:
	A collection of utilities that are specific to OpenGL

	File author(s):
	Graham Wakefield, 2010, grrrwaaa@gmail.com
*/

#include "allocore/graphics/al_Graphics.hpp"
#include "allocore/graphics/al_Lens.hpp"
#include "allocore/graphics/al_DisplayList.hpp"
#include "alloutil/al_TextureGL.hpp"

#include <stdio.h>

/*!

*/

namespace al {

class CubeMapFBO : public CubeMapTexture {
public:
	CubeMapFBO(int resolution=1024)
	:	CubeMapTexture(resolution),
		mFboId(0),
		mRboId(0),
		mClearColor(0)
	{}

	virtual ~CubeMapFBO() {}

	virtual void onCreate() {
		CubeMapTexture::onCreate();

		// one FBO to rule them all...
		glGenFramebuffersEXT(1, &mFboId);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId);
		//Attach one of the faces of the Cubemap texture to this FBO
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, id(), 0);

		glGenRenderbuffersEXT(1, &mRboId);
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRboId);
		glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mResolution, mResolution);
		// Attach depth buffer to FBO
		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, mRboId);

		// ...and in the darkness bind them:
		for (unsigned face=0; face<6; face++) {
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+face, GL_TEXTURE_CUBE_MAP_POSITIVE_X+face, id(), 0);
		}

		//Does the GPU support current FBO configuration?
		GLenum status;
		status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
		if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
			printf("GPU does not support required FBO configuration\n");
			exit(0);
		}

		// cleanup:
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	}

	virtual void onDestroy() {
		glDeleteRenderbuffersEXT(1, &mRboId);
		glDeleteFramebuffersEXT(1, &mFboId);
		mRboId = mFboId = 0;

		CubeMapTexture::onDestroy();
	}

	void capture(Graphics& gl, const Lens& cam, const Pose& pose, Drawable& draw) {
		validate();

		glPushAttrib(GL_ALL_ATTRIB_BITS);

		Vec3d pos = pose.pos();
		Vec3d ux, uy, uz;
		pose.unitVectors(ux, uy, uz);
		mProjection = Matrix4d::perspective(90, 1, cam.near(), cam.far());

		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFboId);
		for (int face=0; face<6; face++) {
			glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT+face);

			gl.viewport(0, 0, resolution(), resolution());
			gl.clearColor(clearColor());
			gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

			switch (face) {
				case 0:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_X
					mModelView = Matrix4d::lookAt(uz, uy, -ux, pos);
					break;
				case 1:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_X
					mModelView = Matrix4d::lookAt(-uz, uy, ux, pos);
					break;
				case 2:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_Y
					mModelView = Matrix4d::lookAt(ux, -uz, uy, pos);
					break;
				case 3:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
					mModelView = Matrix4d::lookAt(ux, uz, -uy, pos);
					break;
				case 4:
					// GL_TEXTURE_CUBE_MAP_POSITIVE_Z
					mModelView = Matrix4d::lookAt(ux, uy, uz, pos);
					break;
				default:
					// GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
					mModelView = Matrix4d::lookAt(-ux, uy, -uz, pos);
					break;
			}

			// apply camera transform:
			gl.pushMatrix(gl.PROJECTION);
			gl.loadMatrix(mProjection);
			gl.pushMatrix(gl.MODELVIEW);
			gl.loadMatrix(mModelView);

			draw.onDraw(gl);

			gl.popMatrix(gl.PROJECTION);
			gl.popMatrix(gl.MODELVIEW);
		}
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

		glPopAttrib();
	}

	Color clearColor() const { return mClearColor; }
	Matrix4d projection() const { return mProjection; }
	Matrix4d modelView() const { return mModelView; }
	GLuint fbo() { return mFboId; }
	GLuint rbo() { return mRboId; }

	CubeMapFBO& clearColor(const Color& c) { mClearColor = c; return *this; }

protected:
	GLuint mFboId, mRboId;
	Color mClearColor;
	Matrix4d mProjection;
	Matrix4d mModelView;
};

} // al::

#endif<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <string>
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>

#include <searcher.hpp>

std::string path_to_string(Graph::Path_type& path)
{
    std::stringstream s;
    s << "[";
    BOOST_FOREACH (Graph::Node_type node, path) {
        s << node;
        if (node != path.back())
            s << " -> ";
    }
    s << "]";
    return s.str();
}

void check_path(Graph::Path_type& expected_path, Graph::Path_type &path)
{
    BOOST_REQUIRE_EQUAL(expected_path.size(), path.size());

    for (unsigned int i = 0; i < expected_path.size(); i++)
        if (expected_path.at(i) != path.at(i))
            BOOST_FAIL("Incorrect path: Expected "
                       << path_to_string(expected_path)
                       << " but got " << path_to_string(path) << ".");
}

struct Small_graph {
    Small_graph()
    {
        using namespace boost::assign;
        graph[1] = list_of(2)(3);
        graph[2] = list_of(1)(4);
        graph[3] = list_of(1)(6);
        graph[4] = list_of(2)(5)(6);
        graph[5] = list_of(4);
        graph[6] = list_of(3)(4)(7);
        graph[7] = list_of(6);
    }

    ~Small_graph() {}

    Graph::Graph_type graph;
};

struct Large_graph {
    Large_graph()
    {
        using namespace boost::assign;
        graph[1] = list_of(2)(3)(5)(6)(9);
        graph[2] = list_of(1)(4)(5)(10);
        graph[3] = list_of(1)(4)(7);
        graph[4] = list_of(2)(3)(5)(8)(10);
        graph[5] = list_of(1)(2)(4);
        graph[6] = list_of(1)(9);
        graph[7] = list_of(3)(8)(16);
        graph[8] = list_of(4)(7);
        graph[9] = list_of(1)(6)(11);
        graph[10] = list_of(2)(4)(13);
        graph[11] = list_of(9)(14);
        graph[12] = list_of(8)(14)(15);
        graph[13] = list_of(10);
        graph[14] = list_of(11)(12);
        graph[15] = list_of(12);
        graph[16] = list_of(7);
    }

    ~Large_graph() {}

    Graph::Graph_type graph;
};

BOOST_FIXTURE_TEST_CASE(test_simple_path, Small_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 7, 5);
    BOOST_REQUIRE_MESSAGE(path.size() > 0, "No path was found.");

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(1)(3)(6)(7);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_impossible_path, Small_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 1000, 5);
    BOOST_REQUIRE_MESSAGE(path.size() == 0,
                          "A path was found, although there can't be one.");
}

BOOST_FIXTURE_TEST_CASE(test_complex1, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(15, 16, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(15)(12)(8)(7)(16);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex2, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 14, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(1)(9)(11)(14);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex3, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(13, 5, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(13)(10)(2)(5);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex4, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(2, 14, 5);

    using namespace boost::assign;
    // 2 -> 4 -> 8 -> 12 -> 14 would be correct as well
    Graph::Path_type expected_path = list_of(2)(1)(9)(11)(14);
    check_path(expected_path, path);
}
<commit_msg>Refactored searcher test case.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <string>
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include <searcher.hpp>

std::string path_to_string(Graph::Path_type& path)
{
    std::stringstream s;
    s << "[";
    BOOST_FOREACH (Graph::Node_type node, path) {
        s << node;
        if (node != path.back())
            s << " -> ";
    }
    s << "]";
    return s.str();
}

void check_path(Graph::Path_type& expected_path, Graph::Path_type &path)
{
    BOOST_REQUIRE_EQUAL(expected_path.size(), path.size());

    for (unsigned int i = 0; i < expected_path.size(); i++)
        if (expected_path.at(i) != path.at(i))
            BOOST_FAIL("Incorrect path: Expected "
                       << path_to_string(expected_path)
                       << " but got " << path_to_string(path) << ".");
}

struct Small_graph {
    Graph::Graph_type graph;

    Small_graph()
    {
        using namespace boost::assign;
        graph[1] = list_of(2)(3);
        graph[2] = list_of(1)(4);
        graph[3] = list_of(1)(6);
        graph[4] = list_of(2)(5)(6);
        graph[5] = list_of(4);
        graph[6] = list_of(3)(4)(7);
        graph[7] = list_of(6);
    }
};

struct Large_graph {
    Graph::Graph_type graph;

    Large_graph()
    {
        using namespace boost::assign;
        graph[1] = list_of(2)(3)(5)(6)(9);
        graph[2] = list_of(1)(4)(5)(10);
        graph[3] = list_of(1)(4)(7);
        graph[4] = list_of(2)(3)(5)(8)(10);
        graph[5] = list_of(1)(2)(4);
        graph[6] = list_of(1)(9);
        graph[7] = list_of(3)(8)(16);
        graph[8] = list_of(4)(7);
        graph[9] = list_of(1)(6)(11);
        graph[10] = list_of(2)(4)(13);
        graph[11] = list_of(9)(14);
        graph[12] = list_of(8)(14)(15);
        graph[13] = list_of(10);
        graph[14] = list_of(11)(12);
        graph[15] = list_of(12);
        graph[16] = list_of(7);
    }
};

BOOST_FIXTURE_TEST_CASE(test_simple_path, Small_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 7, 5);
    BOOST_REQUIRE_MESSAGE(path.size() > 0, "No path was found.");

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(1)(3)(6)(7);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_impossible_path, Small_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 1000, 5);
    BOOST_REQUIRE_MESSAGE(path.size() == 0,
                          "A path was found, although there can't be one.");
}

BOOST_FIXTURE_TEST_CASE(test_complex1, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(15, 16, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(15)(12)(8)(7)(16);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex2, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(1, 14, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(1)(9)(11)(14);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex3, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(13, 5, 5);

    using namespace boost::assign;
    Graph::Path_type expected_path = list_of(13)(10)(2)(5);
    check_path(expected_path, path);
}

BOOST_FIXTURE_TEST_CASE(test_complex4, Large_graph)
{
    Searcher s(graph);
    Graph::Path_type path = s.find_shortest_path(2, 14, 5);

    using namespace boost::assign;
    // 2 -> 4 -> 8 -> 12 -> 14 would be correct as well
    Graph::Path_type expected_path = list_of(2)(1)(9)(11)(14);
    check_path(expected_path, path);
}
<|endoftext|>


<commit_before>#include "eventblock.h"
#include <ctime>
#include <iostream>
#include <cstdlib>

using namespace std;

// Constructor & Destructor
EventBlock::EventBlock(QGameItem * parent) : Block(parent)
{
}

EventBlock::~EventBlock()
{

}

// Methods
void EventBlock::enter(Player* player)
{

}

void EventBlock::checkEvent(Player* player)
{
    // 이벤트 블럭을 밟을시 실행하여 랜덤한 이벤트 발생
    srand((unsigned)time(NULL));
    int value = rand() % 7;
    switch(value) {
    case 0:
        drink(player);
        break;
    case 1:
        cc(player);
        break;
    case 2:
        takeSubject(player);
        break;
    case 3:
        loseSubject(player);
        break;
    case 4:
        lol(player);
        break;
    case 5:
        eatChicken(player);
        break;
    case 6:
        photoGenic();
        break;
    }
}
//전체적으로 수정 바람.
void EventBlock::drink(Player* player)
{
    // 음주칸으로 이동
    player->setEnergy(player->getEnergy() - 100); //
}

void EventBlock::cc(Player* player)
{
    // 행동력 감소 + 일정 확률로 휴학 또는 61콜 이동
    if(getType()!=CharacterType::OUTSIDER)
    {
        player->setEnergy(player->getEnergy() - 100); //
    }
}

void EventBlock::takeSubject(Player* player)
{
    // 플레이어가 과목을 하나 선택한 후 buyBlock을 실행한다
    //player->buyBlock();
}

void EventBlock::loseSubject(Player* player)
{
    // 플레이어가 과목 하나를 잃는다. (랜덤 or 선택)
    //player->sellBlock();
}

void EventBlock::lol(Player* player)
{
    // 50:50으로 행동력 증가 또는 감소, lol타입 캐릭터의 경우 항상 증가
    if(getType()==CharacterType::LOL)
    player->setEnergy(player->getEnergy() +50); //
    else
    {
        int outcome;
        outcome=rand()%2;
        if(outcome==0)
        player->setEnergy(player->getEnergy()+50);
        else
        player->setEnergy(player->getEnergy()-100);
    }
}

void EventBlock::eatChicken(Player* player)
{
    // 치느님을 영접하여 행동력 증가
    player->setEnergy(player->getEnergy() + 100);

}

void EventBlock::photoGenic()
{
    //팀원 사진 띄우기
}
<commit_msg>CC does not neded pay for itself / drink need fix<commit_after>#include "eventblock.h"
#include <ctime>
#include <iostream>
#include <cstdlib>

using namespace std;

// Constructor & Destructor
EventBlock::EventBlock(QGameItem * parent) : Block(parent)
{
}

EventBlock::~EventBlock()
{

}

// Methods
void EventBlock::enter(Player* player)
{

}

void EventBlock::checkEvent(Player* player)
{
    // 이벤트 블럭을 밟을시 실행하여 랜덤한 이벤트 발생
    srand((unsigned)time(NULL));
    int value = rand() % 7;
    switch(value) {
    case 0:
        drink(player);
        break;
    case 1:
        cc(player);
        break;
    case 2:
        takeSubject(player);
        break;
    case 3:
        loseSubject(player);
        break;
    case 4:
        lol(player);
        break;
    case 5:
        eatChicken(player);
        break;
    case 6:
        photoGenic();
        break;
    }
}
//전체적으로 수정 바람.
void EventBlock::drink(Player* player)
{
    // 음주칸으로 이동
    player->setEnergy(player->getEnergy() - 100); //
}

void EventBlock::cc(Player* player)
{
    // 행동력 감소 + 일정 확률로 휴학 또는 61콜 이동
    if(getType()!=CharacterType::OUTSIDER)
    {
    }
}

void EventBlock::takeSubject(Player* player)
{
    // 플레이어가 과목을 하나 선택한 후 buyBlock을 실행한다
    //player->buyBlock();
}

void EventBlock::loseSubject(Player* player)
{
    // 플레이어가 과목 하나를 잃는다. (랜덤 or 선택)
    //player->sellBlock();
}

void EventBlock::lol(Player* player)
{
    // 50:50으로 행동력 증가 또는 감소, lol타입 캐릭터의 경우 항상 증가
    if(getType()==CharacterType::LOL)
    player->setEnergy(player->getEnergy() +50); //
    else
    {
        int outcome;
        outcome=rand()%2;
        if(outcome==0)
        player->setEnergy(player->getEnergy()+50);
        else
        player->setEnergy(player->getEnergy()-100);
    }
}

void EventBlock::eatChicken(Player* player)
{
    // 치느님을 영접하여 행동력 증가
    player->setEnergy(player->getEnergy() + 100);

}

void EventBlock::photoGenic()
{
    //팀원 사진 띄우기
}
<|endoftext|>


<commit_before>// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <type_traits>
#include <utility>

#include <hadesmem/config.hpp>

namespace hadesmem
{

namespace detail
{

template <typename T> class Optional
{
public:
  HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
  {
  }

  explicit Optional(T const& t)
  {
    Construct(t);
  }

  explicit Optional(T&& t)
  {
    Construct(std::move(t));
  }

  Optional(Optional const& other)
  {
    if (other.valid_)
    {
      Construct(other.Get());
    }
  }

  Optional& operator=(Optional const& other)
  {
    Optional tmp{other};
    *this = std::move(tmp);

    return *this;
  }

  Optional(Optional&& other)
  {
    if (other.valid_)
    {
      Construct(std::move(other.Get()));
    }

    other.valid_ = false;
  }

  Optional& operator=(Optional&& other)
  {
    Destroy();

    if (other.valid_)
    {
      Construct(std::move(other.Get()));
    }

    other.valid_ = false;

    return *this;
  }

  Optional& operator=(T const& t)
  {
    Destroy();
    Construct(t);

    return *this;
  }

  Optional& operator=(T&& t)
  {
    Destroy();
    Construct(std::move(t));

    return *this;
  }

  ~Optional()
  {
    Destroy();
  }

  explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT
  {
    return valid_;
  }

  T& Get() HADESMEM_DETAIL_NOEXCEPT
  {
    return *GetPtr();
  }

  T const& Get() const HADESMEM_DETAIL_NOEXCEPT
  {
    return *GetPtr();
  }

  T& operator*() HADESMEM_DETAIL_NOEXCEPT
  {
    return Get();
  }

  T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
  {
    return Get();
  }

  T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
  {
    return static_cast<T*>(static_cast<void*>(&t_));
  }

  T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
  {
    return static_cast<T const*>(static_cast<void const*>(&t_));
  }

  T* operator->() HADESMEM_DETAIL_NOEXCEPT
  {
    return GetPtr();
  }

  T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
  {
    return GetPtr();
  }

private:
  template <typename U> void Construct(U&& u)
  {
    if (valid_)
    {
      Destroy();
    }

    new (&t_) T(std::forward<U>(u));
    valid_ = true;
  }

  void Destroy() HADESMEM_DETAIL_NOEXCEPT
  {
    if (valid_)
    {
      GetPtr()->~T();
      valid_ = false;
    }
  }

  std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_{};
  bool valid_{false};
};

template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}

template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return !(lhs == rhs);
}

template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<commit_msg>* [Optional] Avoid new overloads.<commit_after>// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <type_traits>
#include <utility>

#include <hadesmem/config.hpp>

namespace hadesmem
{

namespace detail
{

template <typename T> class Optional
{
public:
  HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT
  {
  }

  explicit Optional(T const& t)
  {
    Construct(t);
  }

  explicit Optional(T&& t)
  {
    Construct(std::move(t));
  }

  Optional(Optional const& other)
  {
    if (other.valid_)
    {
      Construct(other.Get());
    }
  }

  Optional& operator=(Optional const& other)
  {
    Optional tmp{other};
    *this = std::move(tmp);

    return *this;
  }

  Optional(Optional&& other)
  {
    if (other.valid_)
    {
      Construct(std::move(other.Get()));
    }

    other.valid_ = false;
  }

  Optional& operator=(Optional&& other)
  {
    Destroy();

    if (other.valid_)
    {
      Construct(std::move(other.Get()));
    }

    other.valid_ = false;

    return *this;
  }

  Optional& operator=(T const& t)
  {
    Destroy();
    Construct(t);

    return *this;
  }

  Optional& operator=(T&& t)
  {
    Destroy();
    Construct(std::move(t));

    return *this;
  }

  ~Optional()
  {
    Destroy();
  }

  explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT
  {
    return valid_;
  }

  T& Get() HADESMEM_DETAIL_NOEXCEPT
  {
    return *GetPtr();
  }

  T const& Get() const HADESMEM_DETAIL_NOEXCEPT
  {
    return *GetPtr();
  }

  T& operator*() HADESMEM_DETAIL_NOEXCEPT
  {
    return Get();
  }

  T const& operator*() const HADESMEM_DETAIL_NOEXCEPT
  {
    return Get();
  }

  T* GetPtr() HADESMEM_DETAIL_NOEXCEPT
  {
    return static_cast<T*>(static_cast<void*>(&t_));
  }

  T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT
  {
    return static_cast<T const*>(static_cast<void const*>(&t_));
  }

  T* operator->() HADESMEM_DETAIL_NOEXCEPT
  {
    return GetPtr();
  }

  T const* operator->() const HADESMEM_DETAIL_NOEXCEPT
  {
    return GetPtr();
  }

private:
  template <typename U> void Construct(U&& u)
  {
    if (valid_)
    {
      Destroy();
    }

	// Avoid picking up placement new overloads
    ::new (static_cast<void*>(&t_)) T(std::forward<U>(u));
    valid_ = true;
  }

  void Destroy() HADESMEM_DETAIL_NOEXCEPT
  {
    if (valid_)
    {
      GetPtr()->~T();
      valid_ = false;
    }
  }

  std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_{};
  bool valid_{false};
};

template <typename T>
inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);
}

template <typename T>
inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return !(lhs == rhs);
}

template <typename T>
inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)
{
  return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);
}
}
}
<|endoftext|>


<commit_before>/**
 * response_status.hpp
 *
 *  Created on: 28 авг. 2015 г.
 *      Author: zmij
 */

#ifndef TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_
#define TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_

namespace tip {
namespace http {

/** The status of the reply.
 * [RFC 2616 Fielding, et al.](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
 */
enum class response_status {
	/** Informational */
	continue_						= 100,
	switching_protocols				= 101,
	/** Successful */
	ok								= 200,
	created							= 201,
	accepted						= 202,
	non_authoritative_information	= 203,
	no_content						= 204,
	reset_content					= 205,
	partial_content					= 206,
	/** Redirection */
	multiple_choices				= 300,
	moved_permanently				= 301,
	found							= 302,
	see_other						= 303,
	not_modified					= 304,
	use_proxy						= 305,
	temporary_redirect				= 307,
	/** Client error */
	bad_request						= 400,
	unauthorized					= 401,
	payment_required				= 402,
	forbidden						= 403,
	not_found						= 404,
	method_not_allowed				= 405,
	not_acceptable					= 406,
	proxy_authentication_required	= 407,
	request_timeout					= 408,
	conflict						= 409,
	gone							= 410,
	length_required					= 411,
	precondition_failed				= 412,
	request_entity_too_large		= 413,
	request_uri_too_long			= 414,
	unsupported_media_type			= 415,
	requested_range_not_satisfiable	= 416,
	expectation_failed				= 417,
	/** Server error */
	internal_server_error			= 500,
	not_implemented					= 501,
	bad_gateway						= 502,
	service_unavailable				= 503,
	gateway_timeout					= 504,
	http_version_not_supported		= 505
};  // enum response_status

enum class response_class {
	informational		= 0x01,
	successful			= 0x02,
	redirection			= 0x04,
	client_error		= 0x08,
	server_error		= 0x10
};

inline response_class
status_class(response_status s)
{
	return static_cast< response_class >( static_cast< int >(s) / 100 );
}

inline bool
is_error(response_status s)
{
	return static_cast< int >(s) / 100 >= 4;
}

inline bool
is_error(response_class c)
{
	return c >= response_class::client_error;
}

inline ::std::ostream&
operator << (::std::ostream& os, response_status const& val)
{
	std::ostream::sentry s(os);
	if (s) {
		os << static_cast<int>(val);
	}
	return os;
}

}  // namespace http
}  // namespace tip

#endif /* TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ */
<commit_msg>Fix missing include<commit_after>/**
 * response_status.hpp
 *
 *  Created on: 28 авг. 2015 г.
 *      Author: zmij
 */

#ifndef TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_
#define TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_

#include <iostream>

namespace tip {
namespace http {

/** The status of the reply.
 * [RFC 2616 Fielding, et al.](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
 */
enum class response_status {
	/** Informational */
	continue_						= 100,
	switching_protocols				= 101,
	/** Successful */
	ok								= 200,
	created							= 201,
	accepted						= 202,
	non_authoritative_information	= 203,
	no_content						= 204,
	reset_content					= 205,
	partial_content					= 206,
	/** Redirection */
	multiple_choices				= 300,
	moved_permanently				= 301,
	found							= 302,
	see_other						= 303,
	not_modified					= 304,
	use_proxy						= 305,
	temporary_redirect				= 307,
	/** Client error */
	bad_request						= 400,
	unauthorized					= 401,
	payment_required				= 402,
	forbidden						= 403,
	not_found						= 404,
	method_not_allowed				= 405,
	not_acceptable					= 406,
	proxy_authentication_required	= 407,
	request_timeout					= 408,
	conflict						= 409,
	gone							= 410,
	length_required					= 411,
	precondition_failed				= 412,
	request_entity_too_large		= 413,
	request_uri_too_long			= 414,
	unsupported_media_type			= 415,
	requested_range_not_satisfiable	= 416,
	expectation_failed				= 417,
	/** Server error */
	internal_server_error			= 500,
	not_implemented					= 501,
	bad_gateway						= 502,
	service_unavailable				= 503,
	gateway_timeout					= 504,
	http_version_not_supported		= 505
};  // enum response_status

enum class response_class {
	informational		= 0x01,
	successful			= 0x02,
	redirection			= 0x04,
	client_error		= 0x08,
	server_error		= 0x10
};

inline response_class
status_class(response_status s)
{
	return static_cast< response_class >( static_cast< int >(s) / 100 );
}

inline bool
is_error(response_status s)
{
	return static_cast< int >(s) / 100 >= 4;
}

inline bool
is_error(response_class c)
{
	return c >= response_class::client_error;
}

inline ::std::ostream&
operator << (::std::ostream& os, response_status const& val)
{
	std::ostream::sentry s(os);
	if (s) {
		os << static_cast<int>(val);
	}
	return os;
}

}  // namespace http
}  // namespace tip

#endif /* TIP_HTTP_COMMON_RESPONSE_STATUS_HPP_ */
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cstddef>
#include <type_traits>
#include <utility>

#include <visionaray/math/limits.h>
#include <visionaray/math/ray.h>
#include <visionaray/intersector.h>
#include <visionaray/update_if.h>

#include "../exit_traversal.h"
#include "../multi_hit.h"
#include "../stack.h"
#include "../tags.h"
#include "../traversal_result.h"
#include "hit_record.h"

namespace visionaray
{

//-------------------------------------------------------------------------------------------------
// Ray / BVH intersection
//

template <
    detail::traversal_type Traversal,
    size_t MultiHitMax = 1,             // Max hits for multi-hit traversal
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Intersector,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Intersector&        isect,
        T                   max_t = numeric_limits<T>::max(),
        Cond                update_cond = Cond()
        )
    -> typename detail::traversal_result< hit_record_bvh<
            basic_ray<T>,
            decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
            >, Traversal, MultiHitMax>::type
{

    using namespace detail;
    using HR = hit_record_bvh<
        basic_ray<T>,
        decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
        >;

    using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;

    RT result;

    stack<64> st;
    st.push(0); // address of root node

    auto inv_dir = T(1.0) / ray.dir;

    // while ray not terminated
next:
    while (!st.empty())
    {
        auto node = b.node(st.pop());

        // while node does not contain primitives
        //     traverse to the next node

        while (!is_leaf(node))
        {
            auto children = &b.node(node.get_child(0));

            auto hr1 = isect(ray, children[0].get_bounds(), inv_dir);
            auto hr2 = isect(ray, children[1].get_bounds(), inv_dir);

            auto b1 = any( is_closer(hr1, result, max_t) );
            auto b2 = any( is_closer(hr2, result, max_t) );

            if (b1 && b2)
            {
                unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1;
                st.push(node.get_child(!near_addr));
                node = b.node(node.get_child(near_addr));
            }
            else if (b1)
            {
                node = b.node(node.get_child(0));
            }
            else if (b2)
            {
                node = b.node(node.get_child(1));
            }
            else
            {
                goto next;
            }
        }

        // while node contains untested primitives
        //     perform a ray-primitive intersection test

        for (auto i = node.get_indices().first; i != node.get_indices().last; ++i)
        {
            auto prim = b.primitive(i);

            auto hr = HR(isect(ray, prim), i);
            auto closer = update_cond(hr, result, max_t);

#ifndef __CUDA_ARCH__
            if (!any(closer))
            {
                continue;
            }
#endif

            update_if(result, hr, closer);

            exit_traversal<Traversal> early_exit;
            if (early_exit.check(result))
            {
                return result;
            }
        }
    }

    return result;

}

//-------------------------------------------------------------------------------------------------
// Default intersect returns closest hit!
//

// overload w/ custom intersector -------------------------

template <
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Intersector,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Intersector&        isect,
        Cond                update_cond = Cond()
        )
    -> hit_record_bvh<
        basic_ray<T>,
        decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
        >
{
    return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);
}

// overload w/ default intersector ------------------------

template <
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Cond                update_cond = Cond()
        )
    -> hit_record_bvh<
        basic_ray<T>,
        decltype( intersect(ray, std::declval<typename BVH::primitive_type>()) )
        >
{
    default_intersector isect;
    return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);
}

} // visionaray
<commit_msg>Revert "Use a 64 entry stack for BVH traversal"<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cstddef>
#include <type_traits>
#include <utility>

#include <visionaray/math/limits.h>
#include <visionaray/math/ray.h>
#include <visionaray/intersector.h>
#include <visionaray/update_if.h>

#include "../exit_traversal.h"
#include "../multi_hit.h"
#include "../stack.h"
#include "../tags.h"
#include "../traversal_result.h"
#include "hit_record.h"

namespace visionaray
{

//-------------------------------------------------------------------------------------------------
// Ray / BVH intersection
//

template <
    detail::traversal_type Traversal,
    size_t MultiHitMax = 1,             // Max hits for multi-hit traversal
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Intersector,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Intersector&        isect,
        T                   max_t = numeric_limits<T>::max(),
        Cond                update_cond = Cond()
        )
    -> typename detail::traversal_result< hit_record_bvh<
            basic_ray<T>,
            decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
            >, Traversal, MultiHitMax>::type
{

    using namespace detail;
    using HR = hit_record_bvh<
        basic_ray<T>,
        decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
        >;

    using RT = typename detail::traversal_result<HR, Traversal, MultiHitMax>::type;

    RT result;

    stack<32> st;
    st.push(0); // address of root node

    auto inv_dir = T(1.0) / ray.dir;

    // while ray not terminated
next:
    while (!st.empty())
    {
        auto node = b.node(st.pop());

        // while node does not contain primitives
        //     traverse to the next node

        while (!is_leaf(node))
        {
            auto children = &b.node(node.get_child(0));

            auto hr1 = isect(ray, children[0].get_bounds(), inv_dir);
            auto hr2 = isect(ray, children[1].get_bounds(), inv_dir);

            auto b1 = any( is_closer(hr1, result, max_t) );
            auto b2 = any( is_closer(hr2, result, max_t) );

            if (b1 && b2)
            {
                unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1;
                st.push(node.get_child(!near_addr));
                node = b.node(node.get_child(near_addr));
            }
            else if (b1)
            {
                node = b.node(node.get_child(0));
            }
            else if (b2)
            {
                node = b.node(node.get_child(1));
            }
            else
            {
                goto next;
            }
        }

        // while node contains untested primitives
        //     perform a ray-primitive intersection test

        for (auto i = node.get_indices().first; i != node.get_indices().last; ++i)
        {
            auto prim = b.primitive(i);

            auto hr = HR(isect(ray, prim), i);
            auto closer = update_cond(hr, result, max_t);

#ifndef __CUDA_ARCH__
            if (!any(closer))
            {
                continue;
            }
#endif

            update_if(result, hr, closer);

            exit_traversal<Traversal> early_exit;
            if (early_exit.check(result))
            {
                return result;
            }
        }
    }

    return result;

}

//-------------------------------------------------------------------------------------------------
// Default intersect returns closest hit!
//

// overload w/ custom intersector -------------------------

template <
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Intersector,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Intersector&        isect,
        Cond                update_cond = Cond()
        )
    -> hit_record_bvh<
        basic_ray<T>,
        decltype( isect(ray, std::declval<typename BVH::primitive_type>()) )
        >
{
    return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);
}

// overload w/ default intersector ------------------------

template <
    typename T,
    typename BVH,
    typename = typename std::enable_if<is_any_bvh<BVH>::value>::type,
    typename Cond = is_closer_t
    >
VSNRAY_FUNC
inline auto intersect(
        basic_ray<T> const& ray,
        BVH const&          b,
        Cond                update_cond = Cond()
        )
    -> hit_record_bvh<
        basic_ray<T>,
        decltype( intersect(ray, std::declval<typename BVH::primitive_type>()) )
        >
{
    default_intersector isect;
    return intersect<detail::ClosestHit>(ray, b, isect, numeric_limits<T>::max(), update_cond);
}

} // visionaray
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/bitcoin/utility/path.hpp>
#include <boost/thread/once.hpp>

#ifdef _WIN32
#include <Shlobj.h>
#endif

namespace libbitcoin{

const boost::filesystem::path& default_data_path()
{
    static boost::filesystem::path default_path("");
    static boost::once_flag once = BOOST_ONCE_INIT;
    auto path_init = []() {
        namespace fs = boost::filesystem;
        // Windows < Vista: C:\Documents and Settings\Username\Application Data\Metaverse
        // Windows >= Vista: C:\Users\Username\AppData\Roaming\Metaverse
        // Mac: ~/Library/Application Support/Metaverse
        // Unix: ~/.metaverse
#ifdef _WIN32
        // Windows
#ifdef UNICODE
        wchar_t file_path[MAX_PATH] = { 0 };
#else
        char file_path[MAX_PATH] = { 0 };
#endif
        SHGetSpecialFolderPath(NULL, file_path, CSIDL_APPDATA, true);
        fs::path pathRet = boost::filesystem::path(file_path) / "Metaverse";
        fs::create_directories(pathRet);
        default_path = pathRet;
#else
        fs::path pathRet;
        char* pszHome = getenv("HOME");
        if (pszHome == nullptr || strlen(pszHome) == 0)
            pathRet = fs::path("/");
        else
            pathRet = fs::path(pszHome);
#ifdef MAC_OSX
        // Mac
        pathRet /= "Library/Application Support";
        fs::create_directories(pathRet / "Metaverse");
        default_path = pathRet / "Metaverse";
#else
        // Unix
        fs::create_directories(pathRet / ".metaverse");
        default_path = pathRet / ".metaverse";
#endif
#endif
    };
    boost::call_once(path_init, once);
    return default_path;
}

boost::filesystem::path webpage_path()
{
	return default_data_path() / "mvs-htmls";
}

}//namespace libbitcoin

<commit_msg>#139 modify windows webpath dir<commit_after>/**
 * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse.
 *
 * metaverse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <metaverse/bitcoin/utility/path.hpp>
#include <boost/thread/once.hpp>

#ifdef _WIN32
#include <Shlobj.h>
#endif

namespace libbitcoin{

const boost::filesystem::path& default_data_path()
{
    static boost::filesystem::path default_path("");
    static boost::once_flag once = BOOST_ONCE_INIT;
    auto path_init = []() {
        namespace fs = boost::filesystem;
        // Windows < Vista: C:\Documents and Settings\Username\Application Data\Metaverse
        // Windows >= Vista: C:\Users\Username\AppData\Roaming\Metaverse
        // Mac: ~/Library/Application Support/Metaverse
        // Unix: ~/.metaverse
#ifdef _WIN32
        // Windows
#ifdef UNICODE
        wchar_t file_path[MAX_PATH] = { 0 };
#else
        char file_path[MAX_PATH] = { 0 };
#endif
        SHGetSpecialFolderPath(NULL, file_path, CSIDL_APPDATA, true);
        fs::path pathRet = boost::filesystem::path(file_path) / "Metaverse";
        fs::create_directories(pathRet);
        default_path = pathRet;
#else
        fs::path pathRet;
        char* pszHome = getenv("HOME");
        if (pszHome == nullptr || strlen(pszHome) == 0)
            pathRet = fs::path("/");
        else
            pathRet = fs::path(pszHome);
#ifdef MAC_OSX
        // Mac
        pathRet /= "Library/Application Support";
        fs::create_directories(pathRet / "Metaverse");
        default_path = pathRet / "Metaverse";
#else
        // Unix
        fs::create_directories(pathRet / ".metaverse");
        default_path = pathRet / ".metaverse";
#endif
#endif
    };
    boost::call_once(path_init, once);
    return default_path;
}

boost::filesystem::path webpage_path()
{
#ifdef _MSC_VER
    return "./mvs-htmls";
#else
    return default_data_path() / "mvs-htmls";
#endif
}

}//namespace libbitcoin

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009, Piotr Korzuszek
 * 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 <organization> 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 HOLDER 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 "Properties.h"

#include "common.h"

std::map<CL_String, CL_String> Properties::m_keyValueMap;

const char* FILENAME = "gear.cfg";

Properties::Properties()
{

}

Properties::~Properties()
{

}

void Properties::load()
{
	try {
		CL_File file(FILENAME, CL_File::open_existing, CL_File::access_read);

		CL_DataBuffer buffer(file.get_size());
		file.read(buffer.get_data(), buffer.get_size());

		file.close();

		const std::vector<CL_TempString> lines =
				CL_StringHelp::split_text(buffer.get_data(), END_OF_LINE, true);

		const int linesCount = static_cast<signed>(lines.size());

		std::vector<CL_TempString> parts;

		for (int i = 0; i < linesCount; ++i) {
			parts = CL_StringHelp::split_text(lines[i], "=", false);

			if (parts.size() == 2) {
				const CL_TempString left = CL_StringHelp::trim(parts[0]);
				const CL_TempString right = CL_StringHelp::trim(parts[1]);

				Properties::setProperty(left, right);

				cl_log_event(LOG_DEBUG, "Option '%1' set to '%2'", left, right);
			} else {
				cl_log_event(LOG_DEBUG, "Cannot parse line: %1", lines[i]);
			}
		}

	} catch (CL_Exception &e) {
		cl_log_event(LOG_DEBUG, "File %1 cannot be read: %2", FILENAME, e.message);
	}

}

void Properties::save()
{
	try {
		CL_File file(FILENAME, CL_File::create_always, CL_File::access_write);

		std::pair<CL_String, CL_String> pair;
		CL_String line;

		foreach(pair, m_keyValueMap) {
			line = cl_format("%1 = %2%3", pair.first, pair.second, END_OF_LINE);
			file.write(line.c_str(), line.length());

			cl_log_event(LOG_DEBUG, "Option '%1' saved with value '%2'", pair.first, pair.second);
		}

		file.close();

	} catch (CL_Exception &e) {
		cl_log_event(LOG_DEBUG, "File %1 cannot be written: %2", FILENAME, e.message);
	}
}

void Properties::setProperty(const CL_String &p_key, bool p_value)
{
	setProperty(p_key, CL_StringHelp::bool_to_local8(p_value));
}

void Properties::setProperty(const CL_String &p_key, int p_value)
{
	setProperty(p_key, CL_StringHelp::int_to_local8(p_value));
}

void Properties::setProperty(const CL_String &p_key, const CL_String &p_value)
{
	m_keyValueMap[p_key] = p_value;
}

bool Properties::getPropertyAsBool(const CL_String &p_key, bool p_defaultValue)
{
	return CL_StringHelp::local8_to_bool(getPropertyAsString(p_key, CL_StringHelp::bool_to_local8(p_defaultValue)));
}

int Properties::getPropertyAsInt(const CL_String &p_key, int p_defaultValue)
{
	return CL_StringHelp::local8_to_int(getPropertyAsString(p_key, CL_StringHelp::int_to_local8(p_defaultValue)));
}

CL_String Properties::getPropertyAsString(const CL_String &p_key, const CL_String &defaultValue)
{
	if (m_keyValueMap.find(p_key) != m_keyValueMap.end()) {
		return m_keyValueMap[p_key];
	} else {
		return defaultValue;
	}
}
<commit_msg>Fix to Win32 empty properties loading bug<commit_after>/*
 * Copyright (c) 2009-2010, Piotr Korzuszek
 * 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 <organization> 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 HOLDER 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 "Properties.h"

#include "common.h"

std::map<CL_String, CL_String> Properties::m_keyValueMap;

const char* FILENAME = "gear.cfg";

Properties::Properties()
{

}

Properties::~Properties()
{

}

void Properties::load()
{
	try {
		CL_File file(FILENAME, CL_File::open_existing, CL_File::access_read);

		CL_DataBuffer buffer(file.get_size());
		file.read(buffer.get_data(), buffer.get_size());

		file.close();

		if (buffer.get_size() != 0) {
			const std::vector<CL_TempString> lines =
					CL_StringHelp::split_text(buffer.get_data(), END_OF_LINE, true);

			const int linesCount = static_cast<signed>(lines.size());

			std::vector<CL_TempString> parts;

			for (int i = 0; i < linesCount; ++i) {
				parts = CL_StringHelp::split_text(lines[i], "=", false);

				if (parts.size() == 2) {
					const CL_TempString left = CL_StringHelp::trim(parts[0]);
					const CL_TempString right = CL_StringHelp::trim(parts[1]);

					Properties::setProperty(left, right);

					cl_log_event(LOG_DEBUG, "Option '%1' set to '%2'", left, right);
				} else {
					cl_log_event(LOG_DEBUG, "Cannot parse line: %1", lines[i]);
				}
			}
		}

	} catch (CL_Exception &e) {
		cl_log_event(LOG_DEBUG, "File %1 cannot be read: %2", FILENAME, e.message);
	}

}

void Properties::save()
{
	try {
		CL_File file(FILENAME, CL_File::create_always, CL_File::access_write);

		std::pair<CL_String, CL_String> pair;
		CL_String line;

		foreach(pair, m_keyValueMap) {
			line = cl_format("%1 = %2%3", pair.first, pair.second, END_OF_LINE);
			file.write(line.c_str(), line.length());

			cl_log_event(LOG_DEBUG, "Option '%1' saved with value '%2'", pair.first, pair.second);
		}

		file.close();

	} catch (CL_Exception &e) {
		cl_log_event(LOG_DEBUG, "File %1 cannot be written: %2", FILENAME, e.message);
	}
}

void Properties::setProperty(const CL_String &p_key, bool p_value)
{
	setProperty(p_key, CL_StringHelp::bool_to_local8(p_value));
}

void Properties::setProperty(const CL_String &p_key, int p_value)
{
	setProperty(p_key, CL_StringHelp::int_to_local8(p_value));
}

void Properties::setProperty(const CL_String &p_key, const CL_String &p_value)
{
	m_keyValueMap[p_key] = p_value;
}

bool Properties::getPropertyAsBool(const CL_String &p_key, bool p_defaultValue)
{
	return CL_StringHelp::local8_to_bool(getPropertyAsString(p_key, CL_StringHelp::bool_to_local8(p_defaultValue)));
}

int Properties::getPropertyAsInt(const CL_String &p_key, int p_defaultValue)
{
	return CL_StringHelp::local8_to_int(getPropertyAsString(p_key, CL_StringHelp::int_to_local8(p_defaultValue)));
}

CL_String Properties::getPropertyAsString(const CL_String &p_key, const CL_String &defaultValue)
{
	if (m_keyValueMap.find(p_key) != m_keyValueMap.end()) {
		return m_keyValueMap[p_key];
	} else {
		return defaultValue;
	}
}
<|endoftext|>