<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.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, chrome::NOTIFICATION_BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(int 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 kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
    "chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
    "files/workers/workers_ui_shared_worker.html";

void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
  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(
          window->GetRenderViewHost(),
          L"",
          L"window.domAutomationController.send("
          L"'' + (window.uiTests && (typeof uiTests.runTest)));",
          &result));

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

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest()
      : window_(NULL),
        inspected_rvh_(NULL) {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    RunTestFuntion(window_, test_name.c_str());
    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();
    window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    TabContents* 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);
  }

  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) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, chrome::NOTIFICATION_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, chrome::NOTIFICATION_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(int type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type) {
      case chrome::NOTIFICATION_EXTENSION_LOADED:
      case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
 public:
  explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
    registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
    ui_test_utils::RunMessageLoop();
  }

 private:
  virtual void Observe(int type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == content::NOTIFICATION_LOAD_STOP) {
      if (done_)
        return;
      done_ = true;
      MessageLoopForUI::current()->Quit();
    }
  }

  NotificationRegistrar registrar_;
  bool done_;
  DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};

class WorkerDevToolsSanityTest : public InProcessBrowserTest {
 public:
  WorkerDevToolsSanityTest() : window_(NULL) {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const char* test_name, const char* test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    OpenDevToolsWindowForFirstSharedWorker();
    RunTestFuntion(window_, test_name);
    CloseDevToolsWindow();
  }

  static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
    BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
    bool found = false;
    for (; !iter.Done(); ++iter) {
      WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
      const WorkerProcessHost::Instances& instances = worker->instances();
      for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
           i != instances.end(); ++i) {
        if (!i->shared())
          continue;
        WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
            worker->id(), i->worker_route_id());
        found = true;
        break;
      }
    }
    if (found) {
      BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
          new MessageLoop::QuitTask);
    } else if (attempt < 30) {
      MessageLoop::current()->PostDelayedTask(
          FROM_HERE,
          NewRunnableFunction(
              &OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
          100);
    } else {
      FAIL() << "Shared worker not found.";
    }

  }

  void OpenDevToolsWindowForFirstSharedWorker() {
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
        &OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
    ui_test_utils::RunMessageLoop();
    window_ = static_cast<DevToolsWindow*>(
                  DevToolsClientHost::GetDevToolsClientHostForTest());
    ASSERT_TRUE(window_ != NULL);

    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
    if (client_contents->IsLoading()) {
      LoadStopObserver(
          Source<NavigationController>(&client_contents->controller()));
    }
  }

  void CloseDevToolsWindow() {
    Browser* browser = window_->browser();
    browser->CloseAllTabs();
    BrowserClosedObserver close_observer(browser);
  }

  DevToolsWindow* window_;
};

// 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.
  content::GetContentClient()->browser()->ClearInspectorSettings(
      GetInspectedTab()->render_view_host());
  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.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

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

// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
  RunTest("testNetworkTiming", kSlowTestPage);
}

// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
  RunTest("testNetworkSize", kChunkedTestPage);
}

// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
  RunTest("testNetworkSyncSize", kChunkedTestPage);
}

// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
  RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}

IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
  OpenDevToolsWindow("about:blank");
  std::string result;
  ASSERT_TRUE(
      ui_test_utils::ExecuteJavaScriptAndExtractString(
          window_->GetRenderViewHost(),
          L"",
          L"window.domAutomationController.send("
          L"'' + (window.uiTests && (typeof uiTests.runTest)));",
          &result));
  ASSERT_EQ("function", result) << "DevTools front-end is broken.";
  CloseDevToolsWindow();
}

// Flakily fails: http://crbug.com/89845
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, FLAKY_InspectSharedWorker) {
  RunTest("testSharedWorker", kSharedWorkerTestPage);
}

}  // namespace
<commit_msg>Disable InspectSharedWorker.<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/debugger/devtools_client_host.h"
#include "content/browser/debugger/devtools_manager.h"
#include "content/browser/debugger/worker_devtools_manager_io.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/worker_host/worker_process_host.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.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, chrome::NOTIFICATION_BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(int 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 kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";
const char kChunkedTestPage[] = "chunked";
const char kSlowTestPage[] =
    "chunked?waitBeforeHeaders=100&waitBetweenChunks=100&chunksNumber=2";
const char kSharedWorkerTestPage[] =
    "files/workers/workers_ui_shared_worker.html";

void RunTestFuntion(DevToolsWindow* window, const char* test_name) {
  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(
          window->GetRenderViewHost(),
          L"",
          L"window.domAutomationController.send("
          L"'' + (window.uiTests && (typeof uiTests.runTest)));",
          &result));

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

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest()
      : window_(NULL),
        inspected_rvh_(NULL) {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    RunTestFuntion(window_, test_name.c_str());
    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();
    window_ = DevToolsWindow::OpenDevToolsWindow(inspected_rvh_);
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    TabContents* 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);
  }

  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) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, chrome::NOTIFICATION_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, chrome::NOTIFICATION_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(int type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type) {
      case chrome::NOTIFICATION_EXTENSION_LOADED:
      case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Used to block until a navigation completes.
class LoadStopObserver : public NotificationObserver {
 public:
  explicit LoadStopObserver(const NotificationSource& source) : done_(false) {
    registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, source);
    ui_test_utils::RunMessageLoop();
  }

 private:
  virtual void Observe(int type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == content::NOTIFICATION_LOAD_STOP) {
      if (done_)
        return;
      done_ = true;
      MessageLoopForUI::current()->Quit();
    }
  }

  NotificationRegistrar registrar_;
  bool done_;
  DISALLOW_COPY_AND_ASSIGN(LoadStopObserver);
};

class WorkerDevToolsSanityTest : public InProcessBrowserTest {
 public:
  WorkerDevToolsSanityTest() : window_(NULL) {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const char* test_name, const char* test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    OpenDevToolsWindowForFirstSharedWorker();
    RunTestFuntion(window_, test_name);
    CloseDevToolsWindow();
  }

  static void OpenDevToolsWindowForFirstSharedWorkerOnIOThread(int attempt) {
    BrowserChildProcessHost::Iterator iter(ChildProcessInfo::WORKER_PROCESS);
    bool found = false;
    for (; !iter.Done(); ++iter) {
      WorkerProcessHost* worker = static_cast<WorkerProcessHost*>(*iter);
      const WorkerProcessHost::Instances& instances = worker->instances();
      for (WorkerProcessHost::Instances::const_iterator i = instances.begin();
           i != instances.end(); ++i) {
        if (!i->shared())
          continue;
        WorkerDevToolsManagerIO::GetInstance()->OpenDevToolsForWorker(
            worker->id(), i->worker_route_id());
        found = true;
        break;
      }
    }
    if (found) {
      BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
          new MessageLoop::QuitTask);
    } else if (attempt < 30) {
      MessageLoop::current()->PostDelayedTask(
          FROM_HERE,
          NewRunnableFunction(
              &OpenDevToolsWindowForFirstSharedWorkerOnIOThread, attempt + 1),
          100);
    } else {
      FAIL() << "Shared worker not found.";
    }

  }

  void OpenDevToolsWindowForFirstSharedWorker() {
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableFunction(
        &OpenDevToolsWindowForFirstSharedWorkerOnIOThread, 1));
    ui_test_utils::RunMessageLoop();
    window_ = static_cast<DevToolsWindow*>(
                  DevToolsClientHost::GetDevToolsClientHostForTest());
    ASSERT_TRUE(window_ != NULL);

    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    TabContents* client_contents = client_rvh->delegate()->GetAsTabContents();
    if (client_contents->IsLoading()) {
      LoadStopObserver(
          Source<NavigationController>(&client_contents->controller()));
    }
  }

  void CloseDevToolsWindow() {
    Browser* browser = window_->browser();
    browser->CloseAllTabs();
    BrowserClosedObserver close_observer(browser);
  }

  DevToolsWindow* window_;
};

// 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.
  content::GetContentClient()->browser()->ClearInspectorSettings(
      GetInspectedTab()->render_view_host());
  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.
// Flaky - http://crbug.com/69719.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FLAKY_TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

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

// Tests network timing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkTiming) {
  RunTest("testNetworkTiming", kSlowTestPage);
}

// Tests network size.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSize) {
  RunTest("testNetworkSize", kChunkedTestPage);
}

// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkSyncSize) {
  RunTest("testNetworkSyncSize", kChunkedTestPage);
}

// Tests raw headers text.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNetworkRawHeadersText) {
  RunTest("testNetworkRawHeadersText", kChunkedTestPage);
}

IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPageWithNoJavaScript) {
  OpenDevToolsWindow("about:blank");
  std::string result;
  ASSERT_TRUE(
      ui_test_utils::ExecuteJavaScriptAndExtractString(
          window_->GetRenderViewHost(),
          L"",
          L"window.domAutomationController.send("
          L"'' + (window.uiTests && (typeof uiTests.runTest)));",
          &result));
  ASSERT_EQ("function", result) << "DevTools front-end is broken.";
  CloseDevToolsWindow();
}

// Flakily fails with 25s timeout: http://crbug.com/89845
IN_PROC_BROWSER_TEST_F(WorkerDevToolsSanityTest, DISABLED_InspectSharedWorker) {
  RunTest("testSharedWorker", kSharedWorkerTestPage);
}

}  // namespace
<|endoftext|>


<commit_before>// This file is part of playd.
// playd is licenced under the MIT license: see LICENSE.txt.

/**
 * @file
 * Implementation of the TimeParser class.
 * @see time_parser.hpp
 */

#include <algorithm>
#include <sstream>
#include <stdexcept>

#include "errors.hpp"
#include "messages.h"
#include "time_parser.hpp"

TimeParser::MicrosecondPosition TimeParser::Parse(const std::string &time_str) const
{
	auto seek = Split(time_str);
	std::string unit = seek.first;
	MicrosecondPosition num_units = seek.second;

	return static_cast<MicrosecondPosition>(UnitMultiplier(unit)) * num_units;
}

TimeParser::Multiplier TimeParser::UnitMultiplier(const std::string &unit) const
{
	// Default to microseconds if no unit is given.
	if (unit.empty()) return Multiplier::US;

	if (IsIn(unit, {"us", "usec", "usecs"})) return Multiplier::US;
	if (IsIn(unit, {"ms", "msec", "msecs"})) return Multiplier::MS;
	if (IsIn(unit, {"s", "sec", "secs"})) return Multiplier::S;
	if (IsIn(unit, {"m", "min", "mins"})) return Multiplier::M;
	if (IsIn(unit, {"h", "hour", "hours"})) return Multiplier::H;

	throw std::out_of_range(unit);
}

bool TimeParser::IsIn(const std::string &unit, std::initializer_list<std::string> list) const
{
	return std::find(list.begin(), list.end(), unit) != list.end();
}

std::pair<std::string, TimeParser::MicrosecondPosition> TimeParser::Split(const std::string &time_str) const
{
	std::istringstream is(time_str);
	MicrosecondPosition raw_time;
	std::string rest;

	is >> raw_time;

	// Make sure we actually get a time of some form.
	if (is.fail()) throw SeekError(MSG_SEEK_FAIL);

	is >> rest;
	return std::make_pair(rest, raw_time);
}
<commit_msg>Remove long-form units.<commit_after>// This file is part of playd.
// playd is licenced under the MIT license: see LICENSE.txt.

/**
 * @file
 * Implementation of the TimeParser class.
 * @see time_parser.hpp
 */

#include <algorithm>
#include <sstream>
#include <stdexcept>

#include "errors.hpp"
#include "messages.h"
#include "time_parser.hpp"

TimeParser::MicrosecondPosition TimeParser::Parse(const std::string &time_str) const
{
	auto seek = Split(time_str);
	std::string unit = seek.first;
	MicrosecondPosition num_units = seek.second;

	return static_cast<MicrosecondPosition>(UnitMultiplier(unit)) * num_units;
}

TimeParser::Multiplier TimeParser::UnitMultiplier(const std::string &unit) const
{
	// Default to microseconds if no unit is given.
	if (unit.empty()) return Multiplier::US;

	if (unit == "us") return Multiplier::US;
	if (unit == "ms") return Multiplier::MS;
	if (unit == "s") return Multiplier::S;
	if (unit == "m") return Multiplier::M;
	if (unit == "h") return Multiplier::H;

	throw std::out_of_range(unit);
}

bool TimeParser::IsIn(const std::string &unit, std::initializer_list<std::string> list) const
{
	return std::find(list.begin(), list.end(), unit) != list.end();
}

std::pair<std::string, TimeParser::MicrosecondPosition> TimeParser::Split(const std::string &time_str) const
{
	std::istringstream is(time_str);
	MicrosecondPosition raw_time;
	std::string rest;

	is >> raw_time;

	// Make sure we actually get a time of some form.
	if (is.fail()) throw SeekError(MSG_SEEK_FAIL);

	is >> rest;
	return std::make_pair(rest, raw_time);
}
<|endoftext|>


<commit_before>#include "main.h"

#include <boost/program_options.hpp>
#include <errno.h>
#include <signal.h>

const int RECONNECT_ATTEMPTS = 30;
const int RECONNECT_INTERVAL_MS = 500;

using namespace std;
namespace asio = boost::asio;
namespace po = boost::program_options;

static asio::io_service ioSvc;

void sigint(int sig) {
	cerr << "Intercepted signal#" << sig << endl;
	if (sig == SIGINT) {
		cerr << "Exiting..." << endl;
		ioSvc.stop();
		// TODO: Emergency exit on repeated sig
	}
	cerr.flush();
}

int main(int argc, char *argv[])
{
	signal(SIGINT, &sigint);

	BoostAsioFilesystem_Options opts;

	po::options_description desc("Supported options");
	desc.add_options()
		("help,h",
			"Show help")
		("name,n", po::value< string >()->default_value("bhget"),
			"Bithorde-name of this client")
		("debug,d",
			"Show fuse-commands, for debugging purposes")
		("url,u", po::value< string >()->default_value("/tmp/bithorde"),
			"Where to connect to bithorde. Either host:port, or /path/socket")
		("mountpoint", po::value< string >(&opts.mountpoint),
			"Where to mount filesystem")
	;
	po::positional_options_description p;
	p.add("mountpoint", 1);

	po::command_line_parser parser(argc, argv);
	parser.options(desc).positional(p);

	po::variables_map vm;
	po::store(parser.run(), vm);
	po::notify(vm);

	if (vm.count("help") || !vm.count("mountpoint")) {
		cerr << desc << endl;
		return 1;
	}

	opts.name = "bhfuse";
	if (vm.count("debug"))
		opts.debug = true;

	BHFuse fs(ioSvc, vm["url"].as<string>(), opts);

	return ioSvc.run();
}

BHFuse::BHFuse(asio::io_service & ioSvc, string bithorded, BoostAsioFilesystem_Options & opts) :
	BoostAsioFilesystem(ioSvc, opts),
	ioSvc(ioSvc),
	bithorded(bithorded),
	_ino_allocator(2)
{
	client = Client::create(ioSvc, "bhfuse");
	client->authenticated.connect(boost::bind(&BHFuse::onConnected, this, _1));
	client->disconnected.connect(boost::bind(&BHFuse::reconnect, this));

	client->connect(bithorded);
}

void BHFuse::reconnect()
{
	cerr << "Disconnected, trying reconnect..." << endl;
	for (int i=0; i < RECONNECT_ATTEMPTS; i++) {
		usleep(RECONNECT_INTERVAL_MS * 1000);
		try {
			client->connect(bithorded);
			return;
		} catch (boost::system::system_error e) {
			cerr << "Failed to reconnect, retrying..." << endl;
		}
	}
	cerr << "Giving up." << endl;
}

void BHFuse::onConnected(std::string remoteName) {
	(cout << "Connected to " << remoteName << endl).flush();
}

int BHFuse::fuse_lookup(fuse_req_t req, fuse_ino_t parent, const char *name) {
	if (parent != 1)
		return ENOENT;

	LookupParams lp(parent, name);
	if (_lookup_cache.count(lp)) {
		_lookup_cache[lp]->fuse_reply_lookup(req);
		return 0;
	}

	MagnetURI uri;
	if (uri.parse(name)) {
		Lookup * lookup = new Lookup(this, req, uri, lp);
		lookup->perform(client);
		return 0;
	} else {
		return ENOENT;
	}
}

void BHFuse::fuse_forget(fuse_ino_t ino, ulong nlookup) {
	unrefInode(ino, nlookup);
}

int BHFuse::fuse_getattr(fuse_req_t req, fuse_ino_t ino, fuse_file_info *) {
	if (ino == 1) {
		struct stat attr;
		bzero(&attr, sizeof(attr));
		attr.st_mode = S_IFDIR | 0444;
		attr.st_blksize = 32*1024;
		attr.st_ino = ino;
		attr.st_nlink = 2;
		fuse_reply_attr(req, &attr, 5);
	} else if (_inode_cache.count(ino)) {
		_inode_cache[ino]->fuse_reply_stat(req);
	} else {
		return ENOENT;
	}
	return 0;
}

int BHFuse::fuse_open(fuse_req_t req, fuse_ino_t ino, fuse_file_info *fi) {
	FUSEAsset* a;
	if (_inode_cache.count(ino) && (a = dynamic_cast<FUSEAsset*>(_inode_cache[ino]))) {
		a->fuse_dispatch_open(req, fi);
		return 0;
	} else {
		return ENOENT;
	}
}

int BHFuse::fuse_release(fuse_req_t req, fuse_ino_t ino, fuse_file_info * fi) {
	if (FUSEAsset * a = static_cast<FUSEAsset*>(_inode_cache[ino])) {
		a->fuse_dispatch_close(req, fi);
		return 0;
	} else {
		return EBADF;
	}
}

int BHFuse::fuse_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, fuse_file_info *)
{
	FUSEAsset* a = dynamic_cast<FUSEAsset*>(_inode_cache[ino]);
	if (a) {
		a->read(req, off, size);
		return 0;
	} else {
		return EBADF;
	}
}

FUSEAsset * BHFuse::registerAsset(ReadAsset *asset, LookupParams& lookup_params)
{
	fuse_ino_t ino = _ino_allocator.allocate();
	FUSEAsset * a = new FUSEAsset(this, ino, asset, lookup_params);
	_inode_cache[ino] = a;
	_lookup_cache[lookup_params] = a;
	return a;
}

bool BHFuse::unrefInode(fuse_ino_t ino, int count)
{
	INode * i = _inode_cache[ino];
	if (i) {
		if (!i->dropRefs(count)) {
			_inode_cache.erase(ino);
			_lookup_cache.erase(i->lookup_params);
			_ino_allocator.free(ino);
			delete i;
		}
		return true;
	} else {
		return false;
	}
}
<commit_msg>[clients/bhfuse/main]Cleanly shutdown after failed reconnection.<commit_after>#include "main.h"

#include <boost/program_options.hpp>
#include <errno.h>
#include <signal.h>

const int RECONNECT_ATTEMPTS = 30;
const int RECONNECT_INTERVAL_MS = 500;

using namespace std;
namespace asio = boost::asio;
namespace po = boost::program_options;

static asio::io_service ioSvc;

void sigint(int sig) {
	cerr << "Intercepted signal#" << sig << endl;
	if (sig == SIGINT) {
		cerr << "Exiting..." << endl;
		ioSvc.stop();
		// TODO: Emergency exit on repeated sig
	}
	cerr.flush();
}

int main(int argc, char *argv[])
{
	signal(SIGINT, &sigint);

	BoostAsioFilesystem_Options opts;

	po::options_description desc("Supported options");
	desc.add_options()
		("help,h",
			"Show help")
		("name,n", po::value< string >()->default_value("bhget"),
			"Bithorde-name of this client")
		("debug,d",
			"Show fuse-commands, for debugging purposes")
		("url,u", po::value< string >()->default_value("/tmp/bithorde"),
			"Where to connect to bithorde. Either host:port, or /path/socket")
		("mountpoint", po::value< string >(&opts.mountpoint),
			"Where to mount filesystem")
	;
	po::positional_options_description p;
	p.add("mountpoint", 1);

	po::command_line_parser parser(argc, argv);
	parser.options(desc).positional(p);

	po::variables_map vm;
	po::store(parser.run(), vm);
	po::notify(vm);

	if (vm.count("help") || !vm.count("mountpoint")) {
		cerr << desc << endl;
		return 1;
	}

	opts.name = "bhfuse";
	if (vm.count("debug"))
		opts.debug = true;

	BHFuse fs(ioSvc, vm["url"].as<string>(), opts);

	return ioSvc.run();
}

BHFuse::BHFuse(asio::io_service & ioSvc, string bithorded, BoostAsioFilesystem_Options & opts) :
	BoostAsioFilesystem(ioSvc, opts),
	ioSvc(ioSvc),
	bithorded(bithorded),
	_ino_allocator(2)
{
	client = Client::create(ioSvc, "bhfuse");
	client->authenticated.connect(boost::bind(&BHFuse::onConnected, this, _1));
	client->disconnected.connect(boost::bind(&BHFuse::reconnect, this));

	client->connect(bithorded);
}

void BHFuse::reconnect()
{
	cerr << "Disconnected, trying reconnect..." << endl;
	for (int i=0; i < RECONNECT_ATTEMPTS; i++) {
		usleep(RECONNECT_INTERVAL_MS * 1000);
		try {
			client->connect(bithorded);
			return;
		} catch (boost::system::system_error e) {
			cerr << "Failed to reconnect, retrying..." << endl;
		}
	}
	cerr << "Giving up." << endl;
	ioSvc.stop();
}

void BHFuse::onConnected(std::string remoteName) {
	(cout << "Connected to " << remoteName << endl).flush();
}

int BHFuse::fuse_lookup(fuse_req_t req, fuse_ino_t parent, const char *name) {
	if (parent != 1)
		return ENOENT;

	LookupParams lp(parent, name);
	if (_lookup_cache.count(lp)) {
		_lookup_cache[lp]->fuse_reply_lookup(req);
		return 0;
	}

	MagnetURI uri;
	if (uri.parse(name)) {
		Lookup * lookup = new Lookup(this, req, uri, lp);
		lookup->perform(client);
		return 0;
	} else {
		return ENOENT;
	}
}

void BHFuse::fuse_forget(fuse_ino_t ino, ulong nlookup) {
	unrefInode(ino, nlookup);
}

int BHFuse::fuse_getattr(fuse_req_t req, fuse_ino_t ino, fuse_file_info *) {
	if (ino == 1) {
		struct stat attr;
		bzero(&attr, sizeof(attr));
		attr.st_mode = S_IFDIR | 0444;
		attr.st_blksize = 32*1024;
		attr.st_ino = ino;
		attr.st_nlink = 2;
		fuse_reply_attr(req, &attr, 5);
	} else if (_inode_cache.count(ino)) {
		_inode_cache[ino]->fuse_reply_stat(req);
	} else {
		return ENOENT;
	}
	return 0;
}

int BHFuse::fuse_open(fuse_req_t req, fuse_ino_t ino, fuse_file_info *fi) {
	FUSEAsset* a;
	if (_inode_cache.count(ino) && (a = dynamic_cast<FUSEAsset*>(_inode_cache[ino]))) {
		a->fuse_dispatch_open(req, fi);
		return 0;
	} else {
		return ENOENT;
	}
}

int BHFuse::fuse_release(fuse_req_t req, fuse_ino_t ino, fuse_file_info * fi) {
	if (FUSEAsset * a = static_cast<FUSEAsset*>(_inode_cache[ino])) {
		a->fuse_dispatch_close(req, fi);
		return 0;
	} else {
		return EBADF;
	}
}

int BHFuse::fuse_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, fuse_file_info *)
{
	FUSEAsset* a = dynamic_cast<FUSEAsset*>(_inode_cache[ino]);
	if (a) {
		a->read(req, off, size);
		return 0;
	} else {
		return EBADF;
	}
}

FUSEAsset * BHFuse::registerAsset(ReadAsset *asset, LookupParams& lookup_params)
{
	fuse_ino_t ino = _ino_allocator.allocate();
	FUSEAsset * a = new FUSEAsset(this, ino, asset, lookup_params);
	_inode_cache[ino] = a;
	_lookup_cache[lookup_params] = a;
	return a;
}

bool BHFuse::unrefInode(fuse_ino_t ino, int count)
{
	INode * i = _inode_cache[ino];
	if (i) {
		if (!i->dropRefs(count)) {
			_inode_cache.erase(ino);
			_lookup_cache.erase(i->lookup_params);
			_ino_allocator.free(ino);
			delete i;
		}
		return true;
	} else {
		return false;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: listviewbuilder.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 01:45:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"

#pragma warning (disable : 4786 4503)

//------------------------------------
// include
//------------------------------------

#ifndef LISTVIEWBUILDER_HXX_INCLUDED
#include "listviewbuilder.hxx"
#endif

#ifndef DOCUMENT_STATISTIC_HXX_INCLUDED
#include "document_statistic.hxx"
#endif

#ifndef UTILITIES_HXX_INCLUDED
#include "internal/utilities.hxx"
#endif

#ifndef CONFIG_HXX_INCLUDED
#include "internal/config.hxx"
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <commctrl.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <commctrl.h>
#include <tchar.h>

#ifndef RESOURCE_H_INCLUDED
#include "internal/resource.h"
#endif

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

list_view_builder_ptr create_list_view_builder(
    HWND hwnd_lv, const std::wstring& col1, const std::wstring& col2)
{
    if (is_windows_xp())
        return list_view_builder_ptr(new winxp_list_view_builder(hwnd_lv, col1, col2));
    else
        return list_view_builder_ptr(new list_view_builder(hwnd_lv, col1, col2));
}

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

list_view_builder::list_view_builder(
    HWND hwnd_list_view,
    const std::wstring& column1_title,
    const std::wstring& column2_title) :
    hwnd_list_view_(hwnd_list_view),
    row_index_(-1),
    column1_title_(column1_title),
    column2_title_(column2_title)
{
}

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

list_view_builder::~list_view_builder()
{
}

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

void list_view_builder::build(statistic_group_list_t& gl)
{
    setup_list_view();

    statistic_group_list_t::iterator group_iter     = gl.begin();
    statistic_group_list_t::iterator group_iter_end = gl.end();

    for (/**/; group_iter != group_iter_end; ++group_iter)
    {
        statistic_item_list_t::iterator item_iter     = group_iter->second.begin();
        statistic_item_list_t::iterator item_iter_end = group_iter->second.end();

        if (item_iter != item_iter_end)
            insert_group(group_iter->first);

        for (/**/; item_iter != item_iter_end; ++item_iter)
            insert_item(item_iter->title_, item_iter->value_, item_iter->editable_);
    }
}

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

void list_view_builder::setup_list_view()
{
    HIMAGELIST h_ils = ImageList_Create(16,15,ILC_MASK, 7, 0);
    HBITMAP    h_bmp = LoadBitmap(GetModuleHandle(MODULE_NAME), MAKEINTRESOURCE(IDB_PROPERTY_IMAGES));
    ImageList_AddMasked(h_ils, h_bmp, RGB(255, 0, 255));

    ListView_SetImageList(hwnd_list_view_, h_ils, LVSIL_SMALL);

    std::wstring header = GetResString(IDS_PROPERTY);

    LVCOLUMN lvc;
    lvc.mask = LVCF_FMT |
               LVCF_WIDTH |
                LVCF_TEXT |
               LVCF_SUBITEM;

    lvc.iSubItem = 0;
    lvc.pszText  = const_cast<wchar_t*>(header.c_str());
    lvc.cx       = 120;
    lvc.fmt      = LVCFMT_LEFT;

    ListView_InsertColumn(hwnd_list_view_, 0, &lvc);
    lvc.iSubItem = 1;
    header = GetResString(IDS_PROPERTY_VALUE);
    lvc.pszText = const_cast<wchar_t*>(header.c_str());
    ListView_InsertColumn(hwnd_list_view_, 1, &lvc);
}

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

void list_view_builder::insert_group(const std::wstring& /*title*/)
{
    insert_item(L"", L"", false);
}

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

void list_view_builder::insert_item(const std::wstring& title, const std::wstring& value, bool is_editable)
{
    LVITEM lvi;

    lvi.iItem      = ++row_index_;
    lvi.iSubItem   = 0;
    lvi.mask       = LVIF_TEXT;
    lvi.state      = 0;
    lvi.cchTextMax = title.size() + 1;
    lvi.stateMask  = 0;
    lvi.pszText    = const_cast<wchar_t*>(title.c_str());

    if (title.length() > 0)
    {
        lvi.mask |= LVIF_IMAGE;

        if (is_editable)
            lvi.iImage = 4;
        else
            lvi.iImage = 3;
    }

    ListView_InsertItem(hwnd_list_view_, &lvi);

    lvi.mask     = LVIF_TEXT;
    lvi.iSubItem = 1;
    lvi.pszText  = const_cast<wchar_t*>(value.c_str());

    ListView_SetItem(hwnd_list_view_, &lvi);
}

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

HWND list_view_builder::get_list_view() const
{
    return hwnd_list_view_;
}

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

winxp_list_view_builder::winxp_list_view_builder(
    HWND hwnd_list_view,
    const std::wstring& column1_title,
    const std::wstring& column2_title) :
    list_view_builder(hwnd_list_view, column1_title, column2_title),
    group_count_(-1),
    row_count_(0)
{
}

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

void winxp_list_view_builder::setup_list_view()
{
    list_view_builder::setup_list_view();

    ListView_EnableGroupView(get_list_view(), TRUE);
}

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

void winxp_list_view_builder::insert_group(const std::wstring& name)
{
    LVGROUP lvg;

    ZeroMemory(&lvg, sizeof(lvg));

    lvg.cbSize    = sizeof(lvg);
    lvg.mask      = LVGF_HEADER | LVGF_STATE | LVGF_GROUPID;
    lvg.pszHeader = const_cast<wchar_t*>(name.c_str());
    lvg.cchHeader = name.size() + 1;
    lvg.iGroupId  = ++group_count_;
    lvg.state     = LVGS_NORMAL;
    lvg.uAlign    = LVGA_HEADER_CENTER;

    ListView_InsertGroup(get_list_view(), row_count_++, &lvg);
}

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

void winxp_list_view_builder::insert_item(
    const std::wstring& title, const std::wstring& value, bool is_editable)
{
    LVITEM lvi;

    lvi.iItem      = ++row_index_;
    lvi.iSubItem   = 0;
    lvi.mask       = LVIF_TEXT | LVIF_GROUPID;
    lvi.state      = 0;
    lvi.stateMask  = 0;
    lvi.pszText    = const_cast<wchar_t*>(title.c_str());
    lvi.iGroupId   = group_count_;

    if (title.length() > 0)
    {
        lvi.mask |= LVIF_IMAGE;

        if (is_editable)
            lvi.iImage = 4;
        else
            lvi.iImage = 3;
    }

    ListView_InsertItem(get_list_view(), &lvi);

    lvi.mask     = LVIF_TEXT;
    lvi.iSubItem = 1;
    lvi.pszText  = const_cast<wchar_t*>(value.c_str());

    ListView_SetItem(get_list_view(), &lvi);

    row_count_++;
}
<commit_msg>INTEGRATION: CWS vistaready01 (1.6.22); FILE MERGED 2006/12/08 12:45:40 lla 1.6.22.1: #i72391# version check wrong<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: listviewbuilder.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-01-02 16:13:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_shell.hxx"

#pragma warning (disable : 4786 4503)

//------------------------------------
// include
//------------------------------------

#ifndef LISTVIEWBUILDER_HXX_INCLUDED
#include "listviewbuilder.hxx"
#endif

#ifndef DOCUMENT_STATISTIC_HXX_INCLUDED
#include "document_statistic.hxx"
#endif

#ifndef UTILITIES_HXX_INCLUDED
#include "internal/utilities.hxx"
#endif

#ifndef CONFIG_HXX_INCLUDED
#include "internal/config.hxx"
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <commctrl.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <commctrl.h>
#include <tchar.h>

#ifndef RESOURCE_H_INCLUDED
#include "internal/resource.h"
#endif

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

list_view_builder_ptr create_list_view_builder(
    HWND hwnd_lv, const std::wstring& col1, const std::wstring& col2)
{
    if (is_windows_xp_or_above())
        return list_view_builder_ptr(new winxp_list_view_builder(hwnd_lv, col1, col2));
    else
        return list_view_builder_ptr(new list_view_builder(hwnd_lv, col1, col2));
}

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

list_view_builder::list_view_builder(
    HWND hwnd_list_view,
    const std::wstring& column1_title,
    const std::wstring& column2_title) :
    hwnd_list_view_(hwnd_list_view),
    row_index_(-1),
    column1_title_(column1_title),
    column2_title_(column2_title)
{
}

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

list_view_builder::~list_view_builder()
{
}

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

void list_view_builder::build(statistic_group_list_t& gl)
{
    setup_list_view();

    statistic_group_list_t::iterator group_iter     = gl.begin();
    statistic_group_list_t::iterator group_iter_end = gl.end();

    for (/**/; group_iter != group_iter_end; ++group_iter)
    {
        statistic_item_list_t::iterator item_iter     = group_iter->second.begin();
        statistic_item_list_t::iterator item_iter_end = group_iter->second.end();

        if (item_iter != item_iter_end)
            insert_group(group_iter->first);

        for (/**/; item_iter != item_iter_end; ++item_iter)
            insert_item(item_iter->title_, item_iter->value_, item_iter->editable_);
    }
}

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

void list_view_builder::setup_list_view()
{
    HIMAGELIST h_ils = ImageList_Create(16,15,ILC_MASK, 7, 0);
    HBITMAP    h_bmp = LoadBitmap(GetModuleHandle(MODULE_NAME), MAKEINTRESOURCE(IDB_PROPERTY_IMAGES));
    ImageList_AddMasked(h_ils, h_bmp, RGB(255, 0, 255));

    ListView_SetImageList(hwnd_list_view_, h_ils, LVSIL_SMALL);

    std::wstring header = GetResString(IDS_PROPERTY);

    LVCOLUMN lvc;
    lvc.mask = LVCF_FMT |
               LVCF_WIDTH |
                LVCF_TEXT |
               LVCF_SUBITEM;

    lvc.iSubItem = 0;
    lvc.pszText  = const_cast<wchar_t*>(header.c_str());
    lvc.cx       = 120;
    lvc.fmt      = LVCFMT_LEFT;

    ListView_InsertColumn(hwnd_list_view_, 0, &lvc);
    lvc.iSubItem = 1;
    header = GetResString(IDS_PROPERTY_VALUE);
    lvc.pszText = const_cast<wchar_t*>(header.c_str());
    ListView_InsertColumn(hwnd_list_view_, 1, &lvc);
}

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

void list_view_builder::insert_group(const std::wstring& /*title*/)
{
    insert_item(L"", L"", false);
}

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

void list_view_builder::insert_item(const std::wstring& title, const std::wstring& value, bool is_editable)
{
    LVITEM lvi;

    lvi.iItem      = ++row_index_;
    lvi.iSubItem   = 0;
    lvi.mask       = LVIF_TEXT;
    lvi.state      = 0;
    lvi.cchTextMax = title.size() + 1;
    lvi.stateMask  = 0;
    lvi.pszText    = const_cast<wchar_t*>(title.c_str());

    if (title.length() > 0)
    {
        lvi.mask |= LVIF_IMAGE;

        if (is_editable)
            lvi.iImage = 4;
        else
            lvi.iImage = 3;
    }

    ListView_InsertItem(hwnd_list_view_, &lvi);

    lvi.mask     = LVIF_TEXT;
    lvi.iSubItem = 1;
    lvi.pszText  = const_cast<wchar_t*>(value.c_str());

    ListView_SetItem(hwnd_list_view_, &lvi);
}

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

HWND list_view_builder::get_list_view() const
{
    return hwnd_list_view_;
}

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

winxp_list_view_builder::winxp_list_view_builder(
    HWND hwnd_list_view,
    const std::wstring& column1_title,
    const std::wstring& column2_title) :
    list_view_builder(hwnd_list_view, column1_title, column2_title),
    group_count_(-1),
    row_count_(0)
{
}

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

void winxp_list_view_builder::setup_list_view()
{
    list_view_builder::setup_list_view();

    ListView_EnableGroupView(get_list_view(), TRUE);
}

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

void winxp_list_view_builder::insert_group(const std::wstring& name)
{
    LVGROUP lvg;

    ZeroMemory(&lvg, sizeof(lvg));

    lvg.cbSize    = sizeof(lvg);
    lvg.mask      = LVGF_HEADER | LVGF_STATE | LVGF_GROUPID;
    lvg.pszHeader = const_cast<wchar_t*>(name.c_str());
    lvg.cchHeader = name.size() + 1;
    lvg.iGroupId  = ++group_count_;
    lvg.state     = LVGS_NORMAL;
    lvg.uAlign    = LVGA_HEADER_CENTER;

    ListView_InsertGroup(get_list_view(), row_count_++, &lvg);
}

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

void winxp_list_view_builder::insert_item(
    const std::wstring& title, const std::wstring& value, bool is_editable)
{
    LVITEM lvi;

    lvi.iItem      = ++row_index_;
    lvi.iSubItem   = 0;
    lvi.mask       = LVIF_TEXT | LVIF_GROUPID;
    lvi.state      = 0;
    lvi.stateMask  = 0;
    lvi.pszText    = const_cast<wchar_t*>(title.c_str());
    lvi.iGroupId   = group_count_;

    if (title.length() > 0)
    {
        lvi.mask |= LVIF_IMAGE;

        if (is_editable)
            lvi.iImage = 4;
        else
            lvi.iImage = 3;
    }

    ListView_InsertItem(get_list_view(), &lvi);

    lvi.mask     = LVIF_TEXT;
    lvi.iSubItem = 1;
    lvi.pszText  = const_cast<wchar_t*>(value.c_str());

    ListView_SetItem(get_list_view(), &lvi);

    row_count_++;
}
<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2013, Stuart W Baker
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file StellarisCan.cxx
 * This file implements a can device driver layer specific to stellarisware.
 *
 * @author Stuart W. Baker
 * @date 3 January 2013
 */

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_can.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/can.h"
#include "driverlib/interrupt.h"
#include "driverlib/sysctl.h"

#include "StellarisDev.hxx"

/** Instance pointers help us get context from the interrupt handler(s) */
static StellarisCan *instances[2] = {NULL};

/** Constructor.
 * @param name name of this device instance in the file system
 * @param base base address of this device
 */
StellarisCan::StellarisCan(const char *name, unsigned long base)
    : Can(name),
      base(base),
      interrupt(0),
      txPending(false)
{
    switch (base)
    {
        default:
            HASSERT(0);
        case CAN0_BASE:
            MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN0);
            interrupt = INT_CAN0;
            instances[0] = this;
            break;
        case CAN1_BASE:
            MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN1);
            interrupt = INT_CAN1;
            instances[1] = this;
            break;
    }

    MAP_CANInit(base);
    MAP_CANBitRateSet(base, MAP_SysCtlClockGet(), 125000);
    MAP_CANIntEnable(base, CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS);

    tCANMsgObject can_message;
    can_message.ulMsgID = 0;
    can_message.ulMsgIDMask = 0;
    can_message.ulFlags = MSG_OBJ_RX_INT_ENABLE | MSG_OBJ_USE_ID_FILTER;
    can_message.ulMsgLen = 8;
    MAP_CANMessageSet(base, 1, &can_message, MSG_OBJ_TYPE_RX);
}

/** Enable use of the device.
 */
void StellarisCan::enable()
{
    MAP_IntEnable(interrupt);
    MAP_CANEnable(base);
}

/** Disable use of the device.
 */
void StellarisCan::disable()
{
    MAP_IntDisable(interrupt);
    MAP_CANDisable(base);
}

/* Try and transmit a message.
 */
void StellarisCan::tx_msg()
{
    if (txPending == false)
    {
        struct can_frame can_frame;
        if (os_mq_timedreceive(txQ, &can_frame, 0) == OS_MQ_NONE)
        {
            /* load the next message to transmit */
            tCANMsgObject can_message;
            can_message.ulMsgID = can_frame.can_id;
            can_message.ulMsgIDMask = 0;
            can_message.ulFlags = MSG_OBJ_TX_INT_ENABLE;
            if (can_frame.can_eff)
            {
                can_message.ulFlags |= MSG_OBJ_EXTENDED_ID;
            }
            if (can_frame.can_rtr)
            {
                can_message.ulFlags |= MSG_OBJ_REMOTE_FRAME;
            }
            can_message.ulMsgLen = can_frame.can_dlc;
            can_message.pucMsgData = data;
            memcpy(data, can_frame.data, can_frame.can_dlc);

            MAP_IntDisable(interrupt);
            MAP_CANMessageSet(base, 2, &can_message, MSG_OBJ_TYPE_TX);
            txPending = true;
            MAP_IntEnable(interrupt);
        }
    }
}

/** Common interrupt handler for all CAN devices.
 */
void StellarisCan::interrupt_handler()
{
    uint32_t status = MAP_CANIntStatus(base, CAN_INT_STS_CAUSE);
    int woken = false;

    if (status == CAN_INT_INTID_STATUS)
    {
        status = MAP_CANStatusGet(base, CAN_STS_CONTROL);
        /* some error occured */
        if (status & CAN_STATUS_BUS_OFF)
        {
            /* bus off error condition */
        }
        if (status & CAN_STATUS_EWARN)
        {
            /* One of the error counters has exceded a value of 96 */
        }
        if (status & CAN_STATUS_EPASS)
        {
            /* In error passive state */
        }
        if (status & CAN_STATUS_LEC_STUFF)
        {
            /* bit stuffing error occured */
        }
        if (status & CAN_STATUS_LEC_FORM)
        {
            /* format error occured in the fixed format part of the message */
        }
        if (status & CAN_STATUS_LEC_ACK)
        {
            /* a transmit message was not acked */
        }
        if (status & CAN_STATUS_LEC_CRC)
        {
            /* CRC error detected in received message */
        }
    }
    else if (status == 1)
    {
        /* rx data received */
        bool notify = false;
        tCANMsgObject can_message;
        uint8_t data[8];
        can_message.pucMsgData = data;

        /* Read a message from CAN and clear the interrupt source */
        MAP_CANMessageGet(base, 1, &can_message, 1 /* clear interrupt */);

        struct can_frame can_frame;
        can_frame.can_id = can_message.ulMsgID;
        can_frame.can_rtr = (can_message.ulFlags & MSG_OBJ_REMOTE_FRAME) ? 1 : 0;
        can_frame.can_eff = (can_message.ulFlags & MSG_OBJ_EXTENDED_ID) ? 1 : 0;
        can_frame.can_err = 0;
        can_frame.can_dlc = can_message.ulMsgLen;
        memcpy(can_frame.data, data, can_message.ulMsgLen);
        if (os_mq_num_pending_from_isr(rxQ) == 0)
        {
            notify = true;
        }
        if (os_mq_send_from_isr(rxQ, &can_frame, &woken) == OS_MQ_FULL)
        {
            overrunCount++;
        }
        /* wakeup anyone waiting for read active */
        if (notify && read_callback)
        {
            read_callback(readContext);
        }
    }
    else if (status == 2)
    {
        /* tx complete */
        MAP_CANIntClear(base, 2);

        struct can_frame can_frame;
        if (os_mq_receive_from_isr(txQ, &can_frame, &woken) == OS_MQ_NONE)
        {
            bool notify = false;
            if (os_mq_num_pending_from_isr(txQ) == (CAN_TX_BUFFER_SIZE - 1))
            {
                notify = true;
            }
            /* load the next message to transmit */
            tCANMsgObject can_message;
            can_message.ulMsgID = can_frame.can_id;
            can_message.ulMsgIDMask = 0;
            can_message.ulFlags = MSG_OBJ_TX_INT_ENABLE;
            if (can_frame.can_eff)
            {
                can_message.ulFlags |= MSG_OBJ_EXTENDED_ID;
            }
            if (can_frame.can_rtr)
            {
                can_message.ulFlags |= MSG_OBJ_REMOTE_FRAME;
            }
            can_message.ulMsgLen = can_frame.can_dlc;
            can_message.pucMsgData = data;
            memcpy(data, can_frame.data, can_frame.can_dlc);

            MAP_CANMessageSet(base, 2, &can_message, MSG_OBJ_TYPE_TX);
            /* wakeup anyone waiting for read active */
            if (notify && write_callback)
            {
                write_callback(writeContext);
            }
        }
        else
        {
            /* no more messages pending transmission */
            txPending = false;
        }
    }
    os_isr_exit_yield_test(woken);
}

/** This is the interrupt handler for the can0 device.
 */
void can0_interrupt_handler(void)
{
    if (instances[0])
    {
        instances[0]->interrupt_handler();
    }
}

#if 0
/** This is the interrupt handler for the can0 device.
 */
void can1_interrupt_handler(void)
{
    can_interrupt_handler(&can1);
}
#endif

<commit_msg>fixes broken build of c++ stellaris CAN driver.<commit_after>/** \copyright
 * Copyright (c) 2013, Stuart W Baker
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file StellarisCan.cxx
 * This file implements a can device driver layer specific to stellarisware.
 *
 * @author Stuart W. Baker
 * @date 3 January 2013
 */

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_can.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/can.h"
#include "driverlib/interrupt.h"
#include "driverlib/sysctl.h"

#include "StellarisDev.hxx"

/** Instance pointers help us get context from the interrupt handler(s) */
static StellarisCan *instances[2] = {NULL};

/** Constructor.
 * @param name name of this device instance in the file system
 * @param base base address of this device
 */
StellarisCan::StellarisCan(const char *name, unsigned long base)
    : Can(name),
      base(base),
      interrupt(0),
      txPending(false)
{
    switch (base)
    {
        default:
            HASSERT(0);
        case CAN0_BASE:
            MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN0);
            interrupt = INT_CAN0;
            instances[0] = this;
            break;
        case CAN1_BASE:
            MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN1);
            interrupt = INT_CAN1;
            instances[1] = this;
            break;
    }

    MAP_CANInit(base);
    MAP_CANBitRateSet(base, MAP_SysCtlClockGet(), 125000);
    MAP_CANIntEnable(base, CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS);

    tCANMsgObject can_message;
    can_message.ulMsgID = 0;
    can_message.ulMsgIDMask = 0;
    can_message.ulFlags = MSG_OBJ_RX_INT_ENABLE | MSG_OBJ_USE_ID_FILTER;
    can_message.ulMsgLen = 8;
    MAP_CANMessageSet(base, 1, &can_message, MSG_OBJ_TYPE_RX);
}

/** Enable use of the device.
 */
void StellarisCan::enable()
{
    MAP_IntEnable(interrupt);
    MAP_CANEnable(base);
}

/** Disable use of the device.
 */
void StellarisCan::disable()
{
    MAP_IntDisable(interrupt);
    MAP_CANDisable(base);
}

/* Try and transmit a message.
 */
void StellarisCan::tx_msg()
{
    if (txPending == false)
    {
        struct can_frame can_frame;
        if (os_mq_timedreceive(txQ, &can_frame, 0) == OS_MQ_NONE)
        {
            /* load the next message to transmit */
            tCANMsgObject can_message;
            can_message.ulMsgID = can_frame.can_id;
            can_message.ulMsgIDMask = 0;
            can_message.ulFlags = MSG_OBJ_TX_INT_ENABLE;
            if (can_frame.can_eff)
            {
                can_message.ulFlags |= MSG_OBJ_EXTENDED_ID;
            }
            if (can_frame.can_rtr)
            {
                can_message.ulFlags |= MSG_OBJ_REMOTE_FRAME;
            }
            can_message.ulMsgLen = can_frame.can_dlc;
            can_message.pucMsgData = data;
            memcpy(data, can_frame.data, can_frame.can_dlc);

            MAP_IntDisable(interrupt);
            MAP_CANMessageSet(base, 2, &can_message, MSG_OBJ_TYPE_TX);
            txPending = true;
            MAP_IntEnable(interrupt);
        }
    }
}

/** Common interrupt handler for all CAN devices.
 */
void StellarisCan::interrupt_handler()
{
    uint32_t status = MAP_CANIntStatus(base, CAN_INT_STS_CAUSE);
    int woken = false;

    if (status == CAN_INT_INTID_STATUS)
    {
        status = MAP_CANStatusGet(base, CAN_STS_CONTROL);
        /* some error occured */
        if (status & CAN_STATUS_BUS_OFF)
        {
            /* bus off error condition */
        }
        if (status & CAN_STATUS_EWARN)
        {
            /* One of the error counters has exceded a value of 96 */
        }
        if (status & CAN_STATUS_EPASS)
        {
            /* In error passive state */
        }
        if (status & CAN_STATUS_LEC_STUFF)
        {
            /* bit stuffing error occured */
        }
        if (status & CAN_STATUS_LEC_FORM)
        {
            /* format error occured in the fixed format part of the message */
        }
        if (status & CAN_STATUS_LEC_ACK)
        {
            /* a transmit message was not acked */
        }
        if (status & CAN_STATUS_LEC_CRC)
        {
            /* CRC error detected in received message */
        }
    }
    else if (status == 1)
    {
        /* rx data received */
        bool notify = false;
        tCANMsgObject can_message;
        uint8_t data[8];
        can_message.pucMsgData = data;

        /* Read a message from CAN and clear the interrupt source */
        MAP_CANMessageGet(base, 1, &can_message, 1 /* clear interrupt */);

        struct can_frame can_frame;
        can_frame.can_id = can_message.ulMsgID;
        can_frame.can_rtr = (can_message.ulFlags & MSG_OBJ_REMOTE_FRAME) ? 1 : 0;
        can_frame.can_eff = (can_message.ulFlags & MSG_OBJ_EXTENDED_ID) ? 1 : 0;
        can_frame.can_err = 0;
        can_frame.can_dlc = can_message.ulMsgLen;
        memcpy(can_frame.data, data, can_message.ulMsgLen);
        if (os_mq_num_pending_from_isr(rxQ) == 0)
        {
            notify = true;
        }
        if (os_mq_send_from_isr(rxQ, &can_frame, &woken) == OS_MQ_FULL)
        {
            overrunCount++;
        }
        /* wakeup anyone waiting for read active */
        if (notify && read_callback)
        {
            read_callback(readContext);
        }
    }
    else if (status == 2)
    {
        /* tx complete */
        MAP_CANIntClear(base, 2);

        struct can_frame can_frame;
        if (os_mq_receive_from_isr(txQ, &can_frame, &woken) == OS_MQ_NONE)
        {
            bool notify = false;
            if ((unsigned)os_mq_num_pending_from_isr(txQ) == (CAN_TX_BUFFER_SIZE - 1))
            {
                notify = true;
            }
            /* load the next message to transmit */
            tCANMsgObject can_message;
            can_message.ulMsgID = can_frame.can_id;
            can_message.ulMsgIDMask = 0;
            can_message.ulFlags = MSG_OBJ_TX_INT_ENABLE;
            if (can_frame.can_eff)
            {
                can_message.ulFlags |= MSG_OBJ_EXTENDED_ID;
            }
            if (can_frame.can_rtr)
            {
                can_message.ulFlags |= MSG_OBJ_REMOTE_FRAME;
            }
            can_message.ulMsgLen = can_frame.can_dlc;
            can_message.pucMsgData = data;
            memcpy(data, can_frame.data, can_frame.can_dlc);

            MAP_CANMessageSet(base, 2, &can_message, MSG_OBJ_TYPE_TX);
            /* wakeup anyone waiting for read active */
            if (notify && write_callback)
            {
                write_callback(writeContext);
            }
        }
        else
        {
            /* no more messages pending transmission */
            txPending = false;
        }
    }
    os_isr_exit_yield_test(woken);
}

/** This is the interrupt handler for the can0 device.
 */
void can0_interrupt_handler(void)
{
    if (instances[0])
    {
        instances[0]->interrupt_handler();
    }
}

#if 0
/** This is the interrupt handler for the can0 device.
 */
void can1_interrupt_handler(void)
{
    can_interrupt_handler(&can1);
}
#endif

<|endoftext|>


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

#include "base/command_line.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/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.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"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  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 wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

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

 protected:
  void RunTest(const std::string& test_name, const std::wstring& 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::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->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());
  }

  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_);
    BrowserClosedObserver close_observer(browser);
  }

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

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

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

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

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

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

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

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<commit_msg>Disable interactive_ui_tests::TestProfilerTab for now.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.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/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.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"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  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 wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

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

 protected:
  void RunTest(const std::string& test_name, const std::wstring& 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::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->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());
  }

  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_);
    BrowserClosedObserver close_observer(browser);
  }

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

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

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

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

// Tests profiler panel.
// Flaky, http://crbug.com/21108
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

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

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<|endoftext|>


<commit_before>#include <itomp_cio_planner/contact/contact_util.h>

using namespace std;

namespace itomp_cio_planner
{

double getContactActiveValue(unsigned int contact, unsigned int contact_point,
                             const std::vector<ContactVariables>& contact_variables)
{
    /*
    const double K1 = 10.0;
    const double K2 = 3.0;
    static double MIN_CI_COST = 0.5 * std::tanh(-K2) + 0.5;

    const Eigen::Matrix3d& orientation = exponential_map::ExponentialMapToRotation(contact_variables[contact].projected_orientation_);
    Eigen::Vector3d contact_normal = orientation.block(0, 2, 3, 1);

    Eigen::Vector3d point_contact_force = contact_variables[contact].getPointForce(contact_point);

    double f_norm = point_contact_force.dot(contact_normal);
    f_norm = std::abs(f_norm);

    double c = 0.5 * std::tanh(K1 * f_norm - K2) + 0.5 - MIN_CI_COST;
    */

    double c = contact_variables[contact].getPointForce(contact_point).squaredNorm();

    if (contact >= 2)
        c *= 10.0;

    return c;
}

}
<commit_msg>code cleanup<commit_after>#include <itomp_cio_planner/contact/contact_util.h>

using namespace std;

namespace itomp_cio_planner
{

double getContactActiveValue(unsigned int contact, unsigned int contact_point,
                             const std::vector<ContactVariables>& contact_variables)
{
    double c = contact_variables[contact].getPointForce(contact_point).squaredNorm();

    return c;
}

}
<|endoftext|>


<commit_before>//===-- PPCMCAsmInfo.cpp - PPC asm properties -------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the MCAsmInfoDarwin properties.
//
//===----------------------------------------------------------------------===//

#include "PPCMCAsmInfo.h"
using namespace llvm;

PPCMCAsmInfoDarwin::PPCMCAsmInfoDarwin(bool is64Bit) {
  PCSymbol = ".";
  CommentString = ";";
  ExceptionsType = ExceptionHandling::Dwarf;

  if (!is64Bit)
    Data64bitsDirective = 0;      // We can't emit a 64-bit unit in PPC32 mode.
  AssemblerDialect = 1;           // New-Style mnemonics.
  SupportsDebugInformation= true; // Debug information.
}

PPCLinuxMCAsmInfo::PPCLinuxMCAsmInfo(bool is64Bit) {
  CommentString = "#";
  GlobalPrefix = "";
  PrivateGlobalPrefix = ".L";
  UsedDirective = "\t# .no_dead_strip\t";
  WeakRefDirective = "\t.weak\t";

  // Uses '.section' before '.bss' directive
  UsesELFSectionDirectiveForBSS = true;

  // Debug Information
  AbsoluteDebugSectionOffsets = true;
  SupportsDebugInformation = true;

  PCSymbol = ".";

  // Set up DWARF directives
  HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)

  // Exceptions handling
  if (!is64Bit)
    ExceptionsType = ExceptionHandling::Dwarf;
  AbsoluteEHSectionOffsets = false;

  ZeroDirective = "\t.space\t";
  SetDirective = "\t.set";
  Data64bitsDirective = is64Bit ? "\t.quad\t" : 0;
  AlignmentIsInBytes = false;
  LCOMMDirective = "\t.lcomm\t";
  AssemblerDialect = 0;           // Old-Style mnemonics.
}

<commit_msg>remove unneeded directive set.<commit_after>//===-- PPCMCAsmInfo.cpp - PPC asm properties -------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the MCAsmInfoDarwin properties.
//
//===----------------------------------------------------------------------===//

#include "PPCMCAsmInfo.h"
using namespace llvm;

PPCMCAsmInfoDarwin::PPCMCAsmInfoDarwin(bool is64Bit) {
  PCSymbol = ".";
  CommentString = ";";
  ExceptionsType = ExceptionHandling::Dwarf;

  if (!is64Bit)
    Data64bitsDirective = 0;      // We can't emit a 64-bit unit in PPC32 mode.
  AssemblerDialect = 1;           // New-Style mnemonics.
  SupportsDebugInformation= true; // Debug information.
}

PPCLinuxMCAsmInfo::PPCLinuxMCAsmInfo(bool is64Bit) {
  CommentString = "#";
  GlobalPrefix = "";
  PrivateGlobalPrefix = ".L";
  WeakRefDirective = "\t.weak\t";

  // Uses '.section' before '.bss' directive
  UsesELFSectionDirectiveForBSS = true;

  // Debug Information
  AbsoluteDebugSectionOffsets = true;
  SupportsDebugInformation = true;

  PCSymbol = ".";

  // Set up DWARF directives
  HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)

  // Exceptions handling
  if (!is64Bit)
    ExceptionsType = ExceptionHandling::Dwarf;
  AbsoluteEHSectionOffsets = false;

  ZeroDirective = "\t.space\t";
  SetDirective = "\t.set";
  Data64bitsDirective = is64Bit ? "\t.quad\t" : 0;
  AlignmentIsInBytes = false;
  LCOMMDirective = "\t.lcomm\t";
  AssemblerDialect = 0;           // Old-Style mnemonics.
}

<|endoftext|>