<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 "sandbox/src/handle_closer_agent.h"

#include "base/logging.h"
#include "sandbox/src/nt_internals.h"
#include "sandbox/src/win_utils.h"

namespace sandbox {

// Memory buffer mapped from the parent, with the list of handles.
SANDBOX_INTERCEPT HandleCloserInfo* g_handles_to_close = NULL;

bool HandleCloserAgent::NeedsHandlesClosed() {
  return g_handles_to_close != NULL;
}

// Reads g_handles_to_close and creates the lookup map.
void HandleCloserAgent::InitializeHandlesToClose() {
  CHECK(g_handles_to_close != NULL);

  // Grab the header.
  HandleListEntry* entry = g_handles_to_close->handle_entries;
  for (size_t i = 0; i < g_handles_to_close->num_handle_types; ++i) {
    // Set the type name.
    char16* input = entry->handle_type;
    HandleMap::mapped_type& handle_names = handles_to_close_[input];
    input = reinterpret_cast<char16*>(reinterpret_cast<char*>(entry)
        + entry->offset_to_names);
    // Grab all the handle names.
    for (size_t j = 0; j < entry->name_count; ++j) {
      std::pair<HandleMap::mapped_type::iterator, bool> name
          = handle_names.insert(input);
      CHECK(name.second);
      input += name.first->size() + 1;
    }

    // Move on to the next entry.
    entry = reinterpret_cast<HandleListEntry*>(reinterpret_cast<char*>(entry)
        + entry->record_bytes);

    DCHECK(reinterpret_cast<char16*>(entry) >= input);
    DCHECK(reinterpret_cast<char16*>(entry) - input <
           sizeof(size_t) / sizeof(char16));
  }

  // Clean up the memory we copied over.
  ::VirtualFree(g_handles_to_close, 0, MEM_RELEASE);
  g_handles_to_close = NULL;
}

bool HandleCloserAgent::CloseHandles() {
  DWORD handle_count = UINT_MAX;
  const int kInvalidHandleThreshold = 100;
  const size_t kHandleOffset = sizeof(HANDLE);

  if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
    return false;

  static NtQueryObject QueryObject = NULL;
  if (!QueryObject)
    ResolveNTFunctionPtr("NtQueryObject", &QueryObject);

  // Set up buffers for the type info and the name.
  std::vector<BYTE> type_info_buffer(sizeof(OBJECT_TYPE_INFORMATION) +
                                     32 * sizeof(wchar_t));
  OBJECT_TYPE_INFORMATION* type_info =
      reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0]));
  string16 handle_name;
  HANDLE handle = NULL;
  int invalid_count = 0;

  // Keep incrementing until we hit the number of handles reported by
  // GetProcessHandleCount(). If we hit a very long sequence of invalid
  // handles we assume that we've run past the end of the table.
  while (handle_count && invalid_count < kInvalidHandleThreshold) {
    reinterpret_cast<size_t&>(handle) += kHandleOffset;
    NTSTATUS rc;

    // Get the type name, reusing the buffer.
    ULONG size = static_cast<ULONG>(type_info_buffer.size());
    rc = QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
    while (rc == STATUS_INFO_LENGTH_MISMATCH ||
           rc == STATUS_BUFFER_OVERFLOW) {
      type_info_buffer.resize(size + sizeof(wchar_t));
      type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(
          &(type_info_buffer[0]));
      rc = QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
      // Leave padding for the nul terminator.
      if (NT_SUCCESS(0) && size == type_info_buffer.size())
        rc = STATUS_INFO_LENGTH_MISMATCH;
    }
    if (!NT_SUCCESS(rc) || !type_info->Name.Buffer) {
      ++invalid_count;
      continue;
    }

    --handle_count;
    type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';

    // Check if we're looking for this type of handle.
    HandleMap::iterator result =
        handles_to_close_.find(type_info->Name.Buffer);
    if (result != handles_to_close_.end()) {
      HandleMap::mapped_type& names = result->second;
      // Empty set means close all handles of this type; otherwise check name.
      if (!names.empty()) {
        // Move on to the next handle if this name doesn't match.
        if (!GetHandleName(handle, &handle_name) || !names.count(handle_name))
          continue;
      }

      if (!::SetHandleInformation(handle, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0))
        return false;
      if (!::CloseHandle(handle))
        return false;
    }
  }

  return true;
}

}  // namespace sandbox
<commit_msg>Suppress STATUS_INVALID_HANDLE (0xc0000008) exceptions triggered by HandleCloserAgent.<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 "sandbox/src/handle_closer_agent.h"

#include "base/logging.h"
#include "sandbox/src/nt_internals.h"
#include "sandbox/src/win_utils.h"

namespace {

// Returns type infomation for an NT object. This routine is expected to be
// called for invalid handles so it catches STATUS_INVALID_HANDLE exceptions
// that can be generated when handle tracing is enabled.
NTSTATUS QueryObjectTypeInformation(HANDLE handle,
                                    void* buffer,
                                    ULONG* size) {
  static NtQueryObject QueryObject = NULL;
  if (!QueryObject)
    ResolveNTFunctionPtr("NtQueryObject", &QueryObject);

  NTSTATUS status = STATUS_UNSUCCESSFUL;
  __try {
    status = QueryObject(handle, ObjectTypeInformation, buffer, *size, size);
  } __except(GetExceptionCode() == STATUS_INVALID_HANDLE ?
                 EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    status = STATUS_INVALID_HANDLE;
  }
  return status;
}

}  // namespace

namespace sandbox {

// Memory buffer mapped from the parent, with the list of handles.
SANDBOX_INTERCEPT HandleCloserInfo* g_handles_to_close = NULL;

bool HandleCloserAgent::NeedsHandlesClosed() {
  return g_handles_to_close != NULL;
}

// Reads g_handles_to_close and creates the lookup map.
void HandleCloserAgent::InitializeHandlesToClose() {
  CHECK(g_handles_to_close != NULL);

  // Grab the header.
  HandleListEntry* entry = g_handles_to_close->handle_entries;
  for (size_t i = 0; i < g_handles_to_close->num_handle_types; ++i) {
    // Set the type name.
    char16* input = entry->handle_type;
    HandleMap::mapped_type& handle_names = handles_to_close_[input];
    input = reinterpret_cast<char16*>(reinterpret_cast<char*>(entry)
        + entry->offset_to_names);
    // Grab all the handle names.
    for (size_t j = 0; j < entry->name_count; ++j) {
      std::pair<HandleMap::mapped_type::iterator, bool> name
          = handle_names.insert(input);
      CHECK(name.second);
      input += name.first->size() + 1;
    }

    // Move on to the next entry.
    entry = reinterpret_cast<HandleListEntry*>(reinterpret_cast<char*>(entry)
        + entry->record_bytes);

    DCHECK(reinterpret_cast<char16*>(entry) >= input);
    DCHECK(reinterpret_cast<char16*>(entry) - input <
           sizeof(size_t) / sizeof(char16));
  }

  // Clean up the memory we copied over.
  ::VirtualFree(g_handles_to_close, 0, MEM_RELEASE);
  g_handles_to_close = NULL;
}

bool HandleCloserAgent::CloseHandles() {
  DWORD handle_count = UINT_MAX;
  const int kInvalidHandleThreshold = 100;
  const size_t kHandleOffset = sizeof(HANDLE);

  if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
    return false;

  // Set up buffers for the type info and the name.
  std::vector<BYTE> type_info_buffer(sizeof(OBJECT_TYPE_INFORMATION) +
                                     32 * sizeof(wchar_t));
  OBJECT_TYPE_INFORMATION* type_info =
      reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0]));
  string16 handle_name;
  HANDLE handle = NULL;
  int invalid_count = 0;

  // Keep incrementing until we hit the number of handles reported by
  // GetProcessHandleCount(). If we hit a very long sequence of invalid
  // handles we assume that we've run past the end of the table.
  while (handle_count && invalid_count < kInvalidHandleThreshold) {
    reinterpret_cast<size_t&>(handle) += kHandleOffset;
    NTSTATUS rc;

    // Get the type name, reusing the buffer.
    ULONG size = static_cast<ULONG>(type_info_buffer.size());
    rc = QueryObjectTypeInformation(handle, type_info, &size);
    while (rc == STATUS_INFO_LENGTH_MISMATCH ||
           rc == STATUS_BUFFER_OVERFLOW) {
      type_info_buffer.resize(size + sizeof(wchar_t));
      type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(
          &(type_info_buffer[0]));
      rc = QueryObjectTypeInformation(handle, type_info, &size);
      // Leave padding for the nul terminator.
      if (NT_SUCCESS(0) && size == type_info_buffer.size())
        rc = STATUS_INFO_LENGTH_MISMATCH;
    }
    if (!NT_SUCCESS(rc) || !type_info->Name.Buffer) {
      ++invalid_count;
      continue;
    }

    --handle_count;
    type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';

    // Check if we're looking for this type of handle.
    HandleMap::iterator result =
        handles_to_close_.find(type_info->Name.Buffer);
    if (result != handles_to_close_.end()) {
      HandleMap::mapped_type& names = result->second;
      // Empty set means close all handles of this type; otherwise check name.
      if (!names.empty()) {
        // Move on to the next handle if this name doesn't match.
        if (!GetHandleName(handle, &handle_name) || !names.count(handle_name))
          continue;
      }

      if (!::SetHandleInformation(handle, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0))
        return false;
      if (!::CloseHandle(handle))
        return false;
    }
  }

  return true;
}

}  // namespace sandbox
<|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 "base/command_line.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

class InstantTest : public InProcessBrowserTest {
 public:
  InstantTest()
      : location_bar_(NULL),
        preview_(NULL) {
    EnableDOMAutomation();
  }

  void SetupInstantProvider(const std::string& page) {
    TemplateURLModel* model = browser()->profile()->GetTemplateURLModel();
    ASSERT_TRUE(model);

    if (!model->loaded()) {
      model->Load();
      ui_test_utils::WaitForNotification(
          NotificationType::TEMPLATE_URL_MODEL_LOADED);
    }

    ASSERT_TRUE(model->loaded());

    // TemplateURLModel takes ownership of this.
    TemplateURL* template_url = new TemplateURL();

    std::string url = StringPrintf(
        "http://%s:%d/files/instant/%s?q={searchTerms}",
        test_server()->host_port_pair().host().c_str(),
        test_server()->host_port_pair().port(),
        page.c_str());
    template_url->SetURL(url, 0, 0);
    template_url->SetInstantURL(url, 0, 0);
    template_url->set_keyword(UTF8ToWide("foo"));
    template_url->set_short_name(UTF8ToWide("foo"));

    model->Add(template_url);
    model->SetDefaultSearchProvider(template_url);
  }

  virtual void FindLocationBar() {
    if (location_bar_)
      return;
    location_bar_ = browser()->window()->GetLocationBar();
    ASSERT_TRUE(location_bar_);
  }

  // Type a character to get instant to trigger.
  void SetupLocationBar() {
    FindLocationBar();
    location_bar_->location_entry()->SetUserText(L"a");
  }

  // Wait for instant to load and ensure it is in the state we expect.
  void SetupPreview() {
    preview_ = browser()->instant()->GetPreviewContents()->tab_contents();
    ASSERT_TRUE(preview_);
    ui_test_utils::WaitForNavigation(&preview_->controller());

    // Verify the initial setup of the search box.
    ASSERT_TRUE(browser()->instant());
    EXPECT_TRUE(browser()->instant()->IsShowingInstant());
    EXPECT_FALSE(browser()->instant()->is_active());

    // When the page loads, the initial searchBox values are set and no events
    // have been called.
    EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
        true, "window.chrome.sv", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onsubmitcalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.oncancelcalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onchangecalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onresizecalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
        "a", "window.chrome.searchBox.value", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
        false, "window.chrome.searchBox.verbatim", preview_));
  }

  void SetLocationBarText(const std::wstring& text) {
    ASSERT_NO_FATAL_FAILURE(FindLocationBar());
    location_bar_->location_entry()->SetUserText(text);
    ui_test_utils::WaitForNotification(
        NotificationType::INSTANT_CONTROLLER_SHOWN);
  }

  void SendKey(app::KeyboardCode key) {
    ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
        browser(), key, false, false, false, false));
  }

  void CheckStringValueFromJavascript(
      const std::string& expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    std::string result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

  void CheckBoolValueFromJavascript(
      bool expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    bool result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

  void CheckIntValueFromJavascript(
      int expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    int result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kEnablePredictiveInstant);
  }

  LocationBar* location_bar_;
  TabContents* preview_;
};

// TODO(tonyg): Add the following tests:
// 1. Test that setSuggestions() works.
// 2. Test that the search box API is not populated for pages other than the
//    default search provider.
// 3. Test resize events.

// Verify that the onchange event is dispatched upon typing in the box.
IN_PROC_BROWSER_TEST_F(InstantTest, OnChangeEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));

  // Check that the value is reflected and onchange is called.
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", preview_));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      false, "window.chrome.searchBox.verbatim", preview_));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.onchangecalls", preview_));
}

// Makes sure that if the server doesn't support the instant API we don't show
// anything.
IN_PROC_BROWSER_TEST_F(InstantTest, SearchServerDoesntSupportInstant) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("empty.html"));
  ASSERT_NO_FATAL_FAILURE(FindLocationBar());
  location_bar_->location_entry()->SetUserText(L"a");
  ASSERT_TRUE(browser()->instant());
  // Because we typed in a search string we should think we're showing instant
  // results.
  EXPECT_TRUE(browser()->instant()->IsShowingInstant());
  // But because we're waiting to determine if the page really supports instant
  // we shouldn't be showing the preview.
  EXPECT_FALSE(browser()->instant()->is_active());

  // When the response comes back that the page doesn't support instant the tab
  // should be closed.
  ui_test_utils::WaitForNotification(NotificationType::TAB_CLOSED);
  EXPECT_FALSE(browser()->instant()->IsShowingInstant());
  EXPECT_FALSE(browser()->instant()->is_active());
}

// Verifies transitioning from loading a non-search string to a search string
// with the provider not supporting instant works (meaning we don't display
// anything).
IN_PROC_BROWSER_TEST_F(InstantTest, NonSearchToSearchDoesntSupportInstant) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("empty.html"));
  GURL url(test_server()->GetURL("files/instant/empty.html"));
  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(UTF8ToWide(url.spec())));
  // The preview should be active and showing.
  ASSERT_TRUE(browser()->instant()->is_active());
  TabContentsWrapper* initial_tab = browser()->instant()->GetPreviewContents();
  ASSERT_TRUE(initial_tab);
  RenderWidgetHostView* rwhv =
      initial_tab->tab_contents()->GetRenderWidgetHostView();
  ASSERT_TRUE(rwhv);
  ASSERT_TRUE(rwhv->IsShowing());

  // Now type in some search text.
  location_bar_->location_entry()->SetUserText(L"a");

  // Instant should still be live.
  ASSERT_TRUE(browser()->instant()->is_active());
  // Because we typed in a search string we should think we're showing instant
  // results.
  EXPECT_TRUE(browser()->instant()->MightSupportInstant());
  // Instant should not be current (it's still loading).
  EXPECT_FALSE(browser()->instant()->IsCurrent());

  // When the response comes back that the page doesn't support instant the tab
  // should be closed.
  ui_test_utils::WaitForNotification(NotificationType::TAB_CLOSED);
  EXPECT_FALSE(browser()->instant()->IsShowingInstant());
  EXPECT_FALSE(browser()->instant()->is_active());
}

// Verify that the onsubmit event is dispatched upon pressing enter.
// TODO(sky): Disabled, http://crbug.com/62940.
IN_PROC_BROWSER_TEST_F(InstantTest, DISABLED_OnSubmitEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
  ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_RETURN));

  // Check that the preview contents have been committed.
  ASSERT_FALSE(browser()->instant()->GetPreviewContents());
  TabContents* contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);

  // Check that the value is reflected and onsubmit is called.
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.sv", contents));
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", contents));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.searchBox.verbatim", contents));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.onsubmitcalls", contents));
}

#if defined(OS_MACOSX)
// Does not pass on Mac.  http://crbug.com/64696
#define MAYBE_OnCancelEvent FAILS_OnCancelEvent
#else
#define MAYBE_OnCancelEvent OnCancelEvent
#endif
// Verify that the oncancel event is dispatched upon losing focus.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnCancelEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_TAB_CONTAINER));

  // Check that the preview contents have been committed.
  ASSERT_FALSE(browser()->instant()->GetPreviewContents());
  TabContents* contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);

  // Check that the value is reflected and oncancel is called.
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.sv", contents));
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", contents));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      false, "window.chrome.searchBox.verbatim", contents));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.oncancelcalls", contents));
}
<commit_msg>Mark InstantTest.NonSearchToSearchDoesntSupportInstant as flaky.<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 "base/command_line.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/omnibox/location_bar.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

class InstantTest : public InProcessBrowserTest {
 public:
  InstantTest()
      : location_bar_(NULL),
        preview_(NULL) {
    EnableDOMAutomation();
  }

  void SetupInstantProvider(const std::string& page) {
    TemplateURLModel* model = browser()->profile()->GetTemplateURLModel();
    ASSERT_TRUE(model);

    if (!model->loaded()) {
      model->Load();
      ui_test_utils::WaitForNotification(
          NotificationType::TEMPLATE_URL_MODEL_LOADED);
    }

    ASSERT_TRUE(model->loaded());

    // TemplateURLModel takes ownership of this.
    TemplateURL* template_url = new TemplateURL();

    std::string url = StringPrintf(
        "http://%s:%d/files/instant/%s?q={searchTerms}",
        test_server()->host_port_pair().host().c_str(),
        test_server()->host_port_pair().port(),
        page.c_str());
    template_url->SetURL(url, 0, 0);
    template_url->SetInstantURL(url, 0, 0);
    template_url->set_keyword(UTF8ToWide("foo"));
    template_url->set_short_name(UTF8ToWide("foo"));

    model->Add(template_url);
    model->SetDefaultSearchProvider(template_url);
  }

  virtual void FindLocationBar() {
    if (location_bar_)
      return;
    location_bar_ = browser()->window()->GetLocationBar();
    ASSERT_TRUE(location_bar_);
  }

  // Type a character to get instant to trigger.
  void SetupLocationBar() {
    FindLocationBar();
    location_bar_->location_entry()->SetUserText(L"a");
  }

  // Wait for instant to load and ensure it is in the state we expect.
  void SetupPreview() {
    preview_ = browser()->instant()->GetPreviewContents()->tab_contents();
    ASSERT_TRUE(preview_);
    ui_test_utils::WaitForNavigation(&preview_->controller());

    // Verify the initial setup of the search box.
    ASSERT_TRUE(browser()->instant());
    EXPECT_TRUE(browser()->instant()->IsShowingInstant());
    EXPECT_FALSE(browser()->instant()->is_active());

    // When the page loads, the initial searchBox values are set and no events
    // have been called.
    EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
        true, "window.chrome.sv", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onsubmitcalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.oncancelcalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onchangecalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
        0, "window.onresizecalls", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
        "a", "window.chrome.searchBox.value", preview_));
    EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
        false, "window.chrome.searchBox.verbatim", preview_));
  }

  void SetLocationBarText(const std::wstring& text) {
    ASSERT_NO_FATAL_FAILURE(FindLocationBar());
    location_bar_->location_entry()->SetUserText(text);
    ui_test_utils::WaitForNotification(
        NotificationType::INSTANT_CONTROLLER_SHOWN);
  }

  void SendKey(app::KeyboardCode key) {
    ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
        browser(), key, false, false, false, false));
  }

  void CheckStringValueFromJavascript(
      const std::string& expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    std::string result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

  void CheckBoolValueFromJavascript(
      bool expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    bool result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

  void CheckIntValueFromJavascript(
      int expected,
      const std::string& function,
      TabContents* tab_contents) {
    std::string script = StringPrintf(
        "window.domAutomationController.send(%s)", function.c_str());
    int result;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
        tab_contents->render_view_host(),
        std::wstring(), UTF8ToWide(script), &result));
    EXPECT_EQ(expected, result);
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitch(switches::kEnablePredictiveInstant);
  }

  LocationBar* location_bar_;
  TabContents* preview_;
};

// TODO(tonyg): Add the following tests:
// 1. Test that setSuggestions() works.
// 2. Test that the search box API is not populated for pages other than the
//    default search provider.
// 3. Test resize events.

// Verify that the onchange event is dispatched upon typing in the box.
IN_PROC_BROWSER_TEST_F(InstantTest, OnChangeEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));

  // Check that the value is reflected and onchange is called.
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", preview_));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      false, "window.chrome.searchBox.verbatim", preview_));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.onchangecalls", preview_));
}

// Makes sure that if the server doesn't support the instant API we don't show
// anything.
IN_PROC_BROWSER_TEST_F(InstantTest, SearchServerDoesntSupportInstant) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("empty.html"));
  ASSERT_NO_FATAL_FAILURE(FindLocationBar());
  location_bar_->location_entry()->SetUserText(L"a");
  ASSERT_TRUE(browser()->instant());
  // Because we typed in a search string we should think we're showing instant
  // results.
  EXPECT_TRUE(browser()->instant()->IsShowingInstant());
  // But because we're waiting to determine if the page really supports instant
  // we shouldn't be showing the preview.
  EXPECT_FALSE(browser()->instant()->is_active());

  // When the response comes back that the page doesn't support instant the tab
  // should be closed.
  ui_test_utils::WaitForNotification(NotificationType::TAB_CLOSED);
  EXPECT_FALSE(browser()->instant()->IsShowingInstant());
  EXPECT_FALSE(browser()->instant()->is_active());
}

// Verifies transitioning from loading a non-search string to a search string
// with the provider not supporting instant works (meaning we don't display
// anything).
// Flaky, http://crbug.com/66539.
IN_PROC_BROWSER_TEST_F(InstantTest,
                       FLAKY_NonSearchToSearchDoesntSupportInstant) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("empty.html"));
  GURL url(test_server()->GetURL("files/instant/empty.html"));
  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(UTF8ToWide(url.spec())));
  // The preview should be active and showing.
  ASSERT_TRUE(browser()->instant()->is_active());
  TabContentsWrapper* initial_tab = browser()->instant()->GetPreviewContents();
  ASSERT_TRUE(initial_tab);
  RenderWidgetHostView* rwhv =
      initial_tab->tab_contents()->GetRenderWidgetHostView();
  ASSERT_TRUE(rwhv);
  ASSERT_TRUE(rwhv->IsShowing());

  // Now type in some search text.
  location_bar_->location_entry()->SetUserText(L"a");

  // Instant should still be live.
  ASSERT_TRUE(browser()->instant()->is_active());
  // Because we typed in a search string we should think we're showing instant
  // results.
  EXPECT_TRUE(browser()->instant()->MightSupportInstant());
  // Instant should not be current (it's still loading).
  EXPECT_FALSE(browser()->instant()->IsCurrent());

  // When the response comes back that the page doesn't support instant the tab
  // should be closed.
  ui_test_utils::WaitForNotification(NotificationType::TAB_CLOSED);
  EXPECT_FALSE(browser()->instant()->IsShowingInstant());
  EXPECT_FALSE(browser()->instant()->is_active());
}

// Verify that the onsubmit event is dispatched upon pressing enter.
// TODO(sky): Disabled, http://crbug.com/62940.
IN_PROC_BROWSER_TEST_F(InstantTest, DISABLED_OnSubmitEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
  ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_RETURN));

  // Check that the preview contents have been committed.
  ASSERT_FALSE(browser()->instant()->GetPreviewContents());
  TabContents* contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);

  // Check that the value is reflected and onsubmit is called.
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.sv", contents));
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", contents));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.searchBox.verbatim", contents));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.onsubmitcalls", contents));
}

#if defined(OS_MACOSX)
// Does not pass on Mac.  http://crbug.com/64696
#define MAYBE_OnCancelEvent FAILS_OnCancelEvent
#else
#define MAYBE_OnCancelEvent OnCancelEvent
#endif
// Verify that the oncancel event is dispatched upon losing focus.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnCancelEvent) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
  ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
  ASSERT_NO_FATAL_FAILURE(SetupPreview());

  ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_TAB_CONTAINER));

  // Check that the preview contents have been committed.
  ASSERT_FALSE(browser()->instant()->GetPreviewContents());
  TabContents* contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);

  // Check that the value is reflected and oncancel is called.
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      true, "window.chrome.sv", contents));
  EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
      "abc", "window.chrome.searchBox.value", contents));
  EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
      false, "window.chrome.searchBox.verbatim", contents));
  EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
      1, "window.oncancelcalls", contents));
}
<|endoftext|>


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

/**
 * @file
 */

#include "modules/third_party_perception/fusion.h"

#include <vector>

#include "modules/common/math/polygon2d.h"
#include "modules/common/math/vec2d.h"
#include "modules/third_party_perception/common/third_party_perception_gflags.h"
#include "modules/third_party_perception/common/third_party_perception_util.h"

/**
 * @namespace apollo::third_party_perception::fusion
 * @brief apollo::third_party_perception
 */
namespace apollo {
namespace third_party_perception {
namespace fusion {

using apollo::common::math::Vec2d;
using apollo::perception::PerceptionObstacles;
using apollo::perception::PerceptionObstacle;

std::vector<Vec2d> PerceptionObstacleToVectorVec2d(
    const PerceptionObstacle& obstacle) {
  std::vector<Vec2d> result;
  for (const auto& vertex : obstacle.polygon_point()) {
    result.emplace_back(vertex.x(), vertex.y());
  }
  return result;
}

bool HasOverlap(const PerceptionObstacle& obstacle_1,
                const PerceptionObstacle& obstacle_2) {
  common::math::Polygon2d polygon_1(
      PerceptionObstacleToVectorVec2d(obstacle_1));
  common::math::Polygon2d polygon_2(
      PerceptionObstacleToVectorVec2d(obstacle_2));
  return polygon_1.HasOverlap(polygon_2);
}

bool HasOverlap(const PerceptionObstacle& obstacle,
                const PerceptionObstacles& obstacles) {
  for (const auto& current_obstacle : obstacles.perception_obstacle()) {
    if (HasOverlap(obstacle, current_obstacle)) {
      return true;
    }
  }
  return false;
}

PerceptionObstacles MobileyeRadarFusion(
    const PerceptionObstacles& mobileye_obstacles,
    const PerceptionObstacles& radar_obstacles) {
  PerceptionObstacles mobileye_obstacles_fusion = mobileye_obstacles;
  PerceptionObstacles radar_obstacles_fusion = radar_obstacles;

  for (auto& mobileye_obstacle :
       *(mobileye_obstacles_fusion.mutable_perception_obstacle())) {
    for (auto& radar_obstacle :
         *(radar_obstacles_fusion.mutable_perception_obstacle())) {
      if (HasOverlap(mobileye_obstacle, radar_obstacle)) {
        mobileye_obstacle.set_confidence(0.99);
        radar_obstacle.set_confidence(0.99);
      }
    }
  }

  mobileye_obstacles_fusion.MergeFrom(radar_obstacles_fusion);
  return mobileye_obstacles_fusion;
}

}  // namespace fusion
}  // namespace third_party_perception
}  // namespace apollo
<commit_msg>ThirdParty : Change simple fusion strategy<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 */

#include "modules/third_party_perception/fusion.h"

#include <vector>

#include "modules/common/math/polygon2d.h"
#include "modules/common/math/vec2d.h"
#include "modules/third_party_perception/common/third_party_perception_gflags.h"
#include "modules/third_party_perception/common/third_party_perception_util.h"

/**
 * @namespace apollo::third_party_perception::fusion
 * @brief apollo::third_party_perception
 */
namespace apollo {
namespace third_party_perception {
namespace fusion {

using apollo::common::math::Vec2d;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;

std::vector<Vec2d> PerceptionObstacleToVectorVec2d(
    const PerceptionObstacle& obstacle) {
  std::vector<Vec2d> result;
  for (const auto& vertex : obstacle.polygon_point()) {
    result.emplace_back(vertex.x(), vertex.y());
  }
  return result;
}

bool HasOverlap(const PerceptionObstacle& obstacle_1,
                const PerceptionObstacle& obstacle_2) {
  common::math::Polygon2d polygon_1(
      PerceptionObstacleToVectorVec2d(obstacle_1));
  common::math::Polygon2d polygon_2(
      PerceptionObstacleToVectorVec2d(obstacle_2));
  return polygon_1.HasOverlap(polygon_2);
}

bool HasOverlap(const PerceptionObstacle& obstacle,
                const PerceptionObstacles& obstacles) {
  for (const auto& current_obstacle : obstacles.perception_obstacle()) {
    if (HasOverlap(obstacle, current_obstacle)) {
      return true;
    }
  }
  return false;
}

PerceptionObstacles MobileyeRadarFusion(
    const PerceptionObstacles& mobileye_obstacles,
    const PerceptionObstacles& radar_obstacles) {
  PerceptionObstacles mobileye_obstacles_fusion = mobileye_obstacles;
  PerceptionObstacles radar_obstacles_fusion = radar_obstacles;

  for (auto& mobileye_obstacle :
       *(mobileye_obstacles_fusion.mutable_perception_obstacle())) {
    for (auto& radar_obstacle :
         *(radar_obstacles_fusion.mutable_perception_obstacle())) {
      if (HasOverlap(mobileye_obstacle, radar_obstacle)) {
        mobileye_obstacle.set_confidence(0.99);
        mobileye_obstacle.mutable_velocity()->CopyFrom(
            radar_obstacle.velocity());
      }
    }
  }

  // mobileye_obstacles_fusion.MergeFrom(radar_obstacles_fusion);
  return mobileye_obstacles_fusion;
}

}  // namespace fusion
}  // namespace third_party_perception
}  // namespace apollo
<|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/browser/speech/speech_input_manager.h"

#include <map>
#include <string>

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "base/ref_counted.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/speech/speech_input_bubble_controller.h"
#include "chrome/browser/speech/speech_recognizer.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "media/audio/audio_manager.h"

#if defined(OS_WIN)
#include "chrome/browser/browser_process.h"
#include "chrome/installer/util/wmi.h"
#endif

namespace {

// Asynchronously fetches the PC and audio hardware/driver info on windows if
// the user has opted into UMA. This information is sent with speech input
// requests to the server for identifying and improving quality issues with
// specific device configurations.
class HardwareInfo : public base::RefCountedThreadSafe<HardwareInfo> {
 public:
  HardwareInfo() {}

#if defined(OS_WIN)
  void Refresh() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    // UMA opt-in can be checked only from the UI thread, so switch to that.
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(this, &HardwareInfo::CheckUMAAndGetHardwareInfo));
  }

  void CheckUMAAndGetHardwareInfo() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (g_browser_process->local_state()->GetBoolean(
        prefs::kMetricsReportingEnabled)) {
      // Access potentially slow OS calls from the FILE thread.
      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &HardwareInfo::GetHardwareInfo));
    }
  }

  void GetHardwareInfo() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
    AutoLock lock(lock_);
    value_ = UTF16ToUTF8(
        installer::WMIComputerSystem::GetModel() + L"|" +
        AudioManager::GetAudioManager()->GetAudioInputDeviceModel());
  }

  std::string value() {
    AutoLock lock(lock_);
    return value_;
  }

 private:
  Lock lock_;
  std::string value_;

#else  // defined(OS_WIN)
  void Refresh() {}
  std::string value() { return std::string(); }
#endif  // defined(OS_WIN)

  DISALLOW_COPY_AND_ASSIGN(HardwareInfo);
};

}  // namespace

namespace speech_input {

class SpeechInputManagerImpl : public SpeechInputManager,
                               public SpeechInputBubbleControllerDelegate,
                               public SpeechRecognizerDelegate {
 public:
  // SpeechInputManager methods.
  virtual void StartRecognition(SpeechInputManagerDelegate* delegate,
                                int caller_id,
                                int render_process_id,
                                int render_view_id,
                                const gfx::Rect& element_rect,
                                const std::string& language,
                                const std::string& grammar);
  virtual void CancelRecognition(int caller_id);
  virtual void StopRecording(int caller_id);

  // SpeechRecognizer::Delegate methods.
  virtual void SetRecognitionResult(int caller_id,
                                    bool error,
                                    const SpeechInputResultArray& result);
  virtual void DidCompleteRecording(int caller_id);
  virtual void DidCompleteRecognition(int caller_id);
  virtual void OnRecognizerError(int caller_id,
                                 SpeechRecognizer::ErrorCode error);
  virtual void DidCompleteEnvironmentEstimation(int caller_id);
  virtual void SetInputVolume(int caller_id, float volume);

  // SpeechInputBubbleController::Delegate methods.
  virtual void InfoBubbleButtonClicked(int caller_id,
                                       SpeechInputBubble::Button button);
  virtual void InfoBubbleFocusChanged(int caller_id);

 private:
  struct SpeechInputRequest {
    SpeechInputManagerDelegate* delegate;
    scoped_refptr<SpeechRecognizer> recognizer;
    bool is_active;  // Set to true when recording or recognition is going on.
  };

  // Private constructor to enforce singleton.
  friend struct base::DefaultLazyInstanceTraits<SpeechInputManagerImpl>;
  SpeechInputManagerImpl();
  virtual ~SpeechInputManagerImpl();

  bool HasPendingRequest(int caller_id) const;
  SpeechInputManagerDelegate* GetDelegate(int caller_id) const;

  void CancelRecognitionAndInformDelegate(int caller_id);

  // Starts/restarts recognition for an existing request.
  void StartRecognitionForRequest(int caller_id);

  SpeechInputManagerDelegate* delegate_;
  typedef std::map<int, SpeechInputRequest> SpeechRecognizerMap;
  SpeechRecognizerMap requests_;
  int recording_caller_id_;
  scoped_refptr<SpeechInputBubbleController> bubble_controller_;
  scoped_refptr<HardwareInfo> hardware_info_;
};

static ::base::LazyInstance<SpeechInputManagerImpl> g_speech_input_manager_impl(
    base::LINKER_INITIALIZED);

SpeechInputManager* SpeechInputManager::Get() {
  return g_speech_input_manager_impl.Pointer();
}

bool SpeechInputManager::IsFeatureEnabled() {
  bool enabled = true;
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();

  if (command_line.HasSwitch(switches::kDisableSpeechInput)) {
    enabled = false;
#if defined(GOOGLE_CHROME_BUILD)
  } else if (!command_line.HasSwitch(switches::kEnableSpeechInput)) {
    // We need to evaluate whether IO is OK here. http://crbug.com/63335.
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    // Official Chrome builds have speech input enabled by default only in the
    // dev channel.
    std::string channel = platform_util::GetVersionStringModifier();
    enabled = (channel == "dev");
#endif
  }

  return enabled;
}

SpeechInputManagerImpl::SpeechInputManagerImpl()
    : recording_caller_id_(0),
      bubble_controller_(new SpeechInputBubbleController(
          ALLOW_THIS_IN_INITIALIZER_LIST(this))) {
}

SpeechInputManagerImpl::~SpeechInputManagerImpl() {
  while (requests_.begin() != requests_.end())
    CancelRecognition(requests_.begin()->first);
}

bool SpeechInputManagerImpl::HasPendingRequest(int caller_id) const {
  return requests_.find(caller_id) != requests_.end();
}

SpeechInputManagerDelegate* SpeechInputManagerImpl::GetDelegate(
    int caller_id) const {
  return requests_.find(caller_id)->second.delegate;
}

void SpeechInputManagerImpl::StartRecognition(
    SpeechInputManagerDelegate* delegate,
    int caller_id,
    int render_process_id,
    int render_view_id,
    const gfx::Rect& element_rect,
    const std::string& language,
    const std::string& grammar) {
  DCHECK(!HasPendingRequest(caller_id));

  bubble_controller_->CreateBubble(caller_id, render_process_id, render_view_id,
                                   element_rect);

  if (!hardware_info_.get()) {
    hardware_info_ = new HardwareInfo();
    // Since hardware info is optional with speech input requests, we start an
    // asynchronous fetch here and move on with recording audio. This first
    // speech input request would send an empty string for hardware info and
    // subsequent requests may have the hardware info available if the fetch
    // completed before them. This way we don't end up stalling the user with
    // a long wait and disk seeks when they click on a UI element and start
    // speaking.
    hardware_info_->Refresh();
  }

  SpeechInputRequest* request = &requests_[caller_id];
  request->delegate = delegate;
  request->recognizer = new SpeechRecognizer(this, caller_id, language,
                                             grammar, hardware_info_->value());
  request->is_active = false;

  StartRecognitionForRequest(caller_id);
}

void SpeechInputManagerImpl::StartRecognitionForRequest(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));

  // If we are currently recording audio for another caller, abort that cleanly.
  if (recording_caller_id_)
    CancelRecognitionAndInformDelegate(recording_caller_id_);

  if (!AudioManager::GetAudioManager()->HasAudioInputDevices()) {
    bubble_controller_->SetBubbleMessage(
        caller_id, l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_NO_MIC));
  } else {
    recording_caller_id_ = caller_id;
    requests_[caller_id].is_active = true;
    requests_[caller_id].recognizer->StartRecording();
  }
}

void SpeechInputManagerImpl::CancelRecognition(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  if (requests_[caller_id].is_active)
    requests_[caller_id].recognizer->CancelRecognition();
  requests_.erase(caller_id);
  if (recording_caller_id_ == caller_id)
    recording_caller_id_ = 0;
  bubble_controller_->CloseBubble(caller_id);
}

void SpeechInputManagerImpl::StopRecording(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  requests_[caller_id].recognizer->StopRecording();
}

void SpeechInputManagerImpl::SetRecognitionResult(
    int caller_id, bool error, const SpeechInputResultArray& result) {
  DCHECK(HasPendingRequest(caller_id));
  GetDelegate(caller_id)->SetRecognitionResult(caller_id, result);
}

void SpeechInputManagerImpl::DidCompleteRecording(int caller_id) {
  DCHECK(recording_caller_id_ == caller_id);
  DCHECK(HasPendingRequest(caller_id));
  recording_caller_id_ = 0;
  GetDelegate(caller_id)->DidCompleteRecording(caller_id);
  bubble_controller_->SetBubbleRecognizingMode(caller_id);
}

void SpeechInputManagerImpl::DidCompleteRecognition(int caller_id) {
  GetDelegate(caller_id)->DidCompleteRecognition(caller_id);
  requests_.erase(caller_id);
  bubble_controller_->CloseBubble(caller_id);
}

void SpeechInputManagerImpl::OnRecognizerError(
    int caller_id, SpeechRecognizer::ErrorCode error) {
  if (caller_id == recording_caller_id_)
    recording_caller_id_ = 0;

  requests_[caller_id].is_active = false;

  int message_id;
  switch (error) {
    case SpeechRecognizer::RECOGNIZER_ERROR_CAPTURE:
      message_id = IDS_SPEECH_INPUT_ERROR;
      break;
    case SpeechRecognizer::RECOGNIZER_ERROR_NO_SPEECH:
      message_id = IDS_SPEECH_INPUT_NO_SPEECH;
      break;
    case SpeechRecognizer::RECOGNIZER_ERROR_NO_RESULTS:
      message_id = IDS_SPEECH_INPUT_NO_RESULTS;
      break;
    default:
      NOTREACHED() << "unknown error " << error;
      return;
  }
  bubble_controller_->SetBubbleMessage(caller_id,
                                       l10n_util::GetStringUTF16(message_id));
}

void SpeechInputManagerImpl::DidCompleteEnvironmentEstimation(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  DCHECK(recording_caller_id_ == caller_id);

  // Speech recognizer has gathered enough background audio so we can ask the
  // user to start speaking.
  bubble_controller_->SetBubbleRecordingMode(caller_id);
}

void SpeechInputManagerImpl::SetInputVolume(int caller_id, float volume) {
  DCHECK(HasPendingRequest(caller_id));
  DCHECK_EQ(recording_caller_id_, caller_id);

  bubble_controller_->SetBubbleInputVolume(caller_id, volume);
}

void SpeechInputManagerImpl::CancelRecognitionAndInformDelegate(int caller_id) {
  SpeechInputManagerDelegate* cur_delegate = GetDelegate(caller_id);
  CancelRecognition(caller_id);
  cur_delegate->DidCompleteRecording(caller_id);
  cur_delegate->DidCompleteRecognition(caller_id);
}

void SpeechInputManagerImpl::InfoBubbleButtonClicked(
    int caller_id, SpeechInputBubble::Button button) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // Ignore if the caller id was not in our active recognizers list because the
  // user might have clicked more than once, or recognition could have been
  // cancelled due to other reasons before the user click was processed.
  if (!HasPendingRequest(caller_id))
    return;

  if (button == SpeechInputBubble::BUTTON_CANCEL) {
    CancelRecognitionAndInformDelegate(caller_id);
  } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) {
    StartRecognitionForRequest(caller_id);
  }
}

void SpeechInputManagerImpl::InfoBubbleFocusChanged(int caller_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // Ignore if the caller id was not in our active recognizers list because the
  // user might have clicked more than once, or recognition could have been
  // ended due to other reasons before the user click was processed.
  if (HasPendingRequest(caller_id)) {
    // If this is an ongoing recording or if we were displaying an error message
    // to the user, abort it since user has switched focus. Otherwise
    // recognition has started and keep that going so user can start speaking to
    // another element while this gets the results in parallel.
    if (recording_caller_id_ == caller_id || !requests_[caller_id].is_active) {
      CancelRecognitionAndInformDelegate(caller_id);
    }
  }
}

}  // namespace speech_input
<commit_msg>Fix official chrome linux builder (missing include).<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/browser/speech/speech_input_manager.h"

#include <map>
#include <string>

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/lock.h"
#include "base/ref_counted.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/speech/speech_input_bubble_controller.h"
#include "chrome/browser/speech/speech_recognizer.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "media/audio/audio_manager.h"

#if defined(OS_WIN)
#include "chrome/browser/browser_process.h"
#include "chrome/installer/util/wmi.h"
#endif

namespace {

// Asynchronously fetches the PC and audio hardware/driver info on windows if
// the user has opted into UMA. This information is sent with speech input
// requests to the server for identifying and improving quality issues with
// specific device configurations.
class HardwareInfo : public base::RefCountedThreadSafe<HardwareInfo> {
 public:
  HardwareInfo() {}

#if defined(OS_WIN)
  void Refresh() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    // UMA opt-in can be checked only from the UI thread, so switch to that.
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(this, &HardwareInfo::CheckUMAAndGetHardwareInfo));
  }

  void CheckUMAAndGetHardwareInfo() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (g_browser_process->local_state()->GetBoolean(
        prefs::kMetricsReportingEnabled)) {
      // Access potentially slow OS calls from the FILE thread.
      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
          NewRunnableMethod(this, &HardwareInfo::GetHardwareInfo));
    }
  }

  void GetHardwareInfo() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
    AutoLock lock(lock_);
    value_ = UTF16ToUTF8(
        installer::WMIComputerSystem::GetModel() + L"|" +
        AudioManager::GetAudioManager()->GetAudioInputDeviceModel());
  }

  std::string value() {
    AutoLock lock(lock_);
    return value_;
  }

 private:
  Lock lock_;
  std::string value_;

#else  // defined(OS_WIN)
  void Refresh() {}
  std::string value() { return std::string(); }
#endif  // defined(OS_WIN)

  DISALLOW_COPY_AND_ASSIGN(HardwareInfo);
};

}  // namespace

namespace speech_input {

class SpeechInputManagerImpl : public SpeechInputManager,
                               public SpeechInputBubbleControllerDelegate,
                               public SpeechRecognizerDelegate {
 public:
  // SpeechInputManager methods.
  virtual void StartRecognition(SpeechInputManagerDelegate* delegate,
                                int caller_id,
                                int render_process_id,
                                int render_view_id,
                                const gfx::Rect& element_rect,
                                const std::string& language,
                                const std::string& grammar);
  virtual void CancelRecognition(int caller_id);
  virtual void StopRecording(int caller_id);

  // SpeechRecognizer::Delegate methods.
  virtual void SetRecognitionResult(int caller_id,
                                    bool error,
                                    const SpeechInputResultArray& result);
  virtual void DidCompleteRecording(int caller_id);
  virtual void DidCompleteRecognition(int caller_id);
  virtual void OnRecognizerError(int caller_id,
                                 SpeechRecognizer::ErrorCode error);
  virtual void DidCompleteEnvironmentEstimation(int caller_id);
  virtual void SetInputVolume(int caller_id, float volume);

  // SpeechInputBubbleController::Delegate methods.
  virtual void InfoBubbleButtonClicked(int caller_id,
                                       SpeechInputBubble::Button button);
  virtual void InfoBubbleFocusChanged(int caller_id);

 private:
  struct SpeechInputRequest {
    SpeechInputManagerDelegate* delegate;
    scoped_refptr<SpeechRecognizer> recognizer;
    bool is_active;  // Set to true when recording or recognition is going on.
  };

  // Private constructor to enforce singleton.
  friend struct base::DefaultLazyInstanceTraits<SpeechInputManagerImpl>;
  SpeechInputManagerImpl();
  virtual ~SpeechInputManagerImpl();

  bool HasPendingRequest(int caller_id) const;
  SpeechInputManagerDelegate* GetDelegate(int caller_id) const;

  void CancelRecognitionAndInformDelegate(int caller_id);

  // Starts/restarts recognition for an existing request.
  void StartRecognitionForRequest(int caller_id);

  SpeechInputManagerDelegate* delegate_;
  typedef std::map<int, SpeechInputRequest> SpeechRecognizerMap;
  SpeechRecognizerMap requests_;
  int recording_caller_id_;
  scoped_refptr<SpeechInputBubbleController> bubble_controller_;
  scoped_refptr<HardwareInfo> hardware_info_;
};

static ::base::LazyInstance<SpeechInputManagerImpl> g_speech_input_manager_impl(
    base::LINKER_INITIALIZED);

SpeechInputManager* SpeechInputManager::Get() {
  return g_speech_input_manager_impl.Pointer();
}

bool SpeechInputManager::IsFeatureEnabled() {
  bool enabled = true;
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();

  if (command_line.HasSwitch(switches::kDisableSpeechInput)) {
    enabled = false;
#if defined(GOOGLE_CHROME_BUILD)
  } else if (!command_line.HasSwitch(switches::kEnableSpeechInput)) {
    // We need to evaluate whether IO is OK here. http://crbug.com/63335.
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    // Official Chrome builds have speech input enabled by default only in the
    // dev channel.
    std::string channel = platform_util::GetVersionStringModifier();
    enabled = (channel == "dev");
#endif
  }

  return enabled;
}

SpeechInputManagerImpl::SpeechInputManagerImpl()
    : recording_caller_id_(0),
      bubble_controller_(new SpeechInputBubbleController(
          ALLOW_THIS_IN_INITIALIZER_LIST(this))) {
}

SpeechInputManagerImpl::~SpeechInputManagerImpl() {
  while (requests_.begin() != requests_.end())
    CancelRecognition(requests_.begin()->first);
}

bool SpeechInputManagerImpl::HasPendingRequest(int caller_id) const {
  return requests_.find(caller_id) != requests_.end();
}

SpeechInputManagerDelegate* SpeechInputManagerImpl::GetDelegate(
    int caller_id) const {
  return requests_.find(caller_id)->second.delegate;
}

void SpeechInputManagerImpl::StartRecognition(
    SpeechInputManagerDelegate* delegate,
    int caller_id,
    int render_process_id,
    int render_view_id,
    const gfx::Rect& element_rect,
    const std::string& language,
    const std::string& grammar) {
  DCHECK(!HasPendingRequest(caller_id));

  bubble_controller_->CreateBubble(caller_id, render_process_id, render_view_id,
                                   element_rect);

  if (!hardware_info_.get()) {
    hardware_info_ = new HardwareInfo();
    // Since hardware info is optional with speech input requests, we start an
    // asynchronous fetch here and move on with recording audio. This first
    // speech input request would send an empty string for hardware info and
    // subsequent requests may have the hardware info available if the fetch
    // completed before them. This way we don't end up stalling the user with
    // a long wait and disk seeks when they click on a UI element and start
    // speaking.
    hardware_info_->Refresh();
  }

  SpeechInputRequest* request = &requests_[caller_id];
  request->delegate = delegate;
  request->recognizer = new SpeechRecognizer(this, caller_id, language,
                                             grammar, hardware_info_->value());
  request->is_active = false;

  StartRecognitionForRequest(caller_id);
}

void SpeechInputManagerImpl::StartRecognitionForRequest(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));

  // If we are currently recording audio for another caller, abort that cleanly.
  if (recording_caller_id_)
    CancelRecognitionAndInformDelegate(recording_caller_id_);

  if (!AudioManager::GetAudioManager()->HasAudioInputDevices()) {
    bubble_controller_->SetBubbleMessage(
        caller_id, l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_NO_MIC));
  } else {
    recording_caller_id_ = caller_id;
    requests_[caller_id].is_active = true;
    requests_[caller_id].recognizer->StartRecording();
  }
}

void SpeechInputManagerImpl::CancelRecognition(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  if (requests_[caller_id].is_active)
    requests_[caller_id].recognizer->CancelRecognition();
  requests_.erase(caller_id);
  if (recording_caller_id_ == caller_id)
    recording_caller_id_ = 0;
  bubble_controller_->CloseBubble(caller_id);
}

void SpeechInputManagerImpl::StopRecording(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  requests_[caller_id].recognizer->StopRecording();
}

void SpeechInputManagerImpl::SetRecognitionResult(
    int caller_id, bool error, const SpeechInputResultArray& result) {
  DCHECK(HasPendingRequest(caller_id));
  GetDelegate(caller_id)->SetRecognitionResult(caller_id, result);
}

void SpeechInputManagerImpl::DidCompleteRecording(int caller_id) {
  DCHECK(recording_caller_id_ == caller_id);
  DCHECK(HasPendingRequest(caller_id));
  recording_caller_id_ = 0;
  GetDelegate(caller_id)->DidCompleteRecording(caller_id);
  bubble_controller_->SetBubbleRecognizingMode(caller_id);
}

void SpeechInputManagerImpl::DidCompleteRecognition(int caller_id) {
  GetDelegate(caller_id)->DidCompleteRecognition(caller_id);
  requests_.erase(caller_id);
  bubble_controller_->CloseBubble(caller_id);
}

void SpeechInputManagerImpl::OnRecognizerError(
    int caller_id, SpeechRecognizer::ErrorCode error) {
  if (caller_id == recording_caller_id_)
    recording_caller_id_ = 0;

  requests_[caller_id].is_active = false;

  int message_id;
  switch (error) {
    case SpeechRecognizer::RECOGNIZER_ERROR_CAPTURE:
      message_id = IDS_SPEECH_INPUT_ERROR;
      break;
    case SpeechRecognizer::RECOGNIZER_ERROR_NO_SPEECH:
      message_id = IDS_SPEECH_INPUT_NO_SPEECH;
      break;
    case SpeechRecognizer::RECOGNIZER_ERROR_NO_RESULTS:
      message_id = IDS_SPEECH_INPUT_NO_RESULTS;
      break;
    default:
      NOTREACHED() << "unknown error " << error;
      return;
  }
  bubble_controller_->SetBubbleMessage(caller_id,
                                       l10n_util::GetStringUTF16(message_id));
}

void SpeechInputManagerImpl::DidCompleteEnvironmentEstimation(int caller_id) {
  DCHECK(HasPendingRequest(caller_id));
  DCHECK(recording_caller_id_ == caller_id);

  // Speech recognizer has gathered enough background audio so we can ask the
  // user to start speaking.
  bubble_controller_->SetBubbleRecordingMode(caller_id);
}

void SpeechInputManagerImpl::SetInputVolume(int caller_id, float volume) {
  DCHECK(HasPendingRequest(caller_id));
  DCHECK_EQ(recording_caller_id_, caller_id);

  bubble_controller_->SetBubbleInputVolume(caller_id, volume);
}

void SpeechInputManagerImpl::CancelRecognitionAndInformDelegate(int caller_id) {
  SpeechInputManagerDelegate* cur_delegate = GetDelegate(caller_id);
  CancelRecognition(caller_id);
  cur_delegate->DidCompleteRecording(caller_id);
  cur_delegate->DidCompleteRecognition(caller_id);
}

void SpeechInputManagerImpl::InfoBubbleButtonClicked(
    int caller_id, SpeechInputBubble::Button button) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // Ignore if the caller id was not in our active recognizers list because the
  // user might have clicked more than once, or recognition could have been
  // cancelled due to other reasons before the user click was processed.
  if (!HasPendingRequest(caller_id))
    return;

  if (button == SpeechInputBubble::BUTTON_CANCEL) {
    CancelRecognitionAndInformDelegate(caller_id);
  } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) {
    StartRecognitionForRequest(caller_id);
  }
}

void SpeechInputManagerImpl::InfoBubbleFocusChanged(int caller_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // Ignore if the caller id was not in our active recognizers list because the
  // user might have clicked more than once, or recognition could have been
  // ended due to other reasons before the user click was processed.
  if (HasPendingRequest(caller_id)) {
    // If this is an ongoing recording or if we were displaying an error message
    // to the user, abort it since user has switched focus. Otherwise
    // recognition has started and keep that going so user can start speaking to
    // another element while this gets the results in parallel.
    if (recording_caller_id_ == caller_id || !requests_[caller_id].is_active) {
      CancelRecognitionAndInformDelegate(caller_id);
    }
  }
}

}  // namespace speech_input
<|endoftext|>


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

#include "chrome/browser/views/tabs/dragged_tab_view.h"

#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/browser/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/views/tabs/hwnd_photobooth.h"
#include "chrome/browser/views/tabs/tab_renderer.h"
#include "chrome/views/container_win.h"
#include "skia/include/SkShader.h"

const int kTransparentAlpha = 200;
const int kOpaqueAlpha = 255;
const int kDragFrameBorderSize = 2;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
static const SkColor kDraggedTabBorderColor = SkColorSetRGB(103, 129, 162);

////////////////////////////////////////////////////////////////////////////////
// DraggedTabView, public:

DraggedTabView::DraggedTabView(TabContents* datasource,
                               const gfx::Point& mouse_tab_offset,
                               const gfx::Size& contents_size)
    : container_(NULL),
      renderer_(new TabRenderer),
      attached_(false),
      mouse_tab_offset_(mouse_tab_offset),
      attached_tab_size_(TabRenderer::GetMinimumSelectedSize()),
      photobooth_(NULL),
      contents_size_(contents_size),
      close_animation_(this) {
  SetParentOwned(false);

  renderer_->UpdateData(datasource);

  container_.reset(new views::ContainerWin);
  container_->set_window_style(WS_POPUP);
  container_->set_window_ex_style(
    WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW);
  container_->set_can_update_layered_window(false);
  container_->Init(NULL, gfx::Rect(0, 0, 0, 0), false);
  container_->SetContentsView(this);
}

DraggedTabView::~DraggedTabView() {
  if (close_animation_.IsAnimating())
    close_animation_.Stop();
  GetParent()->RemoveChildView(this);
  container_->CloseNow();
}

void DraggedTabView::MoveTo(const gfx::Point& screen_point) {
  if (!container_->IsVisible())
    container_->ShowWindow(SW_SHOWNOACTIVATE);

  int x;
  if (UILayoutIsRightToLeft() && !attached_) {
    // On RTL locales, a dragged tab (when it is not attached to a tab strip)
    // is rendered using a right-to-left orientation so we should calculate the
    // window position differently.
    gfx::Size ps = GetPreferredSize();
    x = screen_point.x() - ScaleValue(ps.width()) + mouse_tab_offset_.x() +
        ScaleValue(
            renderer_->MirroredXCoordinateInsideView(mouse_tab_offset_.x()));
  } else {
    x = screen_point.x() + mouse_tab_offset_.x() -
        ScaleValue(mouse_tab_offset_.x());
  }
  int y = screen_point.y() + mouse_tab_offset_.y() -
      ScaleValue(mouse_tab_offset_.y());

  container_->SetWindowPos(NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}

void DraggedTabView::Attach(int selected_width) {
  attached_ = true;
  photobooth_ = NULL;
  attached_tab_size_.set_width(selected_width);
  container_->SetLayeredAlpha(kOpaqueAlpha);
  ResizeContainer();
  Update();
}

void DraggedTabView::Detach(HWNDPhotobooth* photobooth) {
  attached_ = false;
  photobooth_ = photobooth;
  container_->SetLayeredAlpha(kTransparentAlpha);
  ResizeContainer();
  Update();
}

void DraggedTabView::Update() {
  container_->set_can_update_layered_window(true);
  SchedulePaint();
  container_->PaintNow(gfx::Rect());
  container_->set_can_update_layered_window(false);
}

void DraggedTabView::AnimateToBounds(const gfx::Rect& bounds,
                                     Callback0::Type* callback) {
  animation_callback_.reset(callback);

  RECT wr;
  GetWindowRect(GetContainer()->GetHWND(), &wr);
  animation_start_bounds_ = wr;
  animation_end_bounds_ = bounds;

  close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
  close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
  if (!close_animation_.IsShowing()) {
    close_animation_.Reset();
    close_animation_.Show();
  }
}

///////////////////////////////////////////////////////////////////////////////
// DraggedTabView, AnimationDelegate implementation:

void DraggedTabView::AnimationProgressed(const Animation* animation) {
  int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
  int x = animation_start_bounds_.x() +
      static_cast<int>(delta_x * animation->GetCurrentValue());
  int y = animation_end_bounds_.y();
  container_->SetWindowPos(NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}

void DraggedTabView::AnimationEnded(const Animation* animation) {
  animation_callback_->Run();
}

void DraggedTabView::AnimationCanceled(const Animation* animation) {
  AnimationEnded(animation);
}

///////////////////////////////////////////////////////////////////////////////
// DraggedTabView, views::View overrides:

void DraggedTabView::Paint(ChromeCanvas* canvas) {
  if (attached_) {
    PaintAttachedTab(canvas);
  } else {
    PaintDetachedView(canvas);
  }
}

void DraggedTabView::Layout() {
  if (attached_) {
    gfx::Size prefsize = GetPreferredSize();
    renderer_->SetBounds(0, 0, prefsize.width(), prefsize.height());
  } else {
    int left = 0;
    if (UILayoutIsRightToLeft())
      left = GetPreferredSize().width() - attached_tab_size_.width();
    renderer_->SetBounds(left, 0, left + attached_tab_size_.width(),
                         attached_tab_size_.height());
  }
}

gfx::Size DraggedTabView::GetPreferredSize() {
  if (attached_)
    return attached_tab_size_;

  int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
      kTwiceDragFrameBorderSize;
  int height = attached_tab_size_.height() + kDragFrameBorderSize +
      contents_size_.height();
  return gfx::Size(width, height);
}

////////////////////////////////////////////////////////////////////////////////
// DraggedTabView, private:

void DraggedTabView::PaintAttachedTab(ChromeCanvas* canvas) {
  renderer_->ProcessPaint(canvas);
}

void DraggedTabView::PaintDetachedView(ChromeCanvas* canvas) {
  gfx::Size ps = GetPreferredSize();
  ChromeCanvas scale_canvas(ps.width(), ps.height(), false);
  SkBitmap& bitmap_device = const_cast<SkBitmap&>(
      scale_canvas.getTopPlatformDevice().accessBitmap(true));
  bitmap_device.eraseARGB(0, 0, 0, 0);

  scale_canvas.FillRectInt(kDraggedTabBorderColor, 0,
      attached_tab_size_.height() - kDragFrameBorderSize,
      ps.width(), ps.height() - attached_tab_size_.height());
  int image_x = kDragFrameBorderSize;
  int image_y = attached_tab_size_.height();
  int image_w = ps.width() - kTwiceDragFrameBorderSize;
  int image_h =
      ps.height() - kTwiceDragFrameBorderSize - attached_tab_size_.height();
  scale_canvas.FillRectInt(SK_ColorBLACK, image_x, image_y, image_w, image_h);
  photobooth_->PaintScreenshotIntoCanvas(
      &scale_canvas,
      gfx::Rect(image_x, image_y, image_w, image_h));
  renderer_->ProcessPaint(&scale_canvas);

  SkIRect subset;
  subset.set(0, 0, ps.width(), ps.height());
  SkBitmap mipmap = scale_canvas.ExtractBitmap();
  mipmap.buildMipMap(true);

  SkShader* bitmap_shader =
      SkShader::CreateBitmapShader(mipmap, SkShader::kClamp_TileMode,
                                   SkShader::kClamp_TileMode);

  SkMatrix shader_scale;
  shader_scale.setScale(kScalingFactor, kScalingFactor);
  bitmap_shader->setLocalMatrix(shader_scale);

  SkPaint paint;
  paint.setShader(bitmap_shader);
  paint.setAntiAlias(true);
  bitmap_shader->unref();

  SkRect rc;
  rc.fLeft = 0;
  rc.fTop = 0;
  rc.fRight = SkIntToScalar(ps.width());
  rc.fBottom = SkIntToScalar(ps.height());
  canvas->drawRect(rc, paint);
}

void DraggedTabView::ResizeContainer() {
  gfx::Size ps = GetPreferredSize();
  SetWindowPos(container_->GetHWND(), HWND_TOPMOST, 0, 0,
               ScaleValue(ps.width()), ScaleValue(ps.height()),
               SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}

int DraggedTabView::ScaleValue(int value) {
  return attached_ ? value : static_cast<int>(value * kScalingFactor);
}

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

#include "chrome/browser/views/tabs/dragged_tab_view.h"

#include "chrome/common/gfx/chrome_canvas.h"
#include "chrome/browser/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/views/tabs/hwnd_photobooth.h"
#include "chrome/browser/views/tabs/tab_renderer.h"
#include "chrome/views/container_win.h"
#include "skia/include/SkShader.h"

const int kTransparentAlpha = 200;
const int kOpaqueAlpha = 255;
const int kDragFrameBorderSize = 2;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
static const SkColor kDraggedTabBorderColor = SkColorSetRGB(103, 129, 162);

////////////////////////////////////////////////////////////////////////////////
// DraggedTabView, public:

DraggedTabView::DraggedTabView(TabContents* datasource,
                               const gfx::Point& mouse_tab_offset,
                               const gfx::Size& contents_size)
    : container_(NULL),
      renderer_(new TabRenderer),
      attached_(false),
      mouse_tab_offset_(mouse_tab_offset),
      attached_tab_size_(TabRenderer::GetMinimumSelectedSize()),
      photobooth_(NULL),
      contents_size_(contents_size),
      close_animation_(this) {
  SetParentOwned(false);

  renderer_->UpdateData(datasource);

  container_.reset(new views::ContainerWin);
  container_->set_delete_on_destroy(false);
  container_->set_window_style(WS_POPUP);
  container_->set_window_ex_style(
    WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW);
  container_->set_can_update_layered_window(false);
  container_->Init(NULL, gfx::Rect(0, 0, 0, 0), false);
  container_->SetContentsView(this);
}

DraggedTabView::~DraggedTabView() {
  if (close_animation_.IsAnimating())
    close_animation_.Stop();
  GetParent()->RemoveChildView(this);
  container_->CloseNow();
}

void DraggedTabView::MoveTo(const gfx::Point& screen_point) {
  if (!container_->IsVisible())
    container_->ShowWindow(SW_SHOWNOACTIVATE);

  int x;
  if (UILayoutIsRightToLeft() && !attached_) {
    // On RTL locales, a dragged tab (when it is not attached to a tab strip)
    // is rendered using a right-to-left orientation so we should calculate the
    // window position differently.
    gfx::Size ps = GetPreferredSize();
    x = screen_point.x() - ScaleValue(ps.width()) + mouse_tab_offset_.x() +
        ScaleValue(
            renderer_->MirroredXCoordinateInsideView(mouse_tab_offset_.x()));
  } else {
    x = screen_point.x() + mouse_tab_offset_.x() -
        ScaleValue(mouse_tab_offset_.x());
  }
  int y = screen_point.y() + mouse_tab_offset_.y() -
      ScaleValue(mouse_tab_offset_.y());

  container_->SetWindowPos(NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}

void DraggedTabView::Attach(int selected_width) {
  attached_ = true;
  photobooth_ = NULL;
  attached_tab_size_.set_width(selected_width);
  container_->SetLayeredAlpha(kOpaqueAlpha);
  ResizeContainer();
  Update();
}

void DraggedTabView::Detach(HWNDPhotobooth* photobooth) {
  attached_ = false;
  photobooth_ = photobooth;
  container_->SetLayeredAlpha(kTransparentAlpha);
  ResizeContainer();
  Update();
}

void DraggedTabView::Update() {
  container_->set_can_update_layered_window(true);
  SchedulePaint();
  container_->PaintNow(gfx::Rect());
  container_->set_can_update_layered_window(false);
}

void DraggedTabView::AnimateToBounds(const gfx::Rect& bounds,
                                     Callback0::Type* callback) {
  animation_callback_.reset(callback);

  RECT wr;
  GetWindowRect(GetContainer()->GetHWND(), &wr);
  animation_start_bounds_ = wr;
  animation_end_bounds_ = bounds;

  close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
  close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
  if (!close_animation_.IsShowing()) {
    close_animation_.Reset();
    close_animation_.Show();
  }
}

///////////////////////////////////////////////////////////////////////////////
// DraggedTabView, AnimationDelegate implementation:

void DraggedTabView::AnimationProgressed(const Animation* animation) {
  int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
  int x = animation_start_bounds_.x() +
      static_cast<int>(delta_x * animation->GetCurrentValue());
  int y = animation_end_bounds_.y();
  container_->SetWindowPos(NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}

void DraggedTabView::AnimationEnded(const Animation* animation) {
  animation_callback_->Run();
}

void DraggedTabView::AnimationCanceled(const Animation* animation) {
  AnimationEnded(animation);
}

///////////////////////////////////////////////////////////////////////////////
// DraggedTabView, views::View overrides:

void DraggedTabView::Paint(ChromeCanvas* canvas) {
  if (attached_) {
    PaintAttachedTab(canvas);
  } else {
    PaintDetachedView(canvas);
  }
}

void DraggedTabView::Layout() {
  if (attached_) {
    gfx::Size prefsize = GetPreferredSize();
    renderer_->SetBounds(0, 0, prefsize.width(), prefsize.height());
  } else {
    int left = 0;
    if (UILayoutIsRightToLeft())
      left = GetPreferredSize().width() - attached_tab_size_.width();
    renderer_->SetBounds(left, 0, left + attached_tab_size_.width(),
                         attached_tab_size_.height());
  }
}

gfx::Size DraggedTabView::GetPreferredSize() {
  if (attached_)
    return attached_tab_size_;

  int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
      kTwiceDragFrameBorderSize;
  int height = attached_tab_size_.height() + kDragFrameBorderSize +
      contents_size_.height();
  return gfx::Size(width, height);
}

////////////////////////////////////////////////////////////////////////////////
// DraggedTabView, private:

void DraggedTabView::PaintAttachedTab(ChromeCanvas* canvas) {
  renderer_->ProcessPaint(canvas);
}

void DraggedTabView::PaintDetachedView(ChromeCanvas* canvas) {
  gfx::Size ps = GetPreferredSize();
  ChromeCanvas scale_canvas(ps.width(), ps.height(), false);
  SkBitmap& bitmap_device = const_cast<SkBitmap&>(
      scale_canvas.getTopPlatformDevice().accessBitmap(true));
  bitmap_device.eraseARGB(0, 0, 0, 0);

  scale_canvas.FillRectInt(kDraggedTabBorderColor, 0,
      attached_tab_size_.height() - kDragFrameBorderSize,
      ps.width(), ps.height() - attached_tab_size_.height());
  int image_x = kDragFrameBorderSize;
  int image_y = attached_tab_size_.height();
  int image_w = ps.width() - kTwiceDragFrameBorderSize;
  int image_h =
      ps.height() - kTwiceDragFrameBorderSize - attached_tab_size_.height();
  scale_canvas.FillRectInt(SK_ColorBLACK, image_x, image_y, image_w, image_h);
  photobooth_->PaintScreenshotIntoCanvas(
      &scale_canvas,
      gfx::Rect(image_x, image_y, image_w, image_h));
  renderer_->ProcessPaint(&scale_canvas);

  SkIRect subset;
  subset.set(0, 0, ps.width(), ps.height());
  SkBitmap mipmap = scale_canvas.ExtractBitmap();
  mipmap.buildMipMap(true);

  SkShader* bitmap_shader =
      SkShader::CreateBitmapShader(mipmap, SkShader::kClamp_TileMode,
                                   SkShader::kClamp_TileMode);

  SkMatrix shader_scale;
  shader_scale.setScale(kScalingFactor, kScalingFactor);
  bitmap_shader->setLocalMatrix(shader_scale);

  SkPaint paint;
  paint.setShader(bitmap_shader);
  paint.setAntiAlias(true);
  bitmap_shader->unref();

  SkRect rc;
  rc.fLeft = 0;
  rc.fTop = 0;
  rc.fRight = SkIntToScalar(ps.width());
  rc.fBottom = SkIntToScalar(ps.height());
  canvas->drawRect(rc, paint);
}

void DraggedTabView::ResizeContainer() {
  gfx::Size ps = GetPreferredSize();
  SetWindowPos(container_->GetHWND(), HWND_TOPMOST, 0, 0,
               ScaleValue(ps.width()), ScaleValue(ps.height()),
               SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}

int DraggedTabView::ScaleValue(int value) {
  return attached_ ? value : static_cast<int>(value * kScalingFactor);
}

<|endoftext|>


<commit_before><commit_msg>fix 500+ new assert failures on export<commit_after><|endoftext|>


<commit_before>// Regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=183

// RUN: %clangxx_asan -O2 %s -o %t
// RUN: not %run %t 12 2>&1 | FileCheck %s
// RUN: not %run %t 100 2>&1 | FileCheck %s
// RUN: not %run %t 10000 2>&1 | FileCheck %s

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "main\n");
  int *x = new int[5];
  memset(x, 0, sizeof(x[0]) * 5);
  int index = atoi(argv[1]);
  int res = x[index];
  // CHECK: main
  // CHECK-NOT: CHECK failed
  delete[] x;
  return res ? res : 1;
}
<commit_msg>Fix a flaky heap-overflow-large.cc test<commit_after>// Regression test for
// https://code.google.com/p/address-sanitizer/issues/detail?id=183

// RUN: %clangxx_asan -O2 %s -o %t
// RUN: not %run %t 12 2>&1 | FileCheck %s
// RUN: not %run %t 100 2>&1 | FileCheck %s
// RUN: not %run %t 10000 2>&1 | FileCheck %s

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "main\n");
  int *x = new int[5];
  memset(x, 0, sizeof(x[0]) * 5);
  int index = atoi(argv[1]);
  unsigned res = x[index];
  // CHECK: main
  // CHECK-NOT: CHECK failed
  delete[] x;
  return (res % 10) + 1;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vpp/imageNd.hh>

int main()
{
  using vpp::imageNd;
  using vpp::vint2;

  int dims[] = {100, 200};
  vpp::imageNd<int, 2> img(dims);

  assert(img.domain().size(0) == dims[0]);
  assert(img.domain().size(1) == dims[1]);

  assert(img.data() == img.begin());

  assert(img.coords_to_index(vpp::vint2::Ones()) == dims[1] + 1);

  for (int r = 0; r < img.domain().size(0); r++)
    for (int c = 0; c < img.domain().size(1); c++)
    {
      assert(img.coords_to_index(vint2(r, c)) == (r * dims[1] + c));
    }

  for (int r = 0; r < img.domain().size(0); r++)
    for (int c = 0; c < img.domain().size(1); c++)
    {
      img(vpp::vint2(r, c)) = r * c;
    }

  for (int r = 0; r < img.domain().size(0) - 1; r++)
    for (int c = 0; c < img.domain().size(1) - 1; c++)
    {
      assert(img(vpp::vint2(r, c)) == r * c);
    }

}
<commit_msg>Cleanup imageNd test.<commit_after>#include <iostream>
#include <vpp/imageNd.hh>

int main()
{
  using vpp::imageNd;
  using vpp::vint2;

  int dims[] = {100, 200};
  imageNd<int, 2> img(dims);

  assert(img.domain().size(0) == dims[0]);
  assert(img.domain().size(1) == dims[1]);

  assert(img.data() == img.begin());

  assert(img.coords_to_index(vpp::vint2::Ones()) == dims[1] + 1);

  for (int r = 0; r < img.domain().size(0); r++)
    for (int c = 0; c < img.domain().size(1); c++)
    {
      assert(img.coords_to_index(vint2(r, c)) == (r * dims[1] + c));
    }

  for (int r = 0; r < img.domain().size(0); r++)
    for (int c = 0; c < img.domain().size(1); c++)
    {
      img(vint2(r, c)) = r * c;
    }

  for (int r = 0; r < img.domain().size(0) - 1; r++)
    for (int c = 0; c < img.domain().size(1) - 1; c++)
    {
      assert(img(vint2(r, c)) == r * c);
    }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: inspectorhelpwindow.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INSPECTORHELPWINDOW_HXX
#define INSPECTORHELPWINDOW_HXX

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <vcl/fixed.hxx>
#include <svtools/svmedit.hxx>

//........................................................................
namespace pcr
{
//........................................................................

    //====================================================================
    //= InspectorHelpWindow
    //====================================================================
    class InspectorHelpWindow : public Window
    {
    private:
        FixedLine       m_aSeparator;
        MultiLineEdit   m_aHelpText;

        sal_Int32       m_nMinLines;
        sal_Int32       m_nMaxLines;

    public:
        InspectorHelpWindow( Window* _pParent );

        virtual void    SetText( const XubString& rStr );

        void            SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );
        long            GetMinimalHeightPixel();
        long            GetOptimalHeightPixel();
        long            GetMaximalHeightPixel();

    protected:
        // Window overridables
        virtual void    Resize();

    private:
        long            impl_getMinimalTextWindowHeight();
        long            impl_getMaximalTextWindowHeight();
        long            impl_getHelpTextBorderHeight();
        long            impl_getSpaceAboveTextWindow();
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // HELPWINDOW_HXX

<commit_msg>INTEGRATION: CWS mba30patches01 (1.2.214); FILE MERGED 2008/04/23 10:49:45 mba 1.2.214.2: RESYNC: (1.2-1.3); FILE MERGED 2008/03/18 15:40:59 mba 1.2.214.1: #i86365#: remove unused code<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: inspectorhelpwindow.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INSPECTORHELPWINDOW_HXX
#define INSPECTORHELPWINDOW_HXX

/** === begin UNO includes === **/
/** === end UNO includes === **/

#include <vcl/fixed.hxx>
#include <svtools/svmedit.hxx>

//........................................................................
namespace pcr
{
//........................................................................

    //====================================================================
    //= InspectorHelpWindow
    //====================================================================
    class InspectorHelpWindow : public Window
    {
    private:
        FixedLine       m_aSeparator;
        MultiLineEdit   m_aHelpText;

        sal_Int32       m_nMinLines;
        sal_Int32       m_nMaxLines;

    public:
        InspectorHelpWindow( Window* _pParent );

        virtual void    SetText( const XubString& rStr );

        void            SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );
        long            GetMinimalHeightPixel();
        long            GetOptimalHeightPixel();

    protected:
        // Window overridables
        virtual void    Resize();

    private:
        long            impl_getMinimalTextWindowHeight();
        long            impl_getMaximalTextWindowHeight();
        long            impl_getHelpTextBorderHeight();
        long            impl_getSpaceAboveTextWindow();
    };

//........................................................................
} // namespace pcr
//........................................................................

#endif // HELPWINDOW_HXX

<|endoftext|>


<commit_before>// Given an array of integers, every element appears twice except for one. Find
// that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement
// it without using extra memory?

class Solution {
  public:
    int singleNumber(vector<int> &nums) {
        int result = 0;
        for (auto &n : nums)
            result ^= n;
        return result;
    }
};<commit_msg>comment 136<commit_after>// Given an array of integers, every element appears twice except for one. Find
// that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement
// it without using extra memory?

class Solution {
  public:
    int singleNumber(vector<int> &nums) {
        int result = 0;
        // if this is not allowed, just use nums[0]
        for (auto &n : nums)
            result ^= n;
        return result;
    }
};<|endoftext|>


<commit_before>#pragma once
#include "util.cpp"

#include <set>
#include <tuple>

long id(int r, int c, int a) {
    return r + 10000 * c + 1000000 * a;
}

bool inbounds(int r, int c, Input& input) {
    return (0 <= r && r < input.r && 0 <= c && c < input.c);
}

int tr_r(int r, int c, int a, Input& input) {
    // cerr << "translating " << r << " " << c << " " << a << endl;
    return r + input.movement_r[r][c][a];
}
int tr_c(int r, int c, int a, Input& input) {
    // cerr << "translating " << r << " " << c << " " << a << endl;
    return (c + input.movement_c[r][c][a] + input.c) % input.c;
}

void consider(Input& input, int r, int c, int a, int l, int rn, int cn, int an, queue<int>& q_r, queue<int>& q_c, queue<int>& q_a, queue<int>& q_l, map<long,int>& prevr, map<long,int>& prevc, map<long,int>& preva) {
    if (inbounds(rn, cn, input)) {
        q_r.push(rn);
        q_c.push(cn);
        q_a.push(an);
        q_l.push(l - 1);
        long i2 = id(rn, cn, an);
        prevr[i2] = r;
        prevc[i2] = c;
        preva[i2] = a;
    }
}

bool cyclefrom(Input& input, int r, int c, int a, int maxlen, vector<int>& cycle_rs, vector<int>& cycle_cs, vector<int>& cycle_as) {

    cerr << "Considering " << r << " " << c << " " << a << endl;

    queue<int> q_r, q_c, q_a, q_l;

    q_r.push(r);
    q_c.push(c);
    q_a.push(a);
    q_l.push(maxlen);

    set<long> seen;

    while(!q_r.empty()) {

        int r = q_r.front();
        int c = q_c.front();
        int a = q_a.front();
        int l = q_l.front();
        q_r.pop();
        q_c.pop();
        q_a.pop();
        q_l.pop();

        map<long, int> prevr, prevc, preva;

        // cerr << "p(" << r << "," << c << "," << a << "," << l << ")" << endl;

        long i = id(r, c, a);
        if (seen.find(i) == seen.end()) {
            seen.insert(i);
            // cerr << "seen: ";
            // for (int s : seen) {
            //     cerr << s << " ";
            // }
            // cerr << endl;
        } else {
            cerr << "cycle of len " << (maxlen - l) << endl;
            // Compute cycle

            break;
        }

        if (l <= 0) {
            continue;
        }

        // reachable:
        if (a > 1) {
            int rn = tr_r(r, c, a - 1, input);
            int cn = tr_c(r, c, a - 1, input);
            int an = a - 1;
            consider(input, r, c, a, l, rn, cn, an, q_r, q_c, q_a, q_l, prevr, prevc, preva);
        }
        if (a < input.a) {
            int rn = tr_r(r, c, a + 1, input);
            int cn = tr_c(r, c, a + 1, input);
            int an = a + 1;
            consider(input, r, c, a, l, rn, cn, an, q_r, q_c, q_a, q_l, prevr, prevc, preva);
        }
        int rn = tr_r(r, c, a, input);
        int cn = tr_c(r, c, a, input);
        consider(input, r, c, a, l, rn, cn, a, q_r, q_c, q_a, q_l, prevr, prevc, preva);
    }

    return false;
}

void cycling(Input& input) {
	//TODO fill me
    cerr << "start emi" << endl;

    int len = 15;

    // graph

    for (auto& c : input.clusters) {
        vector<int> rs, cs, as;
        cyclefrom(input, c.center_r, c.center_c, 1, 15, rs, cs, as);
    }
    cerr << "end Emi" << endl;

}
<commit_msg>cycles<commit_after>#pragma once
#include "util.cpp"

#include <set>
#include <tuple>

long id(int r, int c, int a) {
    return r + 10000 * c + 1000000 * a;
}

bool inbounds(int r, int c, Input& input) {
    return (0 <= r && r < input.r && 0 <= c && c < input.c);
}

int tr_r(int r, int c, int a, Input& input) {
    // cerr << "translating " << r << " " << c << " " << a << endl;
    return r + input.movement_r[r][c][a];
}
int tr_c(int r, int c, int a, Input& input) {
    // cerr << "translating " << r << " " << c << " " << a << endl;
    return (c + input.movement_c[r][c][a] + input.c) % input.c;
}

void consider(Input& input, int r, int c, int a, int l, int rn, int cn, int an, queue<int>& q_r, queue<int>& q_c, queue<int>& q_a, queue<int>& q_l, map<long,int>& prevr, map<long,int>& prevc, map<long,int>& preva) {
    if (inbounds(rn, cn, input)) {
        q_r.push(rn);
        q_c.push(cn);
        q_a.push(an);
        q_l.push(l - 1);
        long i2 = id(rn, cn, an);
        prevr[i2] = r;
        prevc[i2] = c;
        preva[i2] = a;
    }
}

bool cyclefrom(Input& input, int r, int c, int a, int maxlen, vector<int>& tail_rs, vector<int>& tail_cs, vector<int>& tail_as, vector<int>& cycle_rs, vector<int>& cycle_cs, vector<int>& cycle_as) {

    cerr << "Considering " << r << " " << c << " " << a << endl;

    queue<int> q_r, q_c, q_a, q_l;

    q_r.push(r);
    q_c.push(c);
    q_a.push(a);
    q_l.push(maxlen);

    set<long> seen;

    while(!q_r.empty()) {

        int r = q_r.front();
        int c = q_c.front();
        int a = q_a.front();
        int l = q_l.front();
        q_r.pop();
        q_c.pop();
        q_a.pop();
        q_l.pop();

        map<long, int> prevr, prevc, preva;

        // cerr << "p(" << r << "," << c << "," << a << "," << l << ")" << endl;

        long i = id(r, c, a);
        if (seen.find(i) == seen.end()) {
            seen.insert(i);
            // cerr << "seen: ";
            // for (int s : seen) {
            //     cerr << s << " ";
            // }
            // cerr << endl;
        } else {
            cerr << "cycle of len " << (maxlen - l) << endl;
            // Compute cycle
            break;
        }

        if (l <= 0) {
            continue;
        }

        // reachable:
        if (a > 1) {
            int rn = tr_r(r, c, a - 1, input);
            int cn = tr_c(r, c, a - 1, input);
            int an = a - 1;
            consider(input, r, c, a, l, rn, cn, an, q_r, q_c, q_a, q_l, prevr, prevc, preva);
        }
        if (a < input.a) {
            int rn = tr_r(r, c, a + 1, input);
            int cn = tr_c(r, c, a + 1, input);
            int an = a + 1;
            consider(input, r, c, a, l, rn, cn, an, q_r, q_c, q_a, q_l, prevr, prevc, preva);
        }
        int rn = tr_r(r, c, a, input);
        int cn = tr_c(r, c, a, input);
        consider(input, r, c, a, l, rn, cn, a, q_r, q_c, q_a, q_l, prevr, prevc, preva);
    }

    return false;
}

void cycling(Input& input) {
	//TODO fill me
    cerr << "start emi" << endl;

    int len = 15;

    // graph

    for (auto& c : input.clusters) {
        vector<int> rs, cs, as;
        cyclefrom(input, c.center_r, c.center_c, 1, 15, rs, cs, as);
    }
    cerr << "end Emi" << endl;

}
<|endoftext|>