<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/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
    "files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif  // defined(OS_LINUX)

// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
  RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
  RunTest("testCachedResourceMimeType", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif  // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
  RunTest("testCompletionOnPause", kCompletionOnPause);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

}  // namespace
<commit_msg>Disable TestEnableResourcesTab.<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/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
    "files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Fails after WebKit roll 69808:70011, http://crbug.com/59727.
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestEnableResourcesTab DISABLED_TestEnableResourcesTab
#else
#define MAYBE_TestEnableResourcesTab TestEnableResourcesTab
#endif  // defined(OS_LINUX) || defined(OS_WIN)

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif  // defined(OS_LINUX)

// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
  RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
  RunTest("testCachedResourceMimeType", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif  // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
  RunTest("testCompletionOnPause", kCompletionOnPause);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

}  // namespace
<|endoftext|>


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

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

#include <string>

#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "third_party/cros/chromeos_cros_api.h"
#include "third_party/cros/chromeos_input_method_ui.h"

namespace events {

const char kOnUpdateAuxiliaryText[] =
    "experimental.inputUI.onUpdateAuxiliaryText";
const char kOnUpdateLookupTable[] = "experimental.inputUI.onUpdateLookupTable";
const char kOnSetCursorLocation[] = "experimental.inputUI.onSetCursorLocation";

}  // namespace events

class InputUiController {
 public:
  explicit InputUiController(ExtensionInputUiEventRouter* router);
  ~InputUiController();

  void CandidateClicked(int index, int button, int flags);
  void CursorUp();
  void CursorDown();
  void PageUp();
  void PageDown();

 private:
  // The function is called when |HideAuxiliaryText| signal is received in
  // libcros. |ui_controller| is a void pointer to this object.
  static void OnHideAuxiliaryText(void* ui_controller);

  // The function is called when |HideLookupTable| signal is received in
  // libcros. |ui_controller| is a void pointer to this object.
  static void OnHideLookupTable(void* ui_controller);

  // The function is called when |SetCursorLocation| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnSetCursorLocation(void* ui_controller,
                                  int x,
                                  int y,
                                  int width,
                                  int height);

  // The function is called when |UpdateAuxiliaryText| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnUpdateAuxiliaryText(void* ui_controller,
                                    const std::string& utf8_text,
                                    bool visible);

  // The function is called when |UpdateLookupTable| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnUpdateLookupTable(void* ui_controller,
      const chromeos::InputMethodLookupTable& lookup_table);

  // This function is called by libcros when ibus connects or disconnects.
  // |ui_controller| is a void pointer to this object.
  static void OnConnectionChange(void* ui_controller, bool connected);

  ExtensionInputUiEventRouter* router_;
  chromeos::InputMethodUiStatusConnection* ui_status_connection_;

  DISALLOW_COPY_AND_ASSIGN(InputUiController);
};

InputUiController::InputUiController(
    ExtensionInputUiEventRouter* router) :
  router_(router),
  ui_status_connection_(NULL) {
  std::string error;
  chromeos::LoadLibcros(NULL, error);

  chromeos::InputMethodUiStatusMonitorFunctions functions;
  functions.hide_auxiliary_text =
      &InputUiController::OnHideAuxiliaryText;
  functions.hide_lookup_table =
      &InputUiController::OnHideLookupTable;
  functions.set_cursor_location =
      &InputUiController::OnSetCursorLocation;
  functions.update_auxiliary_text =
      &InputUiController::OnUpdateAuxiliaryText;
  functions.update_lookup_table =
      &InputUiController::OnUpdateLookupTable;
  ui_status_connection_ = chromeos::MonitorInputMethodUiStatus(functions, this);

  if (!ui_status_connection_)
    LOG(ERROR) << "chromeos::MonitorInputMethodUiStatus() failed!";
}

InputUiController::~InputUiController() {
  chromeos::DisconnectInputMethodUiStatus(ui_status_connection_);
}

void InputUiController::CandidateClicked(
    int index, int button, int flags) {
  chromeos::NotifyCandidateClicked(ui_status_connection_, index, button, flags);
}

void InputUiController::CursorUp() {
  chromeos::NotifyCursorUp(ui_status_connection_);
}

void InputUiController::CursorDown() {
  chromeos::NotifyCursorDown(ui_status_connection_);
}

void InputUiController::PageUp() {
  chromeos::NotifyPageUp(ui_status_connection_);
}

void InputUiController::PageDown() {
  chromeos::NotifyPageDown(ui_status_connection_);
}

void InputUiController::OnHideAuxiliaryText(
    void* ui_controller) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnHideAuxiliaryText();
}

void InputUiController::OnHideLookupTable(
    void* ui_controller) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnHideLookupTable();
}

void InputUiController::OnSetCursorLocation(
    void* ui_controller,
    int x, int y, int width, int height) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnSetCursorLocation(x, y, width, height);
}

void InputUiController::OnUpdateAuxiliaryText(
    void* ui_controller,
    const std::string& utf8_text,
    bool visible) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  if (!visible) {
    self->router_->OnHideAuxiliaryText();
  } else {
    self->router_->OnUpdateAuxiliaryText(utf8_text);
  }
}

void InputUiController::OnUpdateLookupTable(
    void* ui_controller,
    const chromeos::InputMethodLookupTable& lookup_table) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
    self->router_->OnUpdateLookupTable(lookup_table);
}

ExtensionInputUiEventRouter*
ExtensionInputUiEventRouter::GetInstance() {
  return Singleton<ExtensionInputUiEventRouter>::get();
}

ExtensionInputUiEventRouter::ExtensionInputUiEventRouter()
  : profile_(NULL),
    ui_controller_(NULL) {
}

ExtensionInputUiEventRouter::~ExtensionInputUiEventRouter() {
}

void ExtensionInputUiEventRouter::Init() {
  if (ui_controller_.get() == NULL) {
    ui_controller_.reset(new InputUiController(this));
  }
}

void ExtensionInputUiEventRouter::Register(
    Profile* profile, const std::string& extension_id) {
  profile_ = profile;
  extension_id_ = extension_id;
}

void ExtensionInputUiEventRouter::CandidateClicked(Profile* profile,
    const std::string& extension_id, int index, int button) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CandidateClicked(index, button, 0);
}

void ExtensionInputUiEventRouter::CursorUp(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CursorUp();
}

void ExtensionInputUiEventRouter::CursorDown(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CursorDown();
}

void ExtensionInputUiEventRouter::PageUp(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->PageUp();
}

void ExtensionInputUiEventRouter::PageDown(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->PageDown();
}

void ExtensionInputUiEventRouter::OnHideAuxiliaryText() {
  OnUpdateAuxiliaryText("");
}

void ExtensionInputUiEventRouter::OnHideLookupTable() {
  if (profile_ == NULL || extension_id_.empty())
    return;

  DictionaryValue* dict = new DictionaryValue();
  dict->SetBoolean("visible", false);

  ListValue *candidates = new ListValue();
  dict->Set("candidates", candidates);

  ListValue args;
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnSetCursorLocation(
    int x, int y, int width, int height) {

  if (profile_ == NULL || extension_id_.empty())
    return;

  ListValue args;
  args.Append(Value::CreateIntegerValue(x));
  args.Append(Value::CreateIntegerValue(y));
  args.Append(Value::CreateIntegerValue(width));
  args.Append(Value::CreateIntegerValue(height));

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnSetCursorLocation, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnUpdateAuxiliaryText(
    const std::string& utf8_text) {
  if (profile_ == NULL || extension_id_.empty())
    return;

  ListValue args;
  args.Append(Value::CreateStringValue(utf8_text));

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateAuxiliaryText, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnUpdateLookupTable(
    const chromeos::InputMethodLookupTable& lookup_table) {
  if (profile_ == NULL || extension_id_.empty())
    return;

  DictionaryValue* dict = new DictionaryValue();
  dict->SetBoolean("visible", lookup_table.visible);

  if (lookup_table.visible) {
  }

  ListValue *candidates = new ListValue();
  for (size_t i = 0; i < lookup_table.candidates.size(); i++) {
    candidates->Append(Value::CreateStringValue(lookup_table.candidates[i]));
  }

  dict->Set("candidates", candidates);

  ListValue args;
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}

bool RegisterInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->Register(
      profile(), extension_id());
  return true;
}

bool CandidateClickedInputUiFunction::RunImpl() {
  int index = 0;
  int button = 0;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &index));
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &button));

  ExtensionInputUiEventRouter::GetInstance()->CandidateClicked(
      profile(), extension_id(), index, button);

  return true;
}

bool CursorUpInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->CursorUp(
      profile(), extension_id());
  return true;
}

bool CursorDownInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->CursorDown(
      profile(), extension_id());
  return true;
}

bool PageUpInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->PageUp(
      profile(), extension_id());
  return true;
}

bool PageDownInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->PageDown(
      profile(), extension_id());
  return true;
}

<commit_msg>Use chromeos::CrosLibrary::Get()->EnsureLoaded() to replace chromeos::LoadLibcros()<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

#include <string>

#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "third_party/cros/chromeos_cros_api.h"
#include "third_party/cros/chromeos_input_method_ui.h"

namespace events {

const char kOnUpdateAuxiliaryText[] =
    "experimental.inputUI.onUpdateAuxiliaryText";
const char kOnUpdateLookupTable[] = "experimental.inputUI.onUpdateLookupTable";
const char kOnSetCursorLocation[] = "experimental.inputUI.onSetCursorLocation";

}  // namespace events

class InputUiController {
 public:
  explicit InputUiController(ExtensionInputUiEventRouter* router);
  ~InputUiController();

  void CandidateClicked(int index, int button, int flags);
  void CursorUp();
  void CursorDown();
  void PageUp();
  void PageDown();

 private:
  // The function is called when |HideAuxiliaryText| signal is received in
  // libcros. |ui_controller| is a void pointer to this object.
  static void OnHideAuxiliaryText(void* ui_controller);

  // The function is called when |HideLookupTable| signal is received in
  // libcros. |ui_controller| is a void pointer to this object.
  static void OnHideLookupTable(void* ui_controller);

  // The function is called when |SetCursorLocation| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnSetCursorLocation(void* ui_controller,
                                  int x,
                                  int y,
                                  int width,
                                  int height);

  // The function is called when |UpdateAuxiliaryText| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnUpdateAuxiliaryText(void* ui_controller,
                                    const std::string& utf8_text,
                                    bool visible);

  // The function is called when |UpdateLookupTable| signal is received
  // in libcros. |ui_controller| is a void pointer to this object.
  static void OnUpdateLookupTable(void* ui_controller,
      const chromeos::InputMethodLookupTable& lookup_table);

  // This function is called by libcros when ibus connects or disconnects.
  // |ui_controller| is a void pointer to this object.
  static void OnConnectionChange(void* ui_controller, bool connected);

  ExtensionInputUiEventRouter* router_;
  chromeos::InputMethodUiStatusConnection* ui_status_connection_;

  DISALLOW_COPY_AND_ASSIGN(InputUiController);
};

InputUiController::InputUiController(
    ExtensionInputUiEventRouter* router) :
  router_(router),
  ui_status_connection_(NULL) {
  if (!chromeos::CrosLibrary::Get()->EnsureLoaded())
    return;

  chromeos::InputMethodUiStatusMonitorFunctions functions;
  functions.hide_auxiliary_text =
      &InputUiController::OnHideAuxiliaryText;
  functions.hide_lookup_table =
      &InputUiController::OnHideLookupTable;
  functions.set_cursor_location =
      &InputUiController::OnSetCursorLocation;
  functions.update_auxiliary_text =
      &InputUiController::OnUpdateAuxiliaryText;
  functions.update_lookup_table =
      &InputUiController::OnUpdateLookupTable;
  ui_status_connection_ = chromeos::MonitorInputMethodUiStatus(functions, this);

  if (!ui_status_connection_)
    LOG(ERROR) << "chromeos::MonitorInputMethodUiStatus() failed!";
}

InputUiController::~InputUiController() {
  if (ui_status_connection_)
    chromeos::DisconnectInputMethodUiStatus(ui_status_connection_);
}

void InputUiController::CandidateClicked(
    int index, int button, int flags) {
  chromeos::NotifyCandidateClicked(ui_status_connection_, index, button, flags);
}

void InputUiController::CursorUp() {
  chromeos::NotifyCursorUp(ui_status_connection_);
}

void InputUiController::CursorDown() {
  chromeos::NotifyCursorDown(ui_status_connection_);
}

void InputUiController::PageUp() {
  chromeos::NotifyPageUp(ui_status_connection_);
}

void InputUiController::PageDown() {
  chromeos::NotifyPageDown(ui_status_connection_);
}

void InputUiController::OnHideAuxiliaryText(
    void* ui_controller) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnHideAuxiliaryText();
}

void InputUiController::OnHideLookupTable(
    void* ui_controller) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnHideLookupTable();
}

void InputUiController::OnSetCursorLocation(
    void* ui_controller,
    int x, int y, int width, int height) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  self->router_->OnSetCursorLocation(x, y, width, height);
}

void InputUiController::OnUpdateAuxiliaryText(
    void* ui_controller,
    const std::string& utf8_text,
    bool visible) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
  if (!visible) {
    self->router_->OnHideAuxiliaryText();
  } else {
    self->router_->OnUpdateAuxiliaryText(utf8_text);
  }
}

void InputUiController::OnUpdateLookupTable(
    void* ui_controller,
    const chromeos::InputMethodLookupTable& lookup_table) {
  InputUiController *self = static_cast<InputUiController*>(ui_controller);
    self->router_->OnUpdateLookupTable(lookup_table);
}

ExtensionInputUiEventRouter*
ExtensionInputUiEventRouter::GetInstance() {
  return Singleton<ExtensionInputUiEventRouter>::get();
}

ExtensionInputUiEventRouter::ExtensionInputUiEventRouter()
  : profile_(NULL),
    ui_controller_(NULL) {
}

ExtensionInputUiEventRouter::~ExtensionInputUiEventRouter() {
}

void ExtensionInputUiEventRouter::Init() {
  if (ui_controller_.get() == NULL) {
    ui_controller_.reset(new InputUiController(this));
  }
}

void ExtensionInputUiEventRouter::Register(
    Profile* profile, const std::string& extension_id) {
  profile_ = profile;
  extension_id_ = extension_id;
}

void ExtensionInputUiEventRouter::CandidateClicked(Profile* profile,
    const std::string& extension_id, int index, int button) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CandidateClicked(index, button, 0);
}

void ExtensionInputUiEventRouter::CursorUp(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CursorUp();
}

void ExtensionInputUiEventRouter::CursorDown(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->CursorDown();
}

void ExtensionInputUiEventRouter::PageUp(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->PageUp();
}

void ExtensionInputUiEventRouter::PageDown(Profile* profile,
    const std::string& extension_id) {
    if (profile_ != profile || extension_id_ != extension_id) {
      DLOG(WARNING) << "called from unregistered extension";
    }
    ui_controller_->PageDown();
}

void ExtensionInputUiEventRouter::OnHideAuxiliaryText() {
  OnUpdateAuxiliaryText("");
}

void ExtensionInputUiEventRouter::OnHideLookupTable() {
  if (profile_ == NULL || extension_id_.empty())
    return;

  DictionaryValue* dict = new DictionaryValue();
  dict->SetBoolean("visible", false);

  ListValue *candidates = new ListValue();
  dict->Set("candidates", candidates);

  ListValue args;
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnSetCursorLocation(
    int x, int y, int width, int height) {

  if (profile_ == NULL || extension_id_.empty())
    return;

  ListValue args;
  args.Append(Value::CreateIntegerValue(x));
  args.Append(Value::CreateIntegerValue(y));
  args.Append(Value::CreateIntegerValue(width));
  args.Append(Value::CreateIntegerValue(height));

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnSetCursorLocation, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnUpdateAuxiliaryText(
    const std::string& utf8_text) {
  if (profile_ == NULL || extension_id_.empty())
    return;

  ListValue args;
  args.Append(Value::CreateStringValue(utf8_text));

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateAuxiliaryText, json_args, profile_, GURL());
}

void ExtensionInputUiEventRouter::OnUpdateLookupTable(
    const chromeos::InputMethodLookupTable& lookup_table) {
  if (profile_ == NULL || extension_id_.empty())
    return;

  DictionaryValue* dict = new DictionaryValue();
  dict->SetBoolean("visible", lookup_table.visible);

  if (lookup_table.visible) {
  }

  ListValue *candidates = new ListValue();
  for (size_t i = 0; i < lookup_table.candidates.size(); i++) {
    candidates->Append(Value::CreateStringValue(lookup_table.candidates[i]));
  }

  dict->Set("candidates", candidates);

  ListValue args;
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  profile_->GetExtensionEventRouter()->DispatchEventToExtension(
    extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}

bool RegisterInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->Register(
      profile(), extension_id());
  return true;
}

bool CandidateClickedInputUiFunction::RunImpl() {
  int index = 0;
  int button = 0;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &index));
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &button));

  ExtensionInputUiEventRouter::GetInstance()->CandidateClicked(
      profile(), extension_id(), index, button);

  return true;
}

bool CursorUpInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->CursorUp(
      profile(), extension_id());
  return true;
}

bool CursorDownInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->CursorDown(
      profile(), extension_id());
  return true;
}

bool PageUpInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->PageUp(
      profile(), extension_id());
  return true;
}

bool PageDownInputUiFunction::RunImpl() {
  ExtensionInputUiEventRouter::GetInstance()->PageDown(
      profile(), extension_id());
  return true;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DocumentLoader.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 15:04:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

/*****************************************************************************
 *****************************************************************************
 *
 * Simple client application using the UnoUrlResolver service.
 *
 *****************************************************************************
 *****************************************************************************/
#include <stdio.h>
#include <wchar.h>

#include <cppuhelper/bootstrap.hxx>

#include <osl/file.hxx>
#include <osl/process.h>

#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <string.h>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::bridge;
using namespace com::sun::star::frame;
using namespace com::sun::star::registry;

//============================================================================
int SAL_CALL main( int argc, char **argv )
{
    OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager"));
     if (argc < 2)
    {
        printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n"
               "example: DocumentLoader  \"file:///e:/temp/test.odt\" \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\"\n");
        exit(1);
    }
     if (argc == 3)
    {
        sConnectionString = OUString::createFromAscii(argv[2]);
    }

    // Creates a simple registry service instance.
    Reference< XSimpleRegistry > xSimpleRegistry(
        ::cppu::createSimpleRegistry() );

    // Connects the registry to a persistent data source represented by an URL.
    xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM(
        "DocumentLoader.rdb") ), sal_True, sal_False );

    /* Bootstraps an initial component context with service manager upon a given
       registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)
    */
    Reference< XComponentContext > xComponentContext(
        ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) );

    /* Gets the service manager instance to be used (or null). This method has
       been added for convenience, because the service manager is a often used
       object.
    */
    Reference< XMultiComponentFactory > xMultiComponentFactoryClient(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory.
    */
    Reference< XInterface > xInterface =
        xMultiComponentFactoryClient->createInstanceWithContext(
            OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ),
            xComponentContext );

    Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY );

    // Resolves the component context from the office, on the uno URL given by argv[1].
    try
    {
        xInterface = Reference< XInterface >(
            resolver->resolve( sConnectionString ), UNO_QUERY );
    }
    catch ( Exception& e )
    {
        printf("Error: cannot establish a connection using '%s':\n       %s\n",
               OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(),
               OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr());
        exit(1);
    }

    // gets the server component context as property of the office component factory
    Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY );
    xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext;

    // gets the service manager from the office
    Reference< XMultiComponentFactory > xMultiComponentFactoryServer(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory. Important: using the office component context.
    */
    Reference < XComponentLoader > xComponentLoader(
        xMultiComponentFactoryServer->createInstanceWithContext(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ),
            xComponentContext ), UNO_QUERY );

    /* Loads a component specified by an URL into the specified new or existing
       frame.
    */
    OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getFileURLFromSystemPath( OUString::createFromAscii(argv[1]), sDocPathUrl);
    osl::FileBase::getAbsoluteFileURL( sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);

    Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL(
        sAbsoluteDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0,
        Sequence < ::com::sun::star::beans::PropertyValue >() );

    // dispose the local service manager
    Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose();

    return 0;
}
<commit_msg>INTEGRATION: CWS jsc21 (1.12.92); FILE MERGED 2008/05/21 12:55:39 jsc 1.12.92.1: #i88797# adapted to new structure<commit_after>/*************************************************************************
 *
 *  $RCSfile: DocumentLoader.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2008-07-11 14:25:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

/*****************************************************************************
 *****************************************************************************
 *
 * Simple client application using the UnoUrlResolver service.
 *
 *****************************************************************************
 *****************************************************************************/
#include <stdio.h>
#include <wchar.h>

#include <cppuhelper/bootstrap.hxx>

#include <osl/file.hxx>
#include <osl/process.h>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>

#include <string.h>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::bridge;
using namespace com::sun::star::frame;
using namespace com::sun::star::registry;

//============================================================================
int SAL_CALL main( int argc, char **argv )
{
    OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager"));
     if (argc < 2)
    {
        printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n"
               "example: DocumentLoader  \"file:///e:/temp/test.odt\" \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\"\n");
        exit(1);
    }
     if (argc == 3)
    {
        sConnectionString = OUString::createFromAscii(argv[2]);
    }

    // Creates a simple registry service instance.
    Reference< XSimpleRegistry > xSimpleRegistry(
        ::cppu::createSimpleRegistry() );

    // Connects the registry to a persistent data source represented by an URL.
    xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM(
        "DocumentLoader.rdb") ), sal_True, sal_False );

    /* Bootstraps an initial component context with service manager upon a given
       registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)
    */
    Reference< XComponentContext > xComponentContext(
        ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) );

    /* Gets the service manager instance to be used (or null). This method has
       been added for convenience, because the service manager is a often used
       object.
    */
    Reference< XMultiComponentFactory > xMultiComponentFactoryClient(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory.
    */
    Reference< XInterface > xInterface =
        xMultiComponentFactoryClient->createInstanceWithContext(
            OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ),
            xComponentContext );

    Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY );

    // Resolves the component context from the office, on the uno URL given by argv[1].
    try
    {
        xInterface = Reference< XInterface >(
            resolver->resolve( sConnectionString ), UNO_QUERY );
    }
    catch ( Exception& e )
    {
        printf("Error: cannot establish a connection using '%s':\n       %s\n",
               OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(),
               OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr());
        exit(1);
    }

    // gets the server component context as property of the office component factory
    Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY );
    xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext;

    // gets the service manager from the office
    Reference< XMultiComponentFactory > xMultiComponentFactoryServer(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory. Important: using the office component context.
    */
    Reference < XComponentLoader > xComponentLoader(
        xMultiComponentFactoryServer->createInstanceWithContext(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ),
            xComponentContext ), UNO_QUERY );

    /* Loads a component specified by an URL into the specified new or existing
       frame.
    */
    OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getFileURLFromSystemPath( OUString::createFromAscii(argv[1]), sDocPathUrl);
    osl::FileBase::getAbsoluteFileURL( sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);

    Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL(
        sAbsoluteDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0,
        Sequence < ::com::sun::star::beans::PropertyValue >() );

    // dispose the local service manager
    Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose();

    return 0;
}
<|endoftext|>


<commit_before>/****************************** Module Header ******************************\
Module Name:  Metar.hpp
Project:      Meteorology
Copyright (c) 2014 Steven Frost.

This module defines the Weather class including general meteorology methods,
meteorology-releated enumerations and type definitions for different
meteorology properties.

References:  (1) http://en.wikipedia.org/wiki/Weather

Todo:        (1) Complete type definitions
             (2) Complete enumerated list of cloud type and cover

This source is subject to the MIT License.
See http://opensource.org/licenses/MIT

All other rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

#pragma once

//-----------------------------------------------------------------------------

namespace Meteorology
{

//-----------------------------------------------------------------------------

inline double CelsiusToFahrenheit(double celsius)
{
    return celsius * 9 / 5 + 32;
}

inline double MetresToFeet(double metres)
{
    return metres / 0.3048;
}

inline double MilesToFeet(double miles)
{
    return miles * 5280;
}

inline double InhgToHpa(double inhg)
{
    return inhg * 33.8638816;
}

inline double HpaToInhg(double hpa)
{
    return hpa / 33.8638816;
}

//-----------------------------------------------------------------------------

enum class WeatherIntensity
{
    Light,
    Moderate,
    Heavy,
    InTheVicinity
};

enum class WeatherDescriptor
{
    None,
    Shallow,
    Partial,
    Patches,
    LowDrifting,
    Blowing,
    Showers,
    Thunderstorm,
    Freezing
};

enum class WeatherPhenomena
{
    None,

    Drizzle,
    Rain,
    Snow,
    SnowGrains,
    IceCrystals,
    IcePellets,
    Hail,
    SmallHail,
    UnknownPrecipitation,

    Mist,
    Fog,
    Smoke,
    VolcanicAsh,
    WidespreadDust,
    Sand,
    Haze,
    Spray,

    WellDevelopedDustWhirls,
    Squalls,
    FunnelCloudTornadoWaterspout,
    Sandstorm,
    Duststorm
};

enum class SkyCover
{
    VerticalVisibility,
    Clear,
    Few,
    Scattered,
    Broken,
    Overcast
};

enum class SkyCoverClouds
{
    None,
    Cumulonimbus,
    ToweringCumulus
};

//-----------------------------------------------------------------------------

} // namespace Meterology
<commit_msg>Fixed integer division<commit_after>/****************************** Module Header ******************************\
Module Name:  Metar.hpp
Project:      Meteorology
Copyright (c) 2014 Steven Frost.

This module defines the Weather class including general meteorology methods,
meteorology-releated enumerations and type definitions for different
meteorology properties.

References:  (1) http://en.wikipedia.org/wiki/Weather

Todo:        (1) Complete type definitions
             (2) Complete enumerated list of cloud type and cover

This source is subject to the MIT License.
See http://opensource.org/licenses/MIT

All other rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

#pragma once

//-----------------------------------------------------------------------------

namespace Meteorology
{

//-----------------------------------------------------------------------------

inline double CelsiusToFahrenheit(double celsius)
{
    return celsius * ((9.0 / 5.0) + 32);
}

inline double MetresToFeet(double metres)
{
    return metres / 0.3048;
}

inline double MilesToFeet(double miles)
{
    return miles * 5280;
}

inline double InhgToHpa(double inhg)
{
    return inhg * 33.8638816;
}

inline double HpaToInhg(double hpa)
{
    return hpa / 33.8638816;
}

//-----------------------------------------------------------------------------

enum class WeatherIntensity
{
    Light,
    Moderate,
    Heavy,
    InTheVicinity
};

enum class WeatherDescriptor
{
    None,
    Shallow,
    Partial,
    Patches,
    LowDrifting,
    Blowing,
    Showers,
    Thunderstorm,
    Freezing
};

enum class WeatherPhenomena
{
    None,

    Drizzle,
    Rain,
    Snow,
    SnowGrains,
    IceCrystals,
    IcePellets,
    Hail,
    SmallHail,
    UnknownPrecipitation,

    Mist,
    Fog,
    Smoke,
    VolcanicAsh,
    WidespreadDust,
    Sand,
    Haze,
    Spray,

    WellDevelopedDustWhirls,
    Squalls,
    FunnelCloudTornadoWaterspout,
    Sandstorm,
    Duststorm
};

enum class SkyCover
{
    VerticalVisibility,
    Clear,
    Few,
    Scattered,
    Broken,
    Overcast
};

enum class SkyCoverClouds
{
    None,
    Cumulonimbus,
    ToweringCumulus
};

//-----------------------------------------------------------------------------

} // namespace Meterology
<|endoftext|>


<commit_before>#include "string_utils.h"
#include <sstream>
#include <iostream>
#include <curl/curl.h>
#include <set>

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

std::vector<std::string> &split(const std::string &s,
							const std::vector<char> &delims,
							std::vector<std::string> &elems)
{
	//std::cout << "PARSING: \n" << s << std::endl;

	std::vector<std::string> in_tokens;
	in_tokens.push_back(s);

	for (size_t i = 0; i<delims.size(); i++) {
		std::vector<std::string> out_tokens;
		for (size_t j = 0; j<in_tokens.size(); j++)
			if (in_tokens[j]!="")
				split(in_tokens[j], delims[i], out_tokens);
		in_tokens = out_tokens;
	}
	for (int i = 0; i<in_tokens.size(); i++)
		if (in_tokens[i]!="")
			elems.push_back(in_tokens[i]);
	return elems;
}

void fix_utf8_string(std::string& str)
{
	std::string temp;
	temp.reserve(str.size());
	utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
	str = temp;
}

void splitUtf8(const std::string &_s, std::set<uint32_t> &_delims, std::vector<std::string> &_elems)
{
	if (_s.size()==0)
		return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char *elem = new char [_s.size()];
	char *elem_end = elem;

	memset(elem, 0, _s.size());
	do {
		uint32_t symbol = utf8::next(it, end);

		if (_delims.find(symbol) != _delims.end()) {
			if (elem != elem_end)
				_elems.push_back(std::string(elem));
			memset(elem, 0, _s.size());
			elem_end = elem;
		} else
			elem_end = utf8::append(symbol, elem_end);

	} while (it < end);

	if (elem != elem_end)
		_elems.push_back(std::string(elem));

	delete [] elem;
}

bool isUtf8Char(uint32_t c)
{
	// A to Z
	if (0x41 <= c && c <= 0x5a) return true;
	// a to z
	if (0x61 <= c && c <= 0x7a) return true;
	// ?? to ??
	if (0x410 <= c && c <= 0x42F) return true;
	// ?? to ??
	if (0x430 <= c && c <= 0x44f) return true;
	return false;
}

void eraseNonCharsUtf8(std::string &_s)
{
	if (_s.size()==0)
		return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char res[_s.size()+1];
	char *res_end = res;

	memset(res, 0, _s.size()+1);

	do {
		uint32_t symbol = utf8::next(it, end);

		if (isUtf8Char(symbol)) {
			res_end = utf8::append(symbol, res_end);
		}

	} while (it < end);
	res_end = 0;
	_s = std::string(res);
}

uint32_t toLowerCharUtf8(uint32_t c)
{
	if (0x41 <= c && c <= 0x5a)
		return c + 0x61 - 0x41;
	if (0x410 <= c && c <= 0x42F)
		return c + 0x430 - 0x410;
	return c;
}

void toLowerUtf8(std::string &_s)
{
	if (_s.size()==0)
	return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char res[_s.size()+1];
	char *res_end = res;

	memset(res, 0, _s.size()+1);

	do {
		uint32_t symbol = utf8::next(it, end);
		res_end = utf8::append(toLowerCharUtf8(symbol), res_end);

	} while (it < end);
	res_end = 0;
	_s = std::string(res);
}

void removeLeadingSpaces(std::string &s)
{
	size_t last_leading_space_pos;
	if (s[0]!=' ')
		return;
	last_leading_space_pos = 0;
	while (s[last_leading_space_pos]==' ' && last_leading_space_pos<s.size())
		last_leading_space_pos++;
	s = s.substr(last_leading_space_pos, s.size()-last_leading_space_pos);
}

void removeEndingSpaces(std::string &s)
{
	size_t last_leading_space_pos;
	if (s[s.size()-1]!=' ')
		return;
	last_leading_space_pos = s.size()-1;
	while (s[last_leading_space_pos]==' ' && last_leading_space_pos>0)
		last_leading_space_pos--;
	s = s.substr(0, last_leading_space_pos);
}

void removeLeadingAndEndingSpaces(std::string &s)
{
	removeLeadingSpaces(s);
	removeEndingSpaces(s);
}

bool getPairGET(const std::string &s, std::pair<std::string, std::string> &kv)
{
	size_t eq_sym_pos = s.find('=');
	if (eq_sym_pos == std::string::npos)
		return false;
	std::string key = s.substr(0, eq_sym_pos);
	std::string value = s.substr(eq_sym_pos+1, s.size()-eq_sym_pos);
	removeLeadingAndEndingSpaces(key);
	removeLeadingAndEndingSpaces(value);
	char *key_c = curl_easy_unescape(NULL, key.c_str(), key.size(), NULL);
	if (key_c==NULL) return false;
	kv.first = std::string(key_c);
	curl_free(key_c);

	char *value_c = curl_easy_unescape(NULL, value.c_str(), value.size(), NULL);
	if (value_c==NULL) return false;
	kv.second = std::string(value_c);
	curl_free(value_c);

	return true;
}

void parseGET(const std::string &_data,
			hiaux::hashtable<std::string, std::string> &values_GET)
{
	std::cout << "parseGET " << _data << std::endl;
	std::vector<std::string> words = split(_data, ' ');
	if (words.size()<2)
		return;

	std::string data = words[1];

	if (data.size()<4) return;
	std::vector<std::string> keyvalues;
	/*
	std::set<uint32_t> delims;
	delims.insert(0x3f); // '?'
	delims.insert(0x26); // '&'

	splitUtf8(data, delims, keyvalues);
	*/

	std::vector<char> delims;
	delims.push_back('?');
	delims.push_back('&');
	split(data, delims, keyvalues);

	for (int i = 0; i<keyvalues.size(); i++) {
		std::pair<std::string, std::string> kv;
		if (getPairGET(keyvalues[i], kv))
			//std::cout << "KEY: " << kv.first << " VALUE: " << kv.second << std::endl;
			values_GET[kv.first] = kv.second;
	}
}

inline bool isDelimeter(char c)
{
	//if (c==' ') return true;
	if (c=='\t') return true;
	if (c=='\n') return true;
	return false;
}

void removeRedundantDelimeters(std::string &s)
{
//	std::wstring();
	bool prev_delim = false;
	std::string::iterator it = s.begin();
	while (it != s.end()) {
		if (isDelimeter(*it)) {
			if (prev_delim) {
				s.erase(it);
				//prev_delim = false;
			}
			else
				prev_delim = true;
		} else {
			prev_delim = false;
		}
		it++;
	}
}

void string_to_uint64(const std::string &_s, uint64_t &_i)
{
	sscanf(_s.c_str(), "%llu", &_i);
}

uint64_t string_to_uint64(const std::string &_s)
{
	uint64_t i;
	string_to_uint64(_s, i);
	return i;
}

void uint64_to_string(const uint64_t &_i, std::string &_s)
{
	char bf[50];
	sprintf(bf, "%llu", _i);
	_s = std::string(bf);
}

std::string uint64_to_string(const uint64_t &_i)
{
	char bf[50];
	sprintf(bf, "%llu", _i);
	return std::string(bf);
}

std::string float_to_string(float _f)
{
	char bf[50];
	sprintf(bf, "%f", _f);
	return std::string(bf);
}

std::string &unescapeUrl(std::string &_value) {
	char *value_c = curl_easy_unescape(NULL, _value.c_str(), _value.size(), NULL);
	if (value_c==NULL) _value = "";
	_value = std::string(value_c);
	curl_free(value_c);
	return _value;
}<commit_msg>Added try-catch in fix_utf8_string<commit_after>#include "string_utils.h"
#include <sstream>
#include <iostream>
#include <curl/curl.h>
#include <set>

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

std::vector<std::string> &split(const std::string &s,
							const std::vector<char> &delims,
							std::vector<std::string> &elems)
{
	//std::cout << "PARSING: \n" << s << std::endl;

	std::vector<std::string> in_tokens;
	in_tokens.push_back(s);

	for (size_t i = 0; i<delims.size(); i++) {
		std::vector<std::string> out_tokens;
		for (size_t j = 0; j<in_tokens.size(); j++)
			if (in_tokens[j]!="")
				split(in_tokens[j], delims[i], out_tokens);
		in_tokens = out_tokens;
	}
	for (int i = 0; i<in_tokens.size(); i++)
		if (in_tokens[i]!="")
			elems.push_back(in_tokens[i]);
	return elems;
}

void fix_utf8_string(std::string& str)
{
	try {
		std::string temp;
		utf8::replace_invalid(str.begin(), str.end(), back_inserter(temp));
		str = temp;
	} catch (utf8::not_enough_room ex) {

	}
}

void splitUtf8(const std::string &_s, std::set<uint32_t> &_delims, std::vector<std::string> &_elems)
{
	if (_s.size()==0)
		return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char *elem = new char [_s.size()];
	char *elem_end = elem;

	memset(elem, 0, _s.size());
	do {
		uint32_t symbol = utf8::next(it, end);

		if (_delims.find(symbol) != _delims.end()) {
			if (elem != elem_end)
				_elems.push_back(std::string(elem));
			memset(elem, 0, _s.size());
			elem_end = elem;
		} else
			elem_end = utf8::append(symbol, elem_end);

	} while (it < end);

	if (elem != elem_end)
		_elems.push_back(std::string(elem));

	delete [] elem;
}

bool isUtf8Char(uint32_t c)
{
	// A to Z
	if (0x41 <= c && c <= 0x5a) return true;
	// a to z
	if (0x61 <= c && c <= 0x7a) return true;
	// ?? to ??
	if (0x410 <= c && c <= 0x42F) return true;
	// ?? to ??
	if (0x430 <= c && c <= 0x44f) return true;
	return false;
}

void eraseNonCharsUtf8(std::string &_s)
{
	if (_s.size()==0)
		return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char res[_s.size()+1];
	char *res_end = res;

	memset(res, 0, _s.size()+1);

	do {
		uint32_t symbol = utf8::next(it, end);

		if (isUtf8Char(symbol)) {
			res_end = utf8::append(symbol, res_end);
		}

	} while (it < end);
	res_end = 0;
	_s = std::string(res);
}

uint32_t toLowerCharUtf8(uint32_t c)
{
	if (0x41 <= c && c <= 0x5a)
		return c + 0x61 - 0x41;
	if (0x410 <= c && c <= 0x42F)
		return c + 0x430 - 0x410;
	return c;
}

void toLowerUtf8(std::string &_s)
{
	if (_s.size()==0)
	return;

	const char *it = _s.data();
	const char *end = _s.data()+_s.size();
	char res[_s.size()+1];
	char *res_end = res;

	memset(res, 0, _s.size()+1);

	do {
		uint32_t symbol = utf8::next(it, end);
		res_end = utf8::append(toLowerCharUtf8(symbol), res_end);

	} while (it < end);
	res_end = 0;
	_s = std::string(res);
}

void removeLeadingSpaces(std::string &s)
{
	size_t last_leading_space_pos;
	if (s[0]!=' ')
		return;
	last_leading_space_pos = 0;
	while (s[last_leading_space_pos]==' ' && last_leading_space_pos<s.size())
		last_leading_space_pos++;
	s = s.substr(last_leading_space_pos, s.size()-last_leading_space_pos);
}

void removeEndingSpaces(std::string &s)
{
	size_t last_leading_space_pos;
	if (s[s.size()-1]!=' ')
		return;
	last_leading_space_pos = s.size()-1;
	while (s[last_leading_space_pos]==' ' && last_leading_space_pos>0)
		last_leading_space_pos--;
	s = s.substr(0, last_leading_space_pos);
}

void removeLeadingAndEndingSpaces(std::string &s)
{
	removeLeadingSpaces(s);
	removeEndingSpaces(s);
}

bool getPairGET(const std::string &s, std::pair<std::string, std::string> &kv)
{
	size_t eq_sym_pos = s.find('=');
	if (eq_sym_pos == std::string::npos)
		return false;
	std::string key = s.substr(0, eq_sym_pos);
	std::string value = s.substr(eq_sym_pos+1, s.size()-eq_sym_pos);
	removeLeadingAndEndingSpaces(key);
	removeLeadingAndEndingSpaces(value);
	char *key_c = curl_easy_unescape(NULL, key.c_str(), key.size(), NULL);
	if (key_c==NULL) return false;
	kv.first = std::string(key_c);
	curl_free(key_c);

	char *value_c = curl_easy_unescape(NULL, value.c_str(), value.size(), NULL);
	if (value_c==NULL) return false;
	kv.second = std::string(value_c);
	curl_free(value_c);

	return true;
}

void parseGET(const std::string &_data,
			hiaux::hashtable<std::string, std::string> &values_GET)
{
	std::cout << "parseGET " << _data << std::endl;
	std::vector<std::string> words = split(_data, ' ');
	if (words.size()<2)
		return;

	std::string data = words[1];

	if (data.size()<4) return;
	std::vector<std::string> keyvalues;
	/*
	std::set<uint32_t> delims;
	delims.insert(0x3f); // '?'
	delims.insert(0x26); // '&'

	splitUtf8(data, delims, keyvalues);
	*/

	std::vector<char> delims;
	delims.push_back('?');
	delims.push_back('&');
	split(data, delims, keyvalues);

	for (int i = 0; i<keyvalues.size(); i++) {
		std::pair<std::string, std::string> kv;
		if (getPairGET(keyvalues[i], kv))
			//std::cout << "KEY: " << kv.first << " VALUE: " << kv.second << std::endl;
			values_GET[kv.first] = kv.second;
	}
}

inline bool isDelimeter(char c)
{
	//if (c==' ') return true;
	if (c=='\t') return true;
	if (c=='\n') return true;
	return false;
}

void removeRedundantDelimeters(std::string &s)
{
//	std::wstring();
	bool prev_delim = false;
	std::string::iterator it = s.begin();
	while (it != s.end()) {
		if (isDelimeter(*it)) {
			if (prev_delim) {
				s.erase(it);
				//prev_delim = false;
			}
			else
				prev_delim = true;
		} else {
			prev_delim = false;
		}
		it++;
	}
}

void string_to_uint64(const std::string &_s, uint64_t &_i)
{
	sscanf(_s.c_str(), "%llu", &_i);
}

uint64_t string_to_uint64(const std::string &_s)
{
	uint64_t i;
	string_to_uint64(_s, i);
	return i;
}

void uint64_to_string(const uint64_t &_i, std::string &_s)
{
	char bf[50];
	sprintf(bf, "%llu", _i);
	_s = std::string(bf);
}

std::string uint64_to_string(const uint64_t &_i)
{
	char bf[50];
	sprintf(bf, "%llu", _i);
	return std::string(bf);
}

std::string float_to_string(float _f)
{
	char bf[50];
	sprintf(bf, "%f", _f);
	return std::string(bf);
}

std::string &unescapeUrl(std::string &_value) {
	char *value_c = curl_easy_unescape(NULL, _value.c_str(), _value.size(), NULL);
	if (value_c==NULL) _value = "";
	_value = std::string(value_c);
	curl_free(value_c);
	return _value;
}<|endoftext|>