<commit_before>/** \file
 * Implements generally useful functions.
 */

#include <type_traits> /* std::underlying_type */
#include <string>

#include <cstdio>      /* snprintf() */

#ifndef _POWERDXX_UTILITY_HPP_
#define _POWERDXX_UTILITY_HPP_

/**
 * A collection of generally useful functions.
 */
namespace utility {

/**
 * Like sizeof(), but it returns the number of elements an array consists
 * of instead of the number of bytes.
 *
 * @tparam T,Count
 *	The type and number of array elements
 * @return
 *	The number of array entries
 */
template <typename T, size_t Count>
constexpr size_t countof(T (&)[Count]) { return Count; }

/**
 * Contains literals.
 */
namespace literals {

/**
 * A string literal operator equivalent to the `operator "" s` literal
 * provided by C++14 in \<string\>.
 *
 * @param op
 *	The raw string to turn into an std::string object
 * @param size
 *	The size of the raw string
 * @return
 *	An std::string instance
 */
inline std::string operator "" _s(char const * const op, size_t const size) {
	return {op, size};
}

} /* namespace literals */

/**
 * A wrapper around snprintf() that automatically pulls in the
 * destination buffer size.
 *
 * @tparam Size
 *	The destination buffer size
 * @tparam Args
 *	The types of the arguments
 * @param dst
 *	A reference to the destination buffer
 * @param format
 *	A printf style formatting string
 * @param args
 *	The printf arguments
 * @return
 *	The number of characters in the resulting string, regardless of the
 *	available space
 */
template <size_t Size, typename... Args>
inline int sprintf(char (& dst)[Size], const char * const format,
                   Args const... args) {
	return snprintf(dst, Size, format, args...);
}

/**
 * Casts an enum to its underlying value.
 *
 * @tparam ET,VT
 *	The enum and value type
 * @param op
 *	The operand to convert
 * @return
 *	The integer representation of the operand
 */
template <class ET, typename VT = typename std::underlying_type<ET>::type>
constexpr VT to_value(ET const op) {
	return static_cast<VT>(op);
}

/**
 * A formatting wrapper around string literals.
 *
 * Overloads operator (), which treats the string as a printf formatting
 * string, the arguments represent the data to format.
 *
 * In combination with the literal _fmt, it can be used like this:
 *
 * ~~~ c++
 * std::cout << "%-15.15s %#018p\n"_fmt("Address:", this);
 * ~~~
 */
class Formatter {
	private:
	/**
	 * Pointer to the string literal.
	 */
	char const * const fmt;

	public:
	/**
	 * Construct from string literal.
	 */
	constexpr Formatter(char const * const fmt) : fmt{fmt} {}

	/**
	 * Returns a formatted string.
	 *
	 * @tparam ArgTs
	 *	Variadic argument types
	 * @param args
	 *	Variadic arguments
	 * @return
	 *	An std::string formatted according to fmt
	 */
	template <typename... ArgTs>
	std::string operator ()(ArgTs const &... args) const {
		char buf[65536];
		auto count = sprintf(buf, this->fmt, args...);
		if (count >= countof(buf)) {
			return {buf, countof(buf) - 1};
		} else if (count < 0) {
			return {};
		}
		return {buf, static_cast<size_t>(count)};
	}
};

namespace literals {
/**
 * Literal to convert a string literal to a Formatter instance.
 *
 * @param fmt
 *	A printf style format string
 * @return
 *	A Formatter instance
 */
constexpr Formatter operator "" _fmt(char const * const fmt, size_t const) {
	return {fmt};
}
} /* namespace literals */

} /* namespace utility */

#endif /* _POWERDXX_UTILITY_HPP_ */
<commit_msg>Make Formatter buffer size a template argument<commit_after>/** \file
 * Implements generally useful functions.
 */

#include <type_traits> /* std::underlying_type */
#include <string>

#include <cstdio>      /* snprintf() */

#ifndef _POWERDXX_UTILITY_HPP_
#define _POWERDXX_UTILITY_HPP_

/**
 * A collection of generally useful functions.
 */
namespace utility {

/**
 * Like sizeof(), but it returns the number of elements an array consists
 * of instead of the number of bytes.
 *
 * @tparam T,Count
 *	The type and number of array elements
 * @return
 *	The number of array entries
 */
template <typename T, size_t Count>
constexpr size_t countof(T (&)[Count]) { return Count; }

/**
 * Contains literals.
 */
namespace literals {

/**
 * A string literal operator equivalent to the `operator "" s` literal
 * provided by C++14 in \<string\>.
 *
 * @param op
 *	The raw string to turn into an std::string object
 * @param size
 *	The size of the raw string
 * @return
 *	An std::string instance
 */
inline std::string operator "" _s(char const * const op, size_t const size) {
	return {op, size};
}

} /* namespace literals */

/**
 * A wrapper around snprintf() that automatically pulls in the
 * destination buffer size.
 *
 * @tparam Size
 *	The destination buffer size
 * @tparam Args
 *	The types of the arguments
 * @param dst
 *	A reference to the destination buffer
 * @param format
 *	A printf style formatting string
 * @param args
 *	The printf arguments
 * @return
 *	The number of characters in the resulting string, regardless of the
 *	available space
 */
template <size_t Size, typename... Args>
inline int sprintf(char (& dst)[Size], const char * const format,
                   Args const... args) {
	return snprintf(dst, Size, format, args...);
}

/**
 * Casts an enum to its underlying value.
 *
 * @tparam ET,VT
 *	The enum and value type
 * @param op
 *	The operand to convert
 * @return
 *	The integer representation of the operand
 */
template <class ET, typename VT = typename std::underlying_type<ET>::type>
constexpr VT to_value(ET const op) {
	return static_cast<VT>(op);
}

/**
 * A formatting wrapper around string literals.
 *
 * Overloads operator (), which treats the string as a printf formatting
 * string, the arguments represent the data to format.
 *
 * In combination with the literal _fmt, it can be used like this:
 *
 * ~~~ c++
 * std::cout << "%-15.15s %#018p\n"_fmt("Address:", this);
 * ~~~
 *
 * @tparam BufSize
 *	The buffer size for formatting, resulting strings cannot
 *	grow beyond `BufSize - 1`
 */
template <size_t BufSize>
class Formatter {
	private:
	/**
	 * Pointer to the string literal.
	 */
	char const * const fmt;

	public:
	/**
	 * Construct from string literal.
	 */
	constexpr Formatter(char const * const fmt) : fmt{fmt} {}

	/**
	 * Returns a formatted string.
	 *
	 * @tparam ArgTs
	 *	Variadic argument types
	 * @param args
	 *	Variadic arguments
	 * @return
	 *	An std::string formatted according to fmt
	 */
	template <typename... ArgTs>
	std::string operator ()(ArgTs const &... args) const {
		char buf[BufSize];
		auto count = sprintf(buf, this->fmt, args...);
		if (count >= BufSize) {
			/* does not fit into buffer */
			return {buf, BufSize - 1};
		} else if (count < 0) {
			/* encoding error */
			return {};
		}
		return {buf, static_cast<size_t>(count)};
	}
};

namespace literals {
/**
 * Literal to convert a string literal to a Formatter instance.
 *
 * @param fmt
 *	A printf style format string
 * @return
 *	A Formatter instance
 */
constexpr Formatter<16384> operator "" _fmt(char const * const fmt, size_t const) {
	return {fmt};
}
} /* namespace literals */

} /* namespace utility */

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


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

#include "chrome/browser/extensions/api/socket/socket_api.h"

#include "base/bind.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/api_resource_controller.h"
#include "chrome/browser/extensions/api/socket/socket.h"
#include "chrome/browser/extensions/api/socket/tcp_socket.h"
#include "chrome/browser/extensions/api/socket/udp_socket.h"
#include "chrome/browser/extensions/extension_service.h"

namespace extensions {

const char kBytesWrittenKey[] = "bytesWritten";
const char kMessageKey[] = "message";
const char kSocketIdKey[] = "socketId";
const char kTCPOption[] = "tcp";
const char kUDPOption[] = "udp";

const char kSocketNotFoundError[] = "Socket not found";

SocketCreateFunction::SocketCreateFunction()
    : src_id_(-1) {
}

bool SocketCreateFunction::Prepare() {
  std::string socket_type_string;
  size_t argument_position = 0;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(argument_position++,
                                               &socket_type_string));
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(argument_position++,
                                               &address_));
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(argument_position++,
                                                &port_));
  src_id_ = ExtractSrcId(argument_position);

  if (socket_type_string == kTCPOption)
    socket_type_ = kSocketTypeTCP;
  else if (socket_type_string == kUDPOption)
    socket_type_ = kSocketTypeUDP;
  else
    return false;
  return true;
}

void SocketCreateFunction::Work() {
  APIResourceEventNotifier* event_notifier = CreateEventNotifier(src_id_);
  Socket* socket = NULL;
  if (socket_type_ == kSocketTypeTCP) {
    socket = new TCPSocket(address_, port_, event_notifier);
  } else {
    socket = new UDPSocket(address_, port_, event_notifier);
  }
  DCHECK(socket);
  DCHECK(socket->IsValid());

  DictionaryValue* result = new DictionaryValue();

  result->SetInteger(kSocketIdKey, controller()->AddAPIResource(socket));
  result_.reset(result);
}

bool SocketCreateFunction::Respond() {
  return true;
}

bool SocketDestroyFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketDestroyFunction::Work() {
  controller()->RemoveAPIResource(socket_id_);
}

bool SocketDestroyFunction::Respond() {
  return true;
}

bool SocketConnectFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketConnectFunction::Work() {
  int result = -1;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    result = socket->Connect();
  else
    error_ = kSocketNotFoundError;
  result_.reset(Value::CreateIntegerValue(result));
}

bool SocketConnectFunction::Respond() {
  return true;
}

bool SocketDisconnectFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketDisconnectFunction::Work() {
  int result = -1;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    result = socket->Connect();
  else
    error_ = kSocketNotFoundError;
  result_.reset(Value::CreateNullValue());
}

bool SocketDisconnectFunction::Respond() {
  return true;
}

bool SocketReadFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketReadFunction::Work() {
  std::string message;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    message = socket->Read();

  DictionaryValue* result = new DictionaryValue();
  result->SetString(kMessageKey, message);
  result_.reset(result);
}

bool SocketReadFunction::Respond() {
  return true;
}

bool SocketWriteFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &message_));
  return true;
}

void SocketWriteFunction::Work() {
  int bytes_written = -1;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    bytes_written = socket->Write(message_);
  else
    error_ = kSocketNotFoundError;

  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(kBytesWrittenKey, bytes_written);
  result_.reset(result);
}

bool SocketWriteFunction::Respond() {
  return true;
}

}  // namespace extensions
<commit_msg>Fix a copy/paste error that got by most compilers.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/socket/socket_api.h"

#include "base/bind.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/api_resource_controller.h"
#include "chrome/browser/extensions/api/socket/socket.h"
#include "chrome/browser/extensions/api/socket/tcp_socket.h"
#include "chrome/browser/extensions/api/socket/udp_socket.h"
#include "chrome/browser/extensions/extension_service.h"

namespace extensions {

const char kBytesWrittenKey[] = "bytesWritten";
const char kMessageKey[] = "message";
const char kSocketIdKey[] = "socketId";
const char kTCPOption[] = "tcp";
const char kUDPOption[] = "udp";

const char kSocketNotFoundError[] = "Socket not found";

SocketCreateFunction::SocketCreateFunction()
    : src_id_(-1) {
}

bool SocketCreateFunction::Prepare() {
  std::string socket_type_string;
  size_t argument_position = 0;
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(argument_position++,
                                               &socket_type_string));
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(argument_position++,
                                               &address_));
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(argument_position++,
                                                &port_));
  src_id_ = ExtractSrcId(argument_position);

  if (socket_type_string == kTCPOption)
    socket_type_ = kSocketTypeTCP;
  else if (socket_type_string == kUDPOption)
    socket_type_ = kSocketTypeUDP;
  else
    return false;
  return true;
}

void SocketCreateFunction::Work() {
  APIResourceEventNotifier* event_notifier = CreateEventNotifier(src_id_);
  Socket* socket = NULL;
  if (socket_type_ == kSocketTypeTCP) {
    socket = new TCPSocket(address_, port_, event_notifier);
  } else {
    socket = new UDPSocket(address_, port_, event_notifier);
  }
  DCHECK(socket);
  DCHECK(socket->IsValid());

  DictionaryValue* result = new DictionaryValue();

  result->SetInteger(kSocketIdKey, controller()->AddAPIResource(socket));
  result_.reset(result);
}

bool SocketCreateFunction::Respond() {
  return true;
}

bool SocketDestroyFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketDestroyFunction::Work() {
  controller()->RemoveAPIResource(socket_id_);
}

bool SocketDestroyFunction::Respond() {
  return true;
}

bool SocketConnectFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketConnectFunction::Work() {
  int result = -1;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    result = socket->Connect();
  else
    error_ = kSocketNotFoundError;
  result_.reset(Value::CreateIntegerValue(result));
}

bool SocketConnectFunction::Respond() {
  return true;
}

bool SocketDisconnectFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketDisconnectFunction::Work() {
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    socket->Disconnect();
  else
    error_ = kSocketNotFoundError;
  result_.reset(Value::CreateNullValue());
}

bool SocketDisconnectFunction::Respond() {
  return true;
}

bool SocketReadFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  return true;
}

void SocketReadFunction::Work() {
  std::string message;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    message = socket->Read();

  DictionaryValue* result = new DictionaryValue();
  result->SetString(kMessageKey, message);
  result_.reset(result);
}

bool SocketReadFunction::Respond() {
  return true;
}

bool SocketWriteFunction::Prepare() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &socket_id_));
  EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &message_));
  return true;
}

void SocketWriteFunction::Work() {
  int bytes_written = -1;
  Socket* socket = controller()->GetSocket(socket_id_);
  if (socket)
    bytes_written = socket->Write(message_);
  else
    error_ = kSocketNotFoundError;

  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(kBytesWrittenKey, bytes_written);
  result_.reset(result);
}

bool SocketWriteFunction::Respond() {
  return true;
}

}  // namespace extensions
<|endoftext|>


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

#include "base/command_line.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/shell_window_registry.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/extensions/shell_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/menu_model.h"

using content::WebContents;
using extensions::Extension;

namespace utils = extension_function_test_utils;

namespace {
// Non-abstract RenderViewContextMenu class.
class PlatformAppContextMenu : public RenderViewContextMenu {
 public:
  PlatformAppContextMenu(WebContents* web_contents,
                         const content::ContextMenuParams& params)
      : RenderViewContextMenu(web_contents, params) {}

 protected:
  // These two functions implement pure virtual methods of
  // RenderViewContextMenu.
  virtual bool GetAcceleratorForCommandId(int command_id,
                                          ui::Accelerator* accelerator) {
    return false;
  }
  virtual void PlatformInit() {}
  virtual void PlatformCancel() {}
};

}  // namespace

class PlatformAppBrowserTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

 protected:
  const Extension* LoadAndLaunchPlatformApp(const char* name) {
    ui_test_utils::WindowedNotificationObserver app_loaded_observer(
        content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
        content::NotificationService::AllSources());

    const Extension* extension = LoadExtension(
        test_data_dir_.AppendASCII("platform_apps").AppendASCII(name));
    EXPECT_TRUE(extension);

    application_launch::OpenApplication(
        browser()->profile(),
        extension,
        extension_misc::LAUNCH_NONE,
        GURL(),
        NEW_WINDOW,
        NULL);

    app_loaded_observer.Wait();

    return extension;
  }

  // Gets the WebContents associated with the first shell window that is found
  // (most tests only deal with one platform app window, so this is good
  // enough).
  WebContents* GetFirstShellWindowWebContents() {
    ShellWindowRegistry* app_registry =
        ShellWindowRegistry::Get(browser()->profile());
    ShellWindowRegistry::const_iterator iter;
    ShellWindowRegistry::ShellWindowSet shell_windows =
        app_registry->shell_windows();
    for (iter = shell_windows.begin(); iter != shell_windows.end(); ++iter) {
      return (*iter)->web_contents();
    }

    return NULL;
  }

  // Runs chrome.windows.getAll for the given extension and returns the number
  // of windows that the function returns.
  size_t RunGetWindowsFunctionForExtension(const Extension* extension) {
    GetAllWindowsFunction* function = new GetAllWindowsFunction();
    function->set_extension(extension);
    scoped_ptr<base::ListValue> result(utils::ToList(
        utils::RunFunctionAndReturnResult(function, "[]", browser())));
    return result->GetSize();
  }

  // Runs chrome.windows.get(|window_id|) for the the given extension and
  // returns whether or not a window was found.
  bool RunGetWindowFunctionForExtension(
      int window_id, const Extension* extension) {
    GetWindowFunction* function = new GetWindowFunction();
    function->set_extension(extension);
    utils::RunFunction(
            function,
            base::StringPrintf("[%u]", window_id),
            browser(),
            utils::NONE);
    return function->GetResultValue() != NULL;
  }

  size_t GetShellWindowCount() {
    return ShellWindowRegistry::Get(browser()->profile())->
        shell_windows().size();
  }

  // The command line already has an argument on it - about:blank, which
  // is set by InProcessBrowserTest::PrepareTestCommandLine. For platform app
  // launch tests we need to clear this.
  void ClearCommandLineArgs() {
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    CommandLine::StringVector args = command_line->GetArgs();
    CommandLine::StringVector argv = command_line->argv();
    for (size_t i = 0; i < args.size(); i++)
      argv.pop_back();
    command_line->InitFromArgv(argv);
  }

  void SetCommandLineArg(const std::string& test_file) {
    ClearCommandLineArgs();
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    FilePath test_doc(test_data_dir_.AppendASCII(test_file));
    test_doc = test_doc.NormalizePathSeparators();
    command_line->AppendArgPath(test_doc);
  }
};

// Tests that platform apps received the "launch" event when launched.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OnLaunchedEvent) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, EmptyContextMenu) {
  ExtensionTestMessageListener launched_listener("Launched", false);
  LoadAndLaunchPlatformApp("minimal");

  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());

  // The empty app doesn't add any context menu items, so its menu should
  // only include the developer tools.
  WebContents* web_contents = GetFirstShellWindowWebContents();
  ASSERT_TRUE(web_contents);
  WebKit::WebContextMenuData data;
  content::ContextMenuParams params(data);
  PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,
      params);
  menu->Init();
  // TODO(benwells): Remove the constant below. Instead of checking the
  // number of menu items check certain item's absense and presence.
  // 3 including separator
  ASSERT_EQ(3, menu->menu_model().GetItemCount());
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenu) {
  ExtensionTestMessageListener launched_listener("Launched", false);
  LoadAndLaunchPlatformApp("context_menu");

  // Wait for the extension to tell us it's initialized its context menus and
  // launched a window.
  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());

  // The context_menu app has one context menu item. This, along with a
  // separator and the developer tools, is all that should be in the menu.
  WebContents* web_contents = GetFirstShellWindowWebContents();
  ASSERT_TRUE(web_contents);
  WebKit::WebContextMenuData data;
  content::ContextMenuParams params(data);
  PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,
      params);
  menu->Init();
  // TODO(benwells): Remove the constant below. Instead of checking the
  // number of menu items check certain item's absense and presence.
  ASSERT_EQ(4, menu->menu_model().GetItemCount());
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowNavigation) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/navigation")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Iframes) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/iframes")) << message_;
}

// Tests that localStorage and WebSQL are disabled for platform apps.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowStorage) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Restrictions) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/restrictions")) << message_;
}

// Tests that platform apps can use the chrome.windows.* API.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApi) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/windows_api")) << message_;
}

// Tests that platform apps have isolated storage by default.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Isolation) {
  ASSERT_TRUE(StartTestServer());

  // Load a (non-app) page under the "localhost" origin that sets a cookie.
  GURL set_cookie_url = test_server()->GetURL(
      "files/extensions/platform_apps/isolation/set_cookie.html");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), set_cookie_url,
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Make sure the cookie is set.
  int cookie_size;
  std::string cookie_value;
  automation_util::GetCookies(
      set_cookie_url,
      browser()->GetWebContentsAt(0),
      &cookie_size,
      &cookie_value);
  ASSERT_EQ("testCookie=1", cookie_value);

  // Let the platform app request the same URL, and make sure that it doesn't
  // see the cookie.
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/isolation")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ExtensionWindowingApis) {
  // Initially there should be just the one browser window visible to the
  // extensions API.
  const Extension* extension = LoadExtension(
      test_data_dir_.AppendASCII("common/background_page"));
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));

  // And no shell windows.
  ASSERT_EQ(0U, GetShellWindowCount());

  // Launch a platform app that shows a window.
  ExtensionTestMessageListener launched_listener("Launched", false);
  const Extension* platform_app = LoadAndLaunchPlatformApp("minimal");
  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
  ASSERT_EQ(1U, GetShellWindowCount());
  ShellWindowRegistry::ShellWindowSet shell_windows =
      ShellWindowRegistry::Get(browser()->profile())->shell_windows();
  int shell_window_id = (*shell_windows.begin())->session_id().id();

  // But it's not visible to the extensions API, it still thinks there's just
  // one browser window.
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));
  // It can't look it up by ID either
  ASSERT_FALSE(RunGetWindowFunctionForExtension(shell_window_id, extension));

  // The app can also only see one window (its own).
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app));
  ASSERT_TRUE(RunGetWindowFunctionForExtension(shell_window_id, platform_app));

  // Launch another platform app that also shows a window.
  ExtensionTestMessageListener launched_listener2("Launched", false);
  const Extension* platform_app2 = LoadAndLaunchPlatformApp("context_menu");
  ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());

  // There are two total shell windows, but each app can only see its own.
  ASSERT_EQ(2U, GetShellWindowCount());
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app));
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app2));
}

// TODO(benwells): fix these tests for ChromeOS.
#if !defined(OS_CHROMEOS)
// Tests that command line parameters get passed through to platform apps
// via launchData correctly when launching with a file.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFile) {
  SetCommandLineArg( "platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file"))
      << message_;
}

// Tests that no launch data is sent through if the platform app provides
// an intent with the wrong action.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongIntent) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_intent"))
      << message_;
}

// Tests that no launch data is sent through if the file is of the wrong MIME
// type.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongType) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_type"))
      << message_;
}

// Tests that no launch data is sent through if the platform app does not
// provide an intent.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNoIntent) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_no_intent"))
      << message_;
}

// Tests that no launch data is sent through if the file MIME type cannot
// be read.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoType) {
  SetCommandLineArg("platform_apps/launch_files/test.unknownextension");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if the file does not exist.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoFile) {
  SetCommandLineArg("platform_apps/launch_files/doesnotexist.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if the argument is a directory.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithDirectory) {
  SetCommandLineArg("platform_apps/launch_files");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if there are no arguments passed
// on the command line
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNothing) {
  ClearCommandLineArgs();
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_nothing"))
      << message_;
}
#endif  // defined(OS_CHROMEOS)
<commit_msg>Comment out PlatformAppBrowserTest.LaunchWithFile for Linux.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_tabs_module.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/shell_window_registry.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/extensions/shell_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/menu_model.h"

using content::WebContents;
using extensions::Extension;

namespace utils = extension_function_test_utils;

namespace {
// Non-abstract RenderViewContextMenu class.
class PlatformAppContextMenu : public RenderViewContextMenu {
 public:
  PlatformAppContextMenu(WebContents* web_contents,
                         const content::ContextMenuParams& params)
      : RenderViewContextMenu(web_contents, params) {}

 protected:
  // These two functions implement pure virtual methods of
  // RenderViewContextMenu.
  virtual bool GetAcceleratorForCommandId(int command_id,
                                          ui::Accelerator* accelerator) {
    return false;
  }
  virtual void PlatformInit() {}
  virtual void PlatformCancel() {}
};

}  // namespace

class PlatformAppBrowserTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

 protected:
  const Extension* LoadAndLaunchPlatformApp(const char* name) {
    ui_test_utils::WindowedNotificationObserver app_loaded_observer(
        content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
        content::NotificationService::AllSources());

    const Extension* extension = LoadExtension(
        test_data_dir_.AppendASCII("platform_apps").AppendASCII(name));
    EXPECT_TRUE(extension);

    application_launch::OpenApplication(
        browser()->profile(),
        extension,
        extension_misc::LAUNCH_NONE,
        GURL(),
        NEW_WINDOW,
        NULL);

    app_loaded_observer.Wait();

    return extension;
  }

  // Gets the WebContents associated with the first shell window that is found
  // (most tests only deal with one platform app window, so this is good
  // enough).
  WebContents* GetFirstShellWindowWebContents() {
    ShellWindowRegistry* app_registry =
        ShellWindowRegistry::Get(browser()->profile());
    ShellWindowRegistry::const_iterator iter;
    ShellWindowRegistry::ShellWindowSet shell_windows =
        app_registry->shell_windows();
    for (iter = shell_windows.begin(); iter != shell_windows.end(); ++iter) {
      return (*iter)->web_contents();
    }

    return NULL;
  }

  // Runs chrome.windows.getAll for the given extension and returns the number
  // of windows that the function returns.
  size_t RunGetWindowsFunctionForExtension(const Extension* extension) {
    GetAllWindowsFunction* function = new GetAllWindowsFunction();
    function->set_extension(extension);
    scoped_ptr<base::ListValue> result(utils::ToList(
        utils::RunFunctionAndReturnResult(function, "[]", browser())));
    return result->GetSize();
  }

  // Runs chrome.windows.get(|window_id|) for the the given extension and
  // returns whether or not a window was found.
  bool RunGetWindowFunctionForExtension(
      int window_id, const Extension* extension) {
    GetWindowFunction* function = new GetWindowFunction();
    function->set_extension(extension);
    utils::RunFunction(
            function,
            base::StringPrintf("[%u]", window_id),
            browser(),
            utils::NONE);
    return function->GetResultValue() != NULL;
  }

  size_t GetShellWindowCount() {
    return ShellWindowRegistry::Get(browser()->profile())->
        shell_windows().size();
  }

  // The command line already has an argument on it - about:blank, which
  // is set by InProcessBrowserTest::PrepareTestCommandLine. For platform app
  // launch tests we need to clear this.
  void ClearCommandLineArgs() {
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    CommandLine::StringVector args = command_line->GetArgs();
    CommandLine::StringVector argv = command_line->argv();
    for (size_t i = 0; i < args.size(); i++)
      argv.pop_back();
    command_line->InitFromArgv(argv);
  }

  void SetCommandLineArg(const std::string& test_file) {
    ClearCommandLineArgs();
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    FilePath test_doc(test_data_dir_.AppendASCII(test_file));
    test_doc = test_doc.NormalizePathSeparators();
    command_line->AppendArgPath(test_doc);
  }
};

// Tests that platform apps received the "launch" event when launched.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OnLaunchedEvent) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, EmptyContextMenu) {
  ExtensionTestMessageListener launched_listener("Launched", false);
  LoadAndLaunchPlatformApp("minimal");

  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());

  // The empty app doesn't add any context menu items, so its menu should
  // only include the developer tools.
  WebContents* web_contents = GetFirstShellWindowWebContents();
  ASSERT_TRUE(web_contents);
  WebKit::WebContextMenuData data;
  content::ContextMenuParams params(data);
  PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,
      params);
  menu->Init();
  // TODO(benwells): Remove the constant below. Instead of checking the
  // number of menu items check certain item's absense and presence.
  // 3 including separator
  ASSERT_EQ(3, menu->menu_model().GetItemCount());
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenu) {
  ExtensionTestMessageListener launched_listener("Launched", false);
  LoadAndLaunchPlatformApp("context_menu");

  // Wait for the extension to tell us it's initialized its context menus and
  // launched a window.
  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());

  // The context_menu app has one context menu item. This, along with a
  // separator and the developer tools, is all that should be in the menu.
  WebContents* web_contents = GetFirstShellWindowWebContents();
  ASSERT_TRUE(web_contents);
  WebKit::WebContextMenuData data;
  content::ContextMenuParams params(data);
  PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,
      params);
  menu->Init();
  // TODO(benwells): Remove the constant below. Instead of checking the
  // number of menu items check certain item's absense and presence.
  ASSERT_EQ(4, menu->menu_model().GetItemCount());
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowNavigation) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/navigation")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Iframes) {
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/iframes")) << message_;
}

// Tests that localStorage and WebSQL are disabled for platform apps.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowStorage) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Restrictions) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/restrictions")) << message_;
}

// Tests that platform apps can use the chrome.windows.* API.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApi) {
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/windows_api")) << message_;
}

// Tests that platform apps have isolated storage by default.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Isolation) {
  ASSERT_TRUE(StartTestServer());

  // Load a (non-app) page under the "localhost" origin that sets a cookie.
  GURL set_cookie_url = test_server()->GetURL(
      "files/extensions/platform_apps/isolation/set_cookie.html");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), set_cookie_url,
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Make sure the cookie is set.
  int cookie_size;
  std::string cookie_value;
  automation_util::GetCookies(
      set_cookie_url,
      browser()->GetWebContentsAt(0),
      &cookie_size,
      &cookie_value);
  ASSERT_EQ("testCookie=1", cookie_value);

  // Let the platform app request the same URL, and make sure that it doesn't
  // see the cookie.
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/isolation")) << message_;
}

IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ExtensionWindowingApis) {
  // Initially there should be just the one browser window visible to the
  // extensions API.
  const Extension* extension = LoadExtension(
      test_data_dir_.AppendASCII("common/background_page"));
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));

  // And no shell windows.
  ASSERT_EQ(0U, GetShellWindowCount());

  // Launch a platform app that shows a window.
  ExtensionTestMessageListener launched_listener("Launched", false);
  const Extension* platform_app = LoadAndLaunchPlatformApp("minimal");
  ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
  ASSERT_EQ(1U, GetShellWindowCount());
  ShellWindowRegistry::ShellWindowSet shell_windows =
      ShellWindowRegistry::Get(browser()->profile())->shell_windows();
  int shell_window_id = (*shell_windows.begin())->session_id().id();

  // But it's not visible to the extensions API, it still thinks there's just
  // one browser window.
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));
  // It can't look it up by ID either
  ASSERT_FALSE(RunGetWindowFunctionForExtension(shell_window_id, extension));

  // The app can also only see one window (its own).
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app));
  ASSERT_TRUE(RunGetWindowFunctionForExtension(shell_window_id, platform_app));

  // Launch another platform app that also shows a window.
  ExtensionTestMessageListener launched_listener2("Launched", false);
  const Extension* platform_app2 = LoadAndLaunchPlatformApp("context_menu");
  ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());

  // There are two total shell windows, but each app can only see its own.
  ASSERT_EQ(2U, GetShellWindowCount());
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app));
  ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(platform_app2));
}

// TODO(benwells): fix these tests for ChromeOS.
#if !defined(OS_CHROMEOS)
// Tests that command line parameters get passed through to platform apps
// via launchData correctly when launching with a file.
// TODO(benwells): fix this test for Linux (http://crbug.com/129885).
#if !defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFile) {
  SetCommandLineArg( "platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file"))
      << message_;
}
#endif  // defined(OS_LINUX)

// Tests that no launch data is sent through if the platform app provides
// an intent with the wrong action.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongIntent) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_intent"))
      << message_;
}

// Tests that no launch data is sent through if the file is of the wrong MIME
// type.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongType) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_type"))
      << message_;
}

// Tests that no launch data is sent through if the platform app does not
// provide an intent.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNoIntent) {
  SetCommandLineArg("platform_apps/launch_files/test.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_no_intent"))
      << message_;
}

// Tests that no launch data is sent through if the file MIME type cannot
// be read.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoType) {
  SetCommandLineArg("platform_apps/launch_files/test.unknownextension");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if the file does not exist.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoFile) {
  SetCommandLineArg("platform_apps/launch_files/doesnotexist.txt");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if the argument is a directory.
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithDirectory) {
  SetCommandLineArg("platform_apps/launch_files");
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
      << message_;
}

// Tests that no launch data is sent through if there are no arguments passed
// on the command line
IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNothing) {
  ClearCommandLineArgs();
  ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_nothing"))
      << message_;
}
#endif  // defined(OS_CHROMEOS)
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsNoPermission) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
#endif
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsHasPermissionManifest) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
      << message_;
#endif
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsHasPermission) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  DesktopNotificationServiceFactory::GetForProfile(browser()->profile())
      ->GrantPermission(GURL(
          "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
      << message_;
#endif
}
<commit_msg>Disable ExtensionApiTest.NotificationsHasPermissionManifest<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsNoPermission) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
#endif
}

// Disabled after createHTMLNotification removal
// (http://trac.webkit.org/changeset/140983)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       DISABLED_NotificationsHasPermissionManifest) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
      << message_;
#endif
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsHasPermission) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
  // Notifications not supported on linux/views yet.
#else
  DesktopNotificationServiceFactory::GetForProfile(browser()->profile())
      ->GrantPermission(GURL(
          "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
  ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
      << message_;
#endif
}
<|endoftext|>


<commit_before>#include "sceneLayer.h"

#include <algorithm>

namespace Tangram {

SceneLayer::SceneLayer(std::string _name, Filter _filter, std::vector<DrawRule> _rules, std::vector<SceneLayer> _sublayers) :
    m_filter(_filter), m_name(_name), m_rules(_rules), m_sublayers(_sublayers) {

    // Rules must be sorted to merge correctly
    std::sort(m_rules.begin(), m_rules.end());

    // m_depth is one more than the maximum depth of any sublayer
    for (auto& sublayer : m_sublayers) {
        m_depth = sublayer.m_depth ? sublayer.m_depth : m_depth;
    }
    m_depth++;

    // Sublayers must be sorted by the depth of their deepest leaf in order to correctly traverse them in match()
    std::sort(m_sublayers.begin(), m_sublayers.end(), [&](const SceneLayer& a, const SceneLayer& b) {
        return a.m_depth < b.m_depth;
    });

}

void SceneLayer::match(const Feature& _feat, const Context& _ctx, std::vector<DrawRule>& _matches) const {

    if (!m_filter.eval(_feat, _ctx)) {
        return;
    }

    // Depth-first traversal produces correct parameter precedence when sublayers are sorted by increasing depth
    for (auto& layer : m_sublayers) {
        layer.match(_feat, _ctx, _matches);
    }

    std::vector<DrawRule> merged;

    // For all of m_rules that have the same style as an existing matched rule, merge the rules;
    // for others, take existing rule unchanged
    {
        auto pIt = m_rules.begin(), pEnd = m_rules.end();
        auto cIt = _matches.begin(), cEnd = _matches.end();
        while (pIt != pEnd && cIt != cEnd) {
            if (*pIt < *cIt) {
                merged.push_back(*pIt++);
            } else if (*cIt < *pIt) {
                merged.push_back(std::move(*cIt++));
            } else {
                merged.push_back(std::move((*pIt++).merge(*cIt++)));
            }
        }
        while (pIt != pEnd) { merged.push_back(*pIt++); }
        while (cIt != cEnd) { merged.push_back(std::move(*cIt++)); }
    }

    // Move merged results into output vector
    std::swap(merged, _matches);
}

}

<commit_msg>Fix uninitialized member in SceneLayer<commit_after>#include "sceneLayer.h"

#include <algorithm>

namespace Tangram {

SceneLayer::SceneLayer(std::string _name, Filter _filter, std::vector<DrawRule> _rules, std::vector<SceneLayer> _sublayers) :
    m_filter(_filter), m_name(_name), m_rules(_rules), m_sublayers(_sublayers), m_depth(0) {

    // Rules must be sorted to merge correctly
    std::sort(m_rules.begin(), m_rules.end());

    // m_depth is one more than the maximum depth of any sublayer
    for (auto& sublayer : m_sublayers) {
        m_depth = sublayer.m_depth ? sublayer.m_depth : m_depth;
    }
    m_depth++;

    // Sublayers must be sorted by the depth of their deepest leaf in order to correctly traverse them in match()
    std::sort(m_sublayers.begin(), m_sublayers.end(), [&](const SceneLayer& a, const SceneLayer& b) {
        return a.m_depth < b.m_depth;
    });

}

void SceneLayer::match(const Feature& _feat, const Context& _ctx, std::vector<DrawRule>& _matches) const {

    if (!m_filter.eval(_feat, _ctx)) {
        return;
    }

    // Depth-first traversal produces correct parameter precedence when sublayers are sorted by increasing depth
    for (auto& layer : m_sublayers) {
        layer.match(_feat, _ctx, _matches);
    }

    std::vector<DrawRule> merged;

    // For all of m_rules that have the same style as an existing matched rule, merge the rules;
    // for others, take existing rule unchanged
    {
        auto pIt = m_rules.begin(), pEnd = m_rules.end();
        auto cIt = _matches.begin(), cEnd = _matches.end();
        while (pIt != pEnd && cIt != cEnd) {
            if (*pIt < *cIt) {
                merged.push_back(*pIt++);
            } else if (*cIt < *pIt) {
                merged.push_back(std::move(*cIt++));
            } else {
                merged.push_back(std::move((*pIt++).merge(*cIt++)));
            }
        }
        while (pIt != pEnd) { merged.push_back(*pIt++); }
        while (cIt != cEnd) { merged.push_back(std::move(*cIt++)); }
    }

    // Move merged results into output vector
    std::swap(merged, _matches);
}

}

<|endoftext|>


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

#include "chrome/browser/importer/in_process_importer_bridge.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/importer/importer_host.h"
#include "content/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"

#if defined(OS_WIN)
#include "chrome/browser/password_manager/ie7_password.h"
#endif

InProcessImporterBridge::InProcessImporterBridge(ProfileWriter* writer,
                                                 ImporterHost* host)
    : writer_(writer),
      host_(host) {
}

void InProcessImporterBridge::AddBookmarks(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const string16& first_folder_name) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddBookmarks, bookmarks,
                        first_folder_name));
}

void InProcessImporterBridge::AddHomePage(const GURL &home_page) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddHomepage, home_page));
}

#if defined(OS_WIN)
void InProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo& password_info) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddIE7PasswordInfo,
      password_info));
}
#endif  // OS_WIN

void InProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddFavicons, favicons));
}

void InProcessImporterBridge::SetHistoryItems(
    const std::vector<history::URLRow> &rows,
    history::VisitSource visit_source) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddHistoryPage,
                        rows, visit_source));
}

void InProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    int default_keyword_index,
    bool unique_on_host_and_path) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(
          writer_, &ProfileWriter::AddKeywords, template_urls,
          default_keyword_index, unique_on_host_and_path));
}

void InProcessImporterBridge::SetPasswordForm(
    const webkit_glue::PasswordForm& form) {
  LOG(ERROR) << "InProcessImporterBridge::SetPasswordForm";
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddPasswordForm, form));
}

void InProcessImporterBridge::NotifyStarted() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportStarted));
}

void InProcessImporterBridge::NotifyItemStarted(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportItemStarted, item));
}

void InProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportItemEnded, item));
}

void InProcessImporterBridge::NotifyEnded() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportEnded));
}

string16 InProcessImporterBridge::GetLocalizedString(int message_id) {
  return l10n_util::GetStringUTF16(message_id);
}

InProcessImporterBridge::~InProcessImporterBridge() {}
<commit_msg>Remove stray log statement from long ago.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/importer/in_process_importer_bridge.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/importer/importer_host.h"
#include "content/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/glue/password_form.h"

#if defined(OS_WIN)
#include "chrome/browser/password_manager/ie7_password.h"
#endif

InProcessImporterBridge::InProcessImporterBridge(ProfileWriter* writer,
                                                 ImporterHost* host)
    : writer_(writer),
      host_(host) {
}

void InProcessImporterBridge::AddBookmarks(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const string16& first_folder_name) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddBookmarks, bookmarks,
                        first_folder_name));
}

void InProcessImporterBridge::AddHomePage(const GURL &home_page) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddHomepage, home_page));
}

#if defined(OS_WIN)
void InProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo& password_info) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddIE7PasswordInfo,
      password_info));
}
#endif  // OS_WIN

void InProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddFavicons, favicons));
}

void InProcessImporterBridge::SetHistoryItems(
    const std::vector<history::URLRow> &rows,
    history::VisitSource visit_source) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddHistoryPage,
                        rows, visit_source));
}

void InProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    int default_keyword_index,
    bool unique_on_host_and_path) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(
          writer_, &ProfileWriter::AddKeywords, template_urls,
          default_keyword_index, unique_on_host_and_path));
}

void InProcessImporterBridge::SetPasswordForm(
    const webkit_glue::PasswordForm& form) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(writer_, &ProfileWriter::AddPasswordForm, form));
}

void InProcessImporterBridge::NotifyStarted() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportStarted));
}

void InProcessImporterBridge::NotifyItemStarted(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportItemStarted, item));
}

void InProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportItemEnded, item));
}

void InProcessImporterBridge::NotifyEnded() {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(host_, &ImporterHost::NotifyImportEnded));
}

string16 InProcessImporterBridge::GetLocalizedString(int message_id) {
  return l10n_util::GetStringUTF16(message_id);
}

InProcessImporterBridge::~InProcessImporterBridge() {}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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/renderer/render_widget_fullscreen_pepper.h"

#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/fullscreen_container.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"

using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;

namespace {

// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
 public:
  PepperWidget(webkit::ppapi::PluginInstance* plugin,
               RenderWidgetFullscreenPepper* widget)
      : plugin_(plugin),
        widget_(widget),
        cursor_(WebCursorInfo::TypePointer) {
  }

  // WebWidget API
  virtual void close() {
    delete this;
  }

  virtual WebSize size() {
    return size_;
  }

  virtual void resize(const WebSize& size) {
    size_ = size;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    // TODO(piman): transparently scale the plugin instead of resizing it.
    plugin_->ViewChanged(plugin_rect, plugin_rect);
    widget_->GenerateFullRepaint();
  }

  virtual void layout() {
  }

  virtual void paint(WebCanvas* canvas, const WebRect& rect) {
    if (!plugin_)
      return;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    plugin_->Paint(canvas, plugin_rect, rect);
  }

  virtual void composite(bool finish) {
    NOTIMPLEMENTED();
  }

  virtual void themeChanged() {
    NOTIMPLEMENTED();
  }

  virtual bool handleInputEvent(const WebInputEvent& event) {
    if (!plugin_)
      return false;
    return plugin_->HandleInputEvent(event, &cursor_);
  }

  virtual void mouseCaptureLost() {
    NOTIMPLEMENTED();
  }

  virtual void setFocus(bool focus) {
    NOTIMPLEMENTED();
  }

  virtual bool setComposition(
      const WebString& text,
      const WebVector<WebCompositionUnderline>& underlines,
      int selectionStart,
      int selectionEnd) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition() {
    NOTIMPLEMENTED();
    return false;
  }

  virtual WebTextInputType textInputType() {
    NOTIMPLEMENTED();
    return WebKit::WebTextInputTypeNone;
  }

  virtual WebRect caretOrSelectionBounds() {
    NOTIMPLEMENTED();
    return WebRect();
  }

  virtual void setTextDirection(WebTextDirection) {
    NOTIMPLEMENTED();
  }

  virtual bool isAcceleratedCompositingActive() const {
    // TODO(piman): see if supporting accelerated compositing makes sense.
    return false;
  }

 private:
  webkit::ppapi::PluginInstance* plugin_;
  RenderWidgetFullscreenPepper* widget_;
  WebSize size_;
  WebCursorInfo cursor_;

  DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};

// A FullscreenContainer that forwards the API calls to the
// RenderWidgetFullscreenPepper.
class WidgetFullscreenContainer
    : public webkit::ppapi::FullscreenContainer {
 public:
  explicit WidgetFullscreenContainer(RenderWidgetFullscreenPepper* widget)
      : widget_(widget) {
  }
  virtual ~WidgetFullscreenContainer() { }

  virtual void Invalidate() {
    widget_->GenerateFullRepaint();
  }

  virtual void InvalidateRect(const WebKit::WebRect& rect) {
    widget_->didInvalidateRect(rect);
  }

  virtual void ScrollRect(int dx, int dy, const WebKit::WebRect& rect) {
    widget_->didScrollRect(dx, dy, rect);
  }

  virtual void Destroy() {
    widget_->SendClose();
  }

 private:
  RenderWidgetFullscreenPepper* widget_;

  DISALLOW_COPY_AND_ASSIGN(WidgetFullscreenContainer);
};

}  // anonymous namespace

// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
    int32 opener_id, RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin) {
  DCHECK_NE(MSG_ROUTING_NONE, opener_id);
  scoped_refptr<RenderWidgetFullscreenPepper> widget(
      new RenderWidgetFullscreenPepper(render_thread, plugin));
  widget->Init(opener_id);
  return widget.release();
}

RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
    RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin)
    : RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
      plugin_(plugin),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          container_(new WidgetFullscreenContainer(this))) {
}

RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
}

WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
  return new PepperWidget(plugin_, this);
}

void RenderWidgetFullscreenPepper::Close() {
  // If the fullscreen window is closed (e.g. user pressed escape), reset to
  // normal mode.
  if (plugin_)
    plugin_->SetFullscreen(false);
}

void RenderWidgetFullscreenPepper::DidInitiatePaint() {
  if (plugin_)
    plugin_->ViewInitiatedPaint();
}

void RenderWidgetFullscreenPepper::DidFlushPaint() {
  if (plugin_)
    plugin_->ViewFlushedPaint();
}

void RenderWidgetFullscreenPepper::SendClose() {
  // This function is called by the plugin instance as it's going away, so reset
  // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
  plugin_ = NULL;
  Send(new ViewHostMsg_Close(routing_id_));
}

void RenderWidgetFullscreenPepper::GenerateFullRepaint() {
  didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
}

webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
    const gfx::Rect& paint_bounds,
    TransportDIB** dib,
    gfx::Rect* location,
    gfx::Rect* clip) {
  if (plugin_ &&
      plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
                                                location, clip))
    return plugin_;
  return NULL;
}
<commit_msg>Add a dummy implementation of a new WebWidget::confirmComposition() method.<commit_after>// Copyright (c) 2010 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/renderer/render_widget_fullscreen_pepper.h"

#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/fullscreen_container.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"

using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;

namespace {

// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
 public:
  PepperWidget(webkit::ppapi::PluginInstance* plugin,
               RenderWidgetFullscreenPepper* widget)
      : plugin_(plugin),
        widget_(widget),
        cursor_(WebCursorInfo::TypePointer) {
  }

  // WebWidget API
  virtual void close() {
    delete this;
  }

  virtual WebSize size() {
    return size_;
  }

  virtual void resize(const WebSize& size) {
    size_ = size;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    // TODO(piman): transparently scale the plugin instead of resizing it.
    plugin_->ViewChanged(plugin_rect, plugin_rect);
    widget_->GenerateFullRepaint();
  }

  virtual void layout() {
  }

  virtual void paint(WebCanvas* canvas, const WebRect& rect) {
    if (!plugin_)
      return;
    WebRect plugin_rect(0, 0, size_.width, size_.height);
    plugin_->Paint(canvas, plugin_rect, rect);
  }

  virtual void composite(bool finish) {
    NOTIMPLEMENTED();
  }

  virtual void themeChanged() {
    NOTIMPLEMENTED();
  }

  virtual bool handleInputEvent(const WebInputEvent& event) {
    if (!plugin_)
      return false;
    return plugin_->HandleInputEvent(event, &cursor_);
  }

  virtual void mouseCaptureLost() {
    NOTIMPLEMENTED();
  }

  virtual void setFocus(bool focus) {
    NOTIMPLEMENTED();
  }

  virtual bool setComposition(
      const WebString& text,
      const WebVector<WebCompositionUnderline>& underlines,
      int selectionStart,
      int selectionEnd) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition() {
    NOTIMPLEMENTED();
    return false;
  }

  virtual bool confirmComposition(const WebString& text) {
    NOTIMPLEMENTED();
    return false;
  }

  virtual WebTextInputType textInputType() {
    NOTIMPLEMENTED();
    return WebKit::WebTextInputTypeNone;
  }

  virtual WebRect caretOrSelectionBounds() {
    NOTIMPLEMENTED();
    return WebRect();
  }

  virtual void setTextDirection(WebTextDirection) {
    NOTIMPLEMENTED();
  }

  virtual bool isAcceleratedCompositingActive() const {
    // TODO(piman): see if supporting accelerated compositing makes sense.
    return false;
  }

 private:
  webkit::ppapi::PluginInstance* plugin_;
  RenderWidgetFullscreenPepper* widget_;
  WebSize size_;
  WebCursorInfo cursor_;

  DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};

// A FullscreenContainer that forwards the API calls to the
// RenderWidgetFullscreenPepper.
class WidgetFullscreenContainer
    : public webkit::ppapi::FullscreenContainer {
 public:
  explicit WidgetFullscreenContainer(RenderWidgetFullscreenPepper* widget)
      : widget_(widget) {
  }
  virtual ~WidgetFullscreenContainer() { }

  virtual void Invalidate() {
    widget_->GenerateFullRepaint();
  }

  virtual void InvalidateRect(const WebKit::WebRect& rect) {
    widget_->didInvalidateRect(rect);
  }

  virtual void ScrollRect(int dx, int dy, const WebKit::WebRect& rect) {
    widget_->didScrollRect(dx, dy, rect);
  }

  virtual void Destroy() {
    widget_->SendClose();
  }

 private:
  RenderWidgetFullscreenPepper* widget_;

  DISALLOW_COPY_AND_ASSIGN(WidgetFullscreenContainer);
};

}  // anonymous namespace

// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
    int32 opener_id, RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin) {
  DCHECK_NE(MSG_ROUTING_NONE, opener_id);
  scoped_refptr<RenderWidgetFullscreenPepper> widget(
      new RenderWidgetFullscreenPepper(render_thread, plugin));
  widget->Init(opener_id);
  return widget.release();
}

RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
    RenderThreadBase* render_thread,
    webkit::ppapi::PluginInstance* plugin)
    : RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
      plugin_(plugin),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          container_(new WidgetFullscreenContainer(this))) {
}

RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
}

WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
  return new PepperWidget(plugin_, this);
}

void RenderWidgetFullscreenPepper::Close() {
  // If the fullscreen window is closed (e.g. user pressed escape), reset to
  // normal mode.
  if (plugin_)
    plugin_->SetFullscreen(false);
}

void RenderWidgetFullscreenPepper::DidInitiatePaint() {
  if (plugin_)
    plugin_->ViewInitiatedPaint();
}

void RenderWidgetFullscreenPepper::DidFlushPaint() {
  if (plugin_)
    plugin_->ViewFlushedPaint();
}

void RenderWidgetFullscreenPepper::SendClose() {
  // This function is called by the plugin instance as it's going away, so reset
  // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
  plugin_ = NULL;
  Send(new ViewHostMsg_Close(routing_id_));
}

void RenderWidgetFullscreenPepper::GenerateFullRepaint() {
  didInvalidateRect(gfx::Rect(size_.width(), size_.height()));
}

webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
    const gfx::Rect& paint_bounds,
    TransportDIB** dib,
    gfx::Rect* location,
    gfx::Rect* clip) {
  if (plugin_ &&
      plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
                                                location, clip))
    return plugin_;
  return NULL;
}
<|endoftext|>


<commit_before>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"
#include "GameObject.h"
#include "cMesh.h"

ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled)
{
	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);

	following = NULL;
}

ModuleCamera3D::~ModuleCamera3D()
{}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	MYLOG("Setting up the camera");
	bool ret = true;

	camera = true;
	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	MYLOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
	cameraDistance = { -20.0f, 10.0f, -20.0f };

	if (camera){
		vec3 newPos(0, 0, 0);
		float speed = 3.0f * dt;
		if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
			speed = 8.0f * dt;

		if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_REPEAT) newPos.y -= speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_E) == KEY_REPEAT) newPos.y += speed * 2;

		if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed * 2;

		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed * 2;

		if (!ImGui::IsMouseHoveringAnyWindow())
		{
			if (App->input->GetMouseZ() == 1)
			{
				newPos -= Z * speed * 10;
			}

			if (App->input->GetMouseZ() == -1)
			{
				newPos += Z * speed * 10;
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN)
		{
			if (App->scene->root != nullptr)
			{

				Position.x = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.x * 2;
				Position.y = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.y * 2;
				Position.z = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.z * 2;
				LookAt(vec3(((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().x, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().y, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().z));

			}

		}

		Position += newPos;
		Reference += newPos;

		// Mouse motion ----------------
			int dx = -App->input->GetMouseXMotion();
			int dy = -App->input->GetMouseYMotion();

		if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
		{
			referenceDone = true;
		}
		if (!ImGui::IsMouseHoveringAnyWindow())
		{
			if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
			{
				float Sensitivity = 0.25f;

				if (dx != 0)
				{
					float DeltaX = (float)dx * Sensitivity;

					X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
				}

				if (dy != 0)
				{
					float DeltaY = (float)dy * Sensitivity;

					Y = rotate(Y, DeltaY, X);
					Z = rotate(Z, DeltaY, X);

					if (Y.y < 0.0f)
					{
						Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
						Y = cross(Z, X);
					}
				}

				//Reference = Position - (Reference - Position);
				Reference = Position - Reference;
			}
			else if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
			{
				float Sensitivity = 0.25f;

				if (((cMesh*)App->editor->selected->FindComponent(MESH)) != nullptr && referenceDone)
				{

					//Reference = vec3((*it)->aabbBox.CenterPoint().x, (*it)->aabbBox.CenterPoint().y, (*it)->aabbBox.CenterPoint().z);
					Reference = vec3(((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().x, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().y, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().z);
					referenceDone = false;
				}

				Position -= Reference;

				if (dx != 0)
				{
					float DeltaX = (float)dx * Sensitivity;

					X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
				}

				if (dy != 0)
				{
					float DeltaY = (float)dy * Sensitivity;

					Y = rotate(Y, DeltaY, X);
					Z = rotate(Z, DeltaY, X);

					if (Y.y < 0.0f)
					{
						Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
						Y = cross(Z, X);
					}
				}

				Position = Reference + Z * length(Position);
			}
		}
	}
	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(vec3 Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if (!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

// -----------------------------------------------------------------
void ModuleCamera3D::Follow(PhysBody3D* body, float min, float max, float height)
{
	minFollowingDist = min;
	maxFollowingDist = max;
	followingHeight = height;
	following = body;
}

// -----------------------------------------------------------------
void ModuleCamera3D::UnFollow()
{
	following = NULL;
}<commit_msg>BUG press f without fbx loaded FIXED<commit_after>#include "Globals.h"
#include "Application.h"
#include "PhysBody3D.h"
#include "ModuleCamera3D.h"
#include "GameObject.h"
#include "cMesh.h"

ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled)
{
	CalculateViewMatrix();

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 0.0f, 5.0f);
	Reference = vec3(0.0f, 0.0f, 0.0f);

	following = NULL;
}

ModuleCamera3D::~ModuleCamera3D()
{}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	MYLOG("Setting up the camera");
	bool ret = true;

	camera = true;
	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	MYLOG("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
	cameraDistance = { -20.0f, 10.0f, -20.0f };

	if (camera){
		vec3 newPos(0, 0, 0);
		float speed = 3.0f * dt;
		if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
			speed = 8.0f * dt;

		if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_REPEAT) newPos.y -= speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_E) == KEY_REPEAT) newPos.y += speed * 2;

		if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed * 2;

		if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed * 2;
		if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed * 2;

		if (!ImGui::IsMouseHoveringAnyWindow())
		{
			if (App->input->GetMouseZ() == 1)
			{
				newPos -= Z * speed * 10;
			}

			if (App->input->GetMouseZ() == -1)
			{
				newPos += Z * speed * 10;
			}
		}

		if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN)
		{
			if (App->scene->root != nullptr)
			{
				if (App->editor->selected != nullptr)
				{
					if (((cMesh*)App->editor->selected->FindComponent(MESH)) != nullptr)
					{
						Position.x = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.x * 2;
						Position.y = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.y * 2;
						Position.z = ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.maxPoint.z * 2;
						LookAt(vec3(((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().x, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().y, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().z));

					}
				}
			}
		}

		Position += newPos;
		Reference += newPos;

		// Mouse motion ----------------
			int dx = -App->input->GetMouseXMotion();
			int dy = -App->input->GetMouseYMotion();

		if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
		{
			referenceDone = true;
		}
		if (!ImGui::IsMouseHoveringAnyWindow())
		{
			if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
			{
				float Sensitivity = 0.25f;

				if (dx != 0)
				{
					float DeltaX = (float)dx * Sensitivity;

					X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
				}

				if (dy != 0)
				{
					float DeltaY = (float)dy * Sensitivity;

					Y = rotate(Y, DeltaY, X);
					Z = rotate(Z, DeltaY, X);

					if (Y.y < 0.0f)
					{
						Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
						Y = cross(Z, X);
					}
				}

				//Reference = Position - (Reference - Position);
				Reference = Position - Reference;
			}
			else if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT)
			{
				float Sensitivity = 0.25f;

				if (App->editor->selected != nullptr)
				{
					if (((cMesh*)App->editor->selected->FindComponent(MESH)) != nullptr && referenceDone)
					{

						//Reference = vec3((*it)->aabbBox.CenterPoint().x, (*it)->aabbBox.CenterPoint().y, (*it)->aabbBox.CenterPoint().z);
						Reference = vec3(((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().x, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().y, ((cMesh*)App->editor->selected->FindComponent(MESH))->aabbBox.CenterPoint().z);
						referenceDone = false;
					}
				}

				Position -= Reference;

				if (dx != 0)
				{
					float DeltaX = (float)dx * Sensitivity;

					X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
					Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
				}

				if (dy != 0)
				{
					float DeltaY = (float)dy * Sensitivity;

					Y = rotate(Y, DeltaY, X);
					Z = rotate(Z, DeltaY, X);

					if (Y.y < 0.0f)
					{
						Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
						Y = cross(Z, X);
					}
				}

				Position = Reference + Z * length(Position);
			}
		}
	}
	// Recalculate matrix -------------
	CalculateViewMatrix();

	return UPDATE_CONTINUE;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(vec3 Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if (!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

// -----------------------------------------------------------------
void ModuleCamera3D::Follow(PhysBody3D* body, float min, float max, float height)
{
	minFollowingDist = min;
	maxFollowingDist = max;
	followingHeight = height;
	following = body;
}

// -----------------------------------------------------------------
void ModuleCamera3D::UnFollow()
{
	following = NULL;
}<|endoftext|>