<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/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";

class WorkerTest : public UILayoutTest {
 protected:
  virtual ~WorkerTest() { }

  void RunTest(const std::wstring& test_case) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  bool WaitForProcessCountToBe(int tabs, int workers) {
    // The 1 is for the browser process.
    int number_of_processes = 1 + workers +
        (UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
    // On Linux, we also have a zygote process and a sandbox host process.
    number_of_processes += 2;
#endif

    int cur_process_count;
    for (int i = 0; i < 10; ++i) {
      cur_process_count = GetBrowserProcessCount();
      if (cur_process_count == number_of_processes)
        return true;

      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }

    EXPECT_EQ(number_of_processes, cur_process_count);
    return false;
  }
};

TEST_F(WorkerTest, SingleWorker) {
  RunTest(L"single_worker.html");
}

TEST_F(WorkerTest, MultipleWorkers) {
  RunTest(L"multi_worker.html");
}

#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif

TEST_F(WorkerTest, WorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "stress-js-execution.html",
    "use-machine-stack.html",
    "worker-call.html",
    "worker-cloneport.html",
    "worker-close.html",
    "worker-constructor.html",
    "worker-context-gc.html",
    "worker-context-multi-port.html",
    "worker-event-listener.html",
    "worker-gc.html",
    // worker-lifecycle.html relies on layoutTestController.workerThreadCount
    // which is not currently implemented.
    // "worker-lifecycle.html",
    "worker-location.html",
    "worker-messageport.html",
    // Disabled after r27089 (WebKit merge), http://crbug.com/22947
    // "worker-messageport-gc.html",
    "worker-multi-port.html",
    "worker-navigator.html",
    "worker-replace-global-constructor.html",
    "worker-replace-self.html",
    "worker-script-error.html",
    "worker-terminate.html",
    // clearInterval() sometimes lets the timer continue to fire
    // http://code.google.com/p/chromium/issues/detail?id=25548
    // "worker-timeout.html"
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif

TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-constructor.html",
    "shared-worker-context-gc.html",
    "shared-worker-event-listener.html",
    "shared-worker-exception.html",
    "shared-worker-gc.html",
    // Lifecycle tests rely on layoutTestController.workerThreadCount which is
    // not currently implemented.
    //"shared-worker-frame-lifecycle.html",
    //"shared-worker-lifecycle.html",
    "shared-worker-load-error.html",
    "shared-worker-location.html",
    "shared-worker-name.html",
    "shared-worker-navigator.html",
    "shared-worker-replace-global-constructor.html",
    "shared-worker-replace-self.html",
    "shared-worker-script-error.html",
    "shared-worker-shared.html",
    "shared-worker-simple.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

TEST_F(WorkerTest, WorkerHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-importScripts.html",
    "shared-worker-redirect.html",
    // flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "worker-importScripts.html",
#endif
    "worker-redirect.html",
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "abort-exception-assert.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "close.html",
#endif
    // These tests (and the shared-worker versions below) are disabled due to
    // limitations in lighttpd (doesn't handle all of the HTTP methods).
    //"methods-async.html",
    //"methods.html",

    "shared-worker-close.html",
    // Disabled due to limitations in lighttpd (does not handle methods other
    // than GET/PUT/POST).
    //"shared-worker-methods-async.html",
    //"shared-worker-methods.html",
    "shared-worker-xhr-file-not-found.html",

    "xmlhttprequest-file-not-found.html"
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, MessagePorts) {
  static const char* kLayoutTestFiles[] = {
    "message-channel-gc.html",
    "message-channel-gc-2.html",
    "message-channel-gc-3.html",
    "message-channel-gc-4.html",
    "message-port.html",
    "message-port-clone.html",
    "message-port-constructor-for-deleted-document.html",
    "message-port-deleted-document.html",
    "message-port-deleted-frame.html",
    "message-port-inactive-document.html",
    "message-port-multi.html",
    "message-port-no-wrapper.html",
    // Only works with run-webkit-tests --leaks.
    //"message-channel-listener-circular-ownership.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("events");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // MessagePort tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));

  EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
            UITest::GetBrowserProcessCount());
}
#endif

TEST_F(WorkerTest, LimitTotal) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  int total_workers = WorkerService::kMaxWorkersWhenSeparate;

  int tab_count = (total_workers / max_workers_per_tab) + 1;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  for (int i = 1; i < tab_count; ++i)
    window->AppendTab(url);

  // Check that we didn't create more than the max number of workers.
  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));

  // Now close a page and check that the queued workers were started.
  tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));

  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Enable worker-timeout.html layout test. It's fixed upstream. TEST=worker-timeout.html BUG=25548 Review URL: http://codereview.chromium.org/396001<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/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";

class WorkerTest : public UILayoutTest {
 protected:
  virtual ~WorkerTest() { }

  void RunTest(const std::wstring& test_case) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"workers", test_case);
    ASSERT_TRUE(tab->NavigateToURL(url));

    std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
        kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
    ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
  }

  bool WaitForProcessCountToBe(int tabs, int workers) {
    // The 1 is for the browser process.
    int number_of_processes = 1 + workers +
        (UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
    // On Linux, we also have a zygote process and a sandbox host process.
    number_of_processes += 2;
#endif

    int cur_process_count;
    for (int i = 0; i < 10; ++i) {
      cur_process_count = GetBrowserProcessCount();
      if (cur_process_count == number_of_processes)
        return true;

      PlatformThread::Sleep(sleep_timeout_ms() / 10);
    }

    EXPECT_EQ(number_of_processes, cur_process_count);
    return false;
  }
};

TEST_F(WorkerTest, SingleWorker) {
  RunTest(L"single_worker.html");
}

TEST_F(WorkerTest, MultipleWorkers) {
  RunTest(L"multi_worker.html");
}

#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif

TEST_F(WorkerTest, WorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "stress-js-execution.html",
    "use-machine-stack.html",
    "worker-call.html",
    "worker-cloneport.html",
    "worker-close.html",
    "worker-constructor.html",
    "worker-context-gc.html",
    "worker-context-multi-port.html",
    "worker-event-listener.html",
    "worker-gc.html",
    // worker-lifecycle.html relies on layoutTestController.workerThreadCount
    // which is not currently implemented.
    // "worker-lifecycle.html",
    "worker-location.html",
    "worker-messageport.html",
    // Disabled after r27089 (WebKit merge), http://crbug.com/22947
    // "worker-messageport-gc.html",
    "worker-multi-port.html",
    "worker-navigator.html",
    "worker-replace-global-constructor.html",
    "worker-replace-self.html",
    "worker-script-error.html",
    "worker-terminate.html",
    "worker-timeout.html"
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

#if defined(OS_WIN)
// http://crbug.com/27636 - incorrect URL_MISMATCH exceptions sometimes get
// generated on the windows try bots.
#define SharedWorkerFastLayoutTests DISABLED_SharedWorkerFastLayoutTests
#endif

TEST_F(WorkerTest, SharedWorkerFastLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-constructor.html",
    "shared-worker-context-gc.html",
    "shared-worker-event-listener.html",
    "shared-worker-exception.html",
    "shared-worker-gc.html",
    // Lifecycle tests rely on layoutTestController.workerThreadCount which is
    // not currently implemented.
    //"shared-worker-frame-lifecycle.html",
    //"shared-worker-lifecycle.html",
    "shared-worker-load-error.html",
    "shared-worker-location.html",
    "shared-worker-name.html",
    "shared-worker-navigator.html",
    "shared-worker-replace-global-constructor.html",
    "shared-worker-replace-self.html",
    "shared-worker-script-error.html",
    "shared-worker-shared.html",
    "shared-worker-simple.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // Worker tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

TEST_F(WorkerTest, WorkerHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "shared-worker-importScripts.html",
    "shared-worker-redirect.html",
    // flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "worker-importScripts.html",
#endif
    "worker-redirect.html",
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
  static const char* kLayoutTestFiles[] = {
    "abort-exception-assert.html",
#if defined(OS_WIN)
    // Fails on the mac (and linux?):
    // http://code.google.com/p/chromium/issues/detail?id=22599
    "close.html",
#endif
    // These tests (and the shared-worker versions below) are disabled due to
    // limitations in lighttpd (doesn't handle all of the HTTP methods).
    //"methods-async.html",
    //"methods.html",

    "shared-worker-close.html",
    // Disabled due to limitations in lighttpd (does not handle methods other
    // than GET/PUT/POST).
    //"shared-worker-methods-async.html",
    //"shared-worker-methods.html",
    "shared-worker-xhr-file-not-found.html",

    "xmlhttprequest-file-not-found.html"
  };

  FilePath http_test_dir;
  http_test_dir = http_test_dir.AppendASCII("LayoutTests");
  http_test_dir = http_test_dir.AppendASCII("http");
  http_test_dir = http_test_dir.AppendASCII("tests");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
  worker_test_dir = worker_test_dir.AppendASCII("workers");
  InitializeForLayoutTest(http_test_dir, worker_test_dir, true);

  StartHttpServer(new_http_root_dir_);
  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], true);
  StopHttpServer();
}

TEST_F(WorkerTest, MessagePorts) {
  static const char* kLayoutTestFiles[] = {
    "message-channel-gc.html",
    "message-channel-gc-2.html",
    "message-channel-gc-3.html",
    "message-channel-gc-4.html",
    "message-port.html",
    "message-port-clone.html",
    "message-port-constructor-for-deleted-document.html",
    "message-port-deleted-document.html",
    "message-port-deleted-frame.html",
    "message-port-inactive-document.html",
    "message-port-multi.html",
    "message-port-no-wrapper.html",
    // Only works with run-webkit-tests --leaks.
    //"message-channel-listener-circular-ownership.html",
  };

  FilePath fast_test_dir;
  fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
  fast_test_dir = fast_test_dir.AppendASCII("fast");

  FilePath worker_test_dir;
  worker_test_dir = worker_test_dir.AppendASCII("events");
  InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);

  // MessagePort tests also rely on common files in js/resources.
  FilePath js_dir = fast_test_dir.AppendASCII("js");
  FilePath resource_dir;
  resource_dir = resource_dir.AppendASCII("resources");
  AddResourceForLayoutTest(js_dir, resource_dir);

  for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
    RunLayoutTest(kLayoutTestFiles[i], false);
}

// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));

  EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
            UITest::GetBrowserProcessCount());
}
#endif

TEST_F(WorkerTest, LimitTotal) {
  int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
  int total_workers = WorkerService::kMaxWorkersWhenSeparate;

  int tab_count = (total_workers / max_workers_per_tab) + 1;
  GURL url = GetTestUrl(L"workers", L"many_workers.html");
  url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURL(url));
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  for (int i = 1; i < tab_count; ++i)
    window->AppendTab(url);

  // Check that we didn't create more than the max number of workers.
  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));

  // Now close a page and check that the queued workers were started.
  tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));

  ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <type_traits>

struct A {};
struct B : A {};
struct C : B {};
struct D {};

int main(void) {
    std::cout << "is_const:" << std::endl;
    std::cout << "int: " << std::is_const<int>::value << std::endl;
    std::cout << "const int: " << std::is_const<const int>::value << std::endl;
    std::cout << "const int&: " << std::is_const<const int&>::value << std::endl;
    std::cout << "const int*: " << std::is_const<const int*>::value << std::endl;
    std::cout << "int* const: " << std::is_const<int* const>::value << std::endl;

    using DoublePointer = double*;
    std::cout << std::endl << "is_pointer:" << std::endl;
    std::cout << "int: " << std::is_pointer<int>::value << std::endl;
    std::cout << "int*: " << std::is_pointer<int*>::value << std::endl;
    std::cout << "double*: " << std::is_pointer<DoublePointer>::value << std::endl;

    std::cout << std::endl << "is_same:" << std::endl;
    std::cout << "<int, int>: " << std::is_same<int, int>::value << std::endl;
    std::cout << "<int, const int>: " << std::is_same<int, const int>::value << std::endl;
    std::cout << "<int*, int*>: " << std::is_same<int*, int*>::value << std::endl;
    std::cout << "<double*, double*>: " << std::is_same<DoublePointer, DoublePointer>::value << std::endl;

    std::cout << std::endl << "is_base_of:" << std::endl;
    std::cout << "<A, B>: " << std::is_base_of<A, B>::value << std::endl;
    std::cout << "<B, C>: " << std::is_base_of<B, C>::value << std::endl;
    std::cout << "<A, C>: " << std::is_base_of<A, C>::value << std::endl;
    std::cout << "<B, A>: " << std::is_base_of<B, A>::value << std::endl;
    std::cout << "<C, B>: " << std::is_base_of<C, B>::value << std::endl;
    std::cout << "<C, A>: " << std::is_base_of<C, A>::value << std::endl;
    std::cout << "<A, D>: " << std::is_base_of<A, D>::value << std::endl;
    std::cout << "<B, D>: " << std::is_base_of<B, D>::value << std::endl;
    std::cout << "<C, D>: " << std::is_base_of<C, D>::value << std::endl;

    std::cout << std::endl << "is_base_of:" << std::endl;
    std::cout << "<A*, B*>: " << std::is_convertible<A*, B*>::value << std::endl;
    std::cout << "<B*, C*>: " << std::is_convertible<B*, C*>::value << std::endl;
    std::cout << "<A*, C*>: " << std::is_convertible<A*, C*>::value << std::endl;
    std::cout << "<B*, A*>: " << std::is_convertible<B*, A*>::value << std::endl;
    std::cout << "<C*, B*>: " << std::is_convertible<C*, B*>::value << std::endl;
    std::cout << "<C*, A*>: " << std::is_convertible<C*, A*>::value << std::endl;

    return 0;
}

<commit_msg>modify on languages/program_on_cpp/In_Depth_C++_11/chapter3-type_traits/basic_traits.cpp<commit_after>#include <iostream>
#include <type_traits>

struct A {};
struct B : A {};
struct C : B {};
struct D {};

int main(void) {
    // basic trait judgement;
    std::cout << "is_const:" << std::endl;
    std::cout << "int: " << std::is_const<int>::value << std::endl;
    std::cout << "const int: " << std::is_const<const int>::value << std::endl;
    std::cout << "const int&: " << std::is_const<const int&>::value << std::endl;
    std::cout << "const int*: " << std::is_const<const int*>::value << std::endl;
    std::cout << "int* const: " << std::is_const<int* const>::value << std::endl;

    using DoublePointer = double*;
    std::cout << std::endl << "is_pointer:" << std::endl;
    std::cout << "int: " << std::is_pointer<int>::value << std::endl;
    std::cout << "int*: " << std::is_pointer<int*>::value << std::endl;
    std::cout << "double*: " << std::is_pointer<DoublePointer>::value << std::endl;

    // is_same trait;
    std::cout << std::endl << "is_same:" << std::endl;
    std::cout << "<int, int>: " << std::is_same<int, int>::value << std::endl;
    std::cout << "<int, const int>: " << std::is_same<int, const int>::value << std::endl;
    std::cout << "<int*, int*>: " << std::is_same<int*, int*>::value << std::endl;
    std::cout << "<double*, double*>: " << std::is_same<DoublePointer, DoublePointer>::value << std::endl;

    // is_base_of trait;
    std::cout << std::endl << "is_base_of:" << std::endl;
    std::cout << "<A, B>: " << std::is_base_of<A, B>::value << std::endl;
    std::cout << "<B, C>: " << std::is_base_of<B, C>::value << std::endl;
    std::cout << "<A, C>: " << std::is_base_of<A, C>::value << std::endl;
    std::cout << "<B, A>: " << std::is_base_of<B, A>::value << std::endl;
    std::cout << "<C, B>: " << std::is_base_of<C, B>::value << std::endl;
    std::cout << "<C, A>: " << std::is_base_of<C, A>::value << std::endl;
    std::cout << "<A, D>: " << std::is_base_of<A, D>::value << std::endl;
    std::cout << "<B, D>: " << std::is_base_of<B, D>::value << std::endl;
    std::cout << "<C, D>: " << std::is_base_of<C, D>::value << std::endl;

    // is_convertible trait;
    std::cout << std::endl << "is_convertible:" << std::endl;
    std::cout << "<A*, B*>: " << std::is_convertible<A*, B*>::value << std::endl;
    std::cout << "<B*, C*>: " << std::is_convertible<B*, C*>::value << std::endl;
    std::cout << "<A*, C*>: " << std::is_convertible<A*, C*>::value << std::endl;
    std::cout << "<B*, A*>: " << std::is_convertible<B*, A*>::value << std::endl;
    std::cout << "<C*, B*>: " << std::is_convertible<C*, B*>::value << std::endl;
    std::cout << "<C*, A*>: " << std::is_convertible<C*, A*>::value << std::endl;

    // convert traits;
    std::cout << std::endl << "trait convert:" << std::endl;
    std::cout << "<const int, add const to int>: "
        << std::is_same<const int, std::add_const<int>::type>::value << std::endl;
    std::cout << "<int, remove const from const int>: "
        << std::is_same<int, std::remove_const<const int>::type>::value << std::endl;
    std::cout << "<int*, add pointer to int>: "
        << std::is_same<int*, std::add_pointer<int>::type>::value << std::endl;
    std::cout << "<int, remove pointer from int*>: "
        << std::is_same<int, std::remove_pointer<int*>::type>::value << std::endl;
    std::cout << "<int&, add lvalue from int>: "
        << std::is_same<int&, std::add_lvalue_reference<int>::type>::value << std::endl;
    std::cout << "<int&&, add rvalue from int>: "
        << std::is_same<int&&, std::add_rvalue_reference<int>::type>::value << std::endl;
    std::cout << "<int, remove reference from int&>: "
        << std::is_same<int, std::remove_reference<int&>::type>::value << std::endl;
    std::cout << "<int, remove reference from int&&>: "
        << std::is_same<int, std::remove_reference<int&&>::type>::value << std::endl;
    std::cout << "<int, remove extent from int[]>: "
        << std::is_same<int, std::remove_extent<int[]>::type>::value << std::endl;
    std::cout << "<int[2], remove extent from int[][2]>: "
        << std::is_same<int[2], std::remove_extent<int[][2]>::type>::value << std::endl;
    std::cout << "<int[2][3], remove extent from int[][2][3]>: "
        << std::is_same<int[2][3], std::remove_extent<int[][2][3]>::type>::value << std::endl;
    std::cout << "<int, remove all extent from int[][2]>: "
        << std::is_same<int, std::remove_all_extents<int[][2]>::type>::value << std::endl;

    return 0;
}

<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "AudioOutput.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "routing/VoiceNavigationModel.h"

#include <QtCore/QDirIterator>
#include <phonon/MediaObject>
#include <phonon/MediaSource>
#include <phonon/AudioOutput>

namespace Marble
{

class AudioOutputPrivate
{
public:
    AudioOutput *q;

    Phonon::MediaObject *m_output;

    bool m_muted;

    VoiceNavigationModel m_voiceNavigation;

    AudioOutputPrivate( AudioOutput* parent );

    void audioOutputFinished();

    void setupAudio();

    void reset();

    void playInstructions();
};

AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) :
    q( parent ), m_output( 0 ), m_muted( false )
{
    QObject::connect( &m_voiceNavigation, SIGNAL(instructionChanged()),
                      q, SLOT(playInstructions()) );
}

void AudioOutputPrivate::audioOutputFinished()
{
    m_output->setCurrentSource( QString() );
    m_output->clearQueue();
}

void AudioOutputPrivate::setupAudio()
{
    if ( !m_output ) {
        m_output = new Phonon::MediaObject( q );
        Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q );
        Phonon::createPath( m_output, audioOutput );

        q->connect( m_output, SIGNAL(finished()), q, SLOT(audioOutputFinished()) );
    }
}

void AudioOutputPrivate::reset()
{
    if ( m_output ) {
        m_output->stop();
        m_output->setCurrentSource( QString() );
        m_output->clearQueue();
    }

    m_voiceNavigation.reset();
}

void AudioOutputPrivate::playInstructions()
{
    setupAudio();
    if ( m_output ) {
        m_output->enqueue( m_voiceNavigation.instruction() );
        m_output->play();
    }
}

AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ),
    d( new AudioOutputPrivate( this ) )
{
    setSoundEnabled( false );
}

AudioOutput::~AudioOutput()
{
    delete d;
}

void AudioOutput::update(const Route &route, qreal distanceManeuver, qreal distanceTarget, bool deviated )
{
    d->m_voiceNavigation.update( route, distanceManeuver, distanceTarget, deviated );
}

void AudioOutput::setMuted( bool muted )
{
    d->m_muted = muted;
}

bool AudioOutput::isMuted() const
{
    return d->m_muted;
}

void AudioOutput::setSpeaker( const QString &speaker )
{
    d->m_voiceNavigation.setSpeaker( speaker );
}

QString AudioOutput::speaker() const
{
    return d->m_voiceNavigation.speaker();
}

void AudioOutput::setSoundEnabled( bool enabled )
{
    d->m_voiceNavigation.setSpeakerEnabled( !enabled );
}

bool AudioOutput::isSoundEnabled() const
{
    return d->m_voiceNavigation.isSpeakerEnabled();
}

}

#include "AudioOutput.moc"
<commit_msg>fix speaker enabled toggling between starts of Marble<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "AudioOutput.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "routing/VoiceNavigationModel.h"

#include <QtCore/QDirIterator>
#include <phonon/MediaObject>
#include <phonon/MediaSource>
#include <phonon/AudioOutput>

namespace Marble
{

class AudioOutputPrivate
{
public:
    AudioOutput *q;

    Phonon::MediaObject *m_output;

    bool m_muted;

    VoiceNavigationModel m_voiceNavigation;

    AudioOutputPrivate( AudioOutput* parent );

    void audioOutputFinished();

    void setupAudio();

    void reset();

    void playInstructions();
};

AudioOutputPrivate::AudioOutputPrivate( AudioOutput* parent ) :
    q( parent ), m_output( 0 ), m_muted( false )
{
    QObject::connect( &m_voiceNavigation, SIGNAL(instructionChanged()),
                      q, SLOT(playInstructions()) );
}

void AudioOutputPrivate::audioOutputFinished()
{
    m_output->setCurrentSource( QString() );
    m_output->clearQueue();
}

void AudioOutputPrivate::setupAudio()
{
    if ( !m_output ) {
        m_output = new Phonon::MediaObject( q );
        Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput( Phonon::VideoCategory, q );
        Phonon::createPath( m_output, audioOutput );

        q->connect( m_output, SIGNAL(finished()), q, SLOT(audioOutputFinished()) );
    }
}

void AudioOutputPrivate::reset()
{
    if ( m_output ) {
        m_output->stop();
        m_output->setCurrentSource( QString() );
        m_output->clearQueue();
    }

    m_voiceNavigation.reset();
}

void AudioOutputPrivate::playInstructions()
{
    setupAudio();
    if ( m_output ) {
        m_output->enqueue( m_voiceNavigation.instruction() );
        m_output->play();
    }
}

AudioOutput::AudioOutput( QObject* parent ) : QObject( parent ),
    d( new AudioOutputPrivate( this ) )
{
    setSoundEnabled( false );
}

AudioOutput::~AudioOutput()
{
    delete d;
}

void AudioOutput::update(const Route &route, qreal distanceManeuver, qreal distanceTarget, bool deviated )
{
    d->m_voiceNavigation.update( route, distanceManeuver, distanceTarget, deviated );
}

void AudioOutput::setMuted( bool muted )
{
    d->m_muted = muted;
}

bool AudioOutput::isMuted() const
{
    return d->m_muted;
}

void AudioOutput::setSpeaker( const QString &speaker )
{
    d->m_voiceNavigation.setSpeaker( speaker );
}

QString AudioOutput::speaker() const
{
    return d->m_voiceNavigation.speaker();
}

void AudioOutput::setSoundEnabled( bool enabled )
{
    d->m_voiceNavigation.setSpeakerEnabled( !enabled );
}

bool AudioOutput::isSoundEnabled() const
{
    return !d->m_voiceNavigation.isSpeakerEnabled();
}

}

#include "AudioOutput.moc"
<|endoftext|>


<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "CompileConfig.h"
#include "Label.h"
#include "Engine.h"
#include "Renderer.h"
#include "Layer.h"
#include "Camera.h"
#include "BMFont.h"
#include "Cache.h"

namespace ouzel
{
    std::shared_ptr<Label> Label::create(const std::string& font, const std::string& text, const Vector2& textAnchor)
    {
        std::shared_ptr<Label> result = std::make_shared<Label>();

        if (!result->init(font, text, textAnchor))
        {
            result.reset();
        }

        return result;
    }

    Label::Label()
    {
        _shader = Engine::getInstance()->getCache()->getShader(SHADER_TEXTURE);

#ifdef OUZEL_PLATFORM_WINDOWS
        _uniModelViewProj = 0;
#else
        _uniModelViewProj = _shader->getVertexShaderConstantId("modelViewProj");
#endif
    }

    Label::~Label()
    {

    }

    bool Label::init(const std::string& font, const std::string& text, const Vector2& textAnchor)
    {
        _font.loadFont(font);
        _textAnchor = textAnchor;

        _texture = _font.getTexture();

        if (!_texture)
        {
            return false;
        }

        setText(text);

        return true;
    }

    void Label::draw()
    {
        Widget::draw();

        LayerPtr layer = _layer.lock();

        if (_shader && _texture && layer && _meshBuffer)
        {
            Engine::getInstance()->getRenderer()->activateTexture(_texture, 0);
            Engine::getInstance()->getRenderer()->activateShader(_shader);

            Matrix4 modelViewProj = layer->getCamera()->getViewProjection() * _transform;

            _shader->setVertexShaderConstant(_uniModelViewProj, { modelViewProj });

            Engine::getInstance()->getRenderer()->drawMeshBuffer(_meshBuffer);
        }
    }

    void Label::setText(const std::string& text)
    {
        _text = text;

        if (_text.empty())
        {
            _meshBuffer.reset();
        }
        else
        {
            _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor);
        }
    }

    void Label::setColor(const Color& color)
    {
        _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor);
    }
}
<commit_msg>Fix label color setter<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "CompileConfig.h"
#include "Label.h"
#include "Engine.h"
#include "Renderer.h"
#include "Layer.h"
#include "Camera.h"
#include "BMFont.h"
#include "Cache.h"

namespace ouzel
{
    std::shared_ptr<Label> Label::create(const std::string& font, const std::string& text, const Vector2& textAnchor)
    {
        std::shared_ptr<Label> result = std::make_shared<Label>();

        if (!result->init(font, text, textAnchor))
        {
            result.reset();
        }

        return result;
    }

    Label::Label()
    {
        _shader = Engine::getInstance()->getCache()->getShader(SHADER_TEXTURE);

#ifdef OUZEL_PLATFORM_WINDOWS
        _uniModelViewProj = 0;
#else
        _uniModelViewProj = _shader->getVertexShaderConstantId("modelViewProj");
#endif
    }

    Label::~Label()
    {

    }

    bool Label::init(const std::string& font, const std::string& text, const Vector2& textAnchor)
    {
        _font.loadFont(font);
        _textAnchor = textAnchor;

        _texture = _font.getTexture();

        if (!_texture)
        {
            return false;
        }

        setText(text);

        return true;
    }

    void Label::draw()
    {
        Widget::draw();

        LayerPtr layer = _layer.lock();

        if (_shader && _texture && layer && _meshBuffer)
        {
            Engine::getInstance()->getRenderer()->activateTexture(_texture, 0);
            Engine::getInstance()->getRenderer()->activateShader(_shader);

            Matrix4 modelViewProj = layer->getCamera()->getViewProjection() * _transform;

            _shader->setVertexShaderConstant(_uniModelViewProj, { modelViewProj });

            Engine::getInstance()->getRenderer()->drawMeshBuffer(_meshBuffer);
        }
    }

    void Label::setText(const std::string& text)
    {
        _text = text;

        if (_text.empty())
        {
            _meshBuffer.reset();
        }
        else
        {
            _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor);
        }
    }

    void Label::setColor(const Color& color)
    {
        _color = color;
        _meshBuffer = _font.createMeshBuffer(_text, _color, _textAnchor);
    }
}
<|endoftext|>


<commit_before>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_impl.h"
#include "browser/inspectable_web_contents_view_delegate.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();

    if (shell->GetDelegate())
      icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
  }
  virtual ~DevToolsWindowDelegate() {}

  void SetWindowTitle(const base::string16& title) { title_ = title; }

  // views::WidgetDelegate:
  void DeleteDelegate() override { delete this; }
  views::View* GetInitiallyFocusedView() override { return view_; }
  bool CanResize() const override { return true; }
  bool CanMaximize() const override { return true; }
  bool CanMinimize() const override { return true; }
  base::string16 GetWindowTitle() const override { return title_; }
  gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); }
  gfx::ImageSkia GetWindowIcon() override { return icon_; }
  views::Widget* GetWidget() override { return widget_; }
  const views::Widget* GetWidget() const override { return widget_; }
  views::View* GetContentsView() override { return view_; }
  views::ClientView* CreateClientView(views::Widget* widget) override { return this; }

  // views::ClientView:
  bool CanClose() override {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;
  gfx::ImageSkia icon_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(nullptr),
      contents_web_view_(nullptr),
      devtools_web_view_(new views::WebView(nullptr)),
      devtools_visible_(false),
      devtools_window_delegate_(nullptr) {
  set_owned_by_client();

  if (inspectable_web_contents_->GetWebContents()->GetNativeView()) {
    views::WebView* contents_web_view = new views::WebView(nullptr);
    contents_web_view->SetWebContents(inspectable_web_contents_->GetWebContents());
    contents_web_view_ = contents_web_view;
  } else {
    contents_web_view_ = new views::Label(L"No content under offscreen mode");
  }

  devtools_web_view_->SetVisible(false);
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(
        inspectable_web_contents_->GetDevToolsWebContents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(
        inspectable_web_contents_->GetDevToolsWebContents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = nullptr;
    devtools_window_delegate_ = nullptr;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
  if (devtools_window_web_view_)
    return devtools_window_web_view_->HasFocus();
  else if (devtools_web_view_)
    return devtools_web_view_->HasFocus();
  else
    return false;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);
    devtools_window_delegate_ = new DevToolsWindowDelegate(this,
                                                           devtools_window_web_view_,
                                                           devtools_window_.get());

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = GetDevToolsWindowDelegate();
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();

#if defined(USE_X11)
    params.wm_role_name = "devtools";
    if (GetDelegate())
      GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class);
#endif

    devtools_window_->Init(params);
    devtools_window_->UpdateWindowIcon();
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::SetTitle(const base::string16& title) {
  if (devtools_window_) {
    GetDevToolsWindowDelegate()->SetWindowTitle(title);
    devtools_window_->UpdateWindowTitle();
  }
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<commit_msg>Fix building under linux<commit_after>#include "browser/views/inspectable_web_contents_view_views.h"

#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_impl.h"
#include "browser/inspectable_web_contents_view_delegate.h"

#include "base/strings/utf_string_conversions.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"

namespace brightray {

namespace {

class DevToolsWindowDelegate : public views::ClientView,
                               public views::WidgetDelegate {
 public:
  DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
                         views::View* view,
                         views::Widget* widget)
      : views::ClientView(widget, view),
        shell_(shell),
        view_(view),
        widget_(widget),
        title_(base::ASCIIToUTF16("Developer Tools")) {
    // A WidgetDelegate should be deleted on DeleteDelegate.
    set_owned_by_client();

    if (shell->GetDelegate())
      icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
  }
  virtual ~DevToolsWindowDelegate() {}

  void SetWindowTitle(const base::string16& title) { title_ = title; }

  // views::WidgetDelegate:
  void DeleteDelegate() override { delete this; }
  views::View* GetInitiallyFocusedView() override { return view_; }
  bool CanResize() const override { return true; }
  bool CanMaximize() const override { return true; }
  bool CanMinimize() const override { return true; }
  base::string16 GetWindowTitle() const override { return title_; }
  gfx::ImageSkia GetWindowAppIcon() override { return GetWindowIcon(); }
  gfx::ImageSkia GetWindowIcon() override { return icon_; }
  views::Widget* GetWidget() override { return widget_; }
  const views::Widget* GetWidget() const override { return widget_; }
  views::View* GetContentsView() override { return view_; }
  views::ClientView* CreateClientView(views::Widget* widget) override { return this; }

  // views::ClientView:
  bool CanClose() override {
    shell_->inspectable_web_contents()->CloseDevTools();
    return false;
  }

 private:
  InspectableWebContentsViewViews* shell_;
  views::View* view_;
  views::Widget* widget_;
  base::string16 title_;
  gfx::ImageSkia icon_;

  DISALLOW_COPY_AND_ASSIGN(DevToolsWindowDelegate);
};

}  // namespace

InspectableWebContentsView* CreateInspectableContentsView(
    InspectableWebContentsImpl* inspectable_web_contents) {
  return new InspectableWebContentsViewViews(inspectable_web_contents);
}

InspectableWebContentsViewViews::InspectableWebContentsViewViews(
    InspectableWebContentsImpl* inspectable_web_contents)
    : inspectable_web_contents_(inspectable_web_contents),
      devtools_window_web_view_(nullptr),
      contents_web_view_(nullptr),
      devtools_web_view_(new views::WebView(nullptr)),
      devtools_visible_(false),
      devtools_window_delegate_(nullptr) {
  set_owned_by_client();

  if (inspectable_web_contents_->GetWebContents()->GetNativeView()) {
    views::WebView* contents_web_view = new views::WebView(nullptr);
    contents_web_view->SetWebContents(inspectable_web_contents_->GetWebContents());
    contents_web_view_ = contents_web_view;
  } else {
    contents_web_view_ = new views::Label(base::ASCIIToUTF16("No content under offscreen mode"));
  }

  devtools_web_view_->SetVisible(false);
  AddChildView(devtools_web_view_);
  AddChildView(contents_web_view_);
}

InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
  if (devtools_window_)
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
}

views::View* InspectableWebContentsViewViews::GetView() {
  return this;
}

views::View* InspectableWebContentsViewViews::GetWebView() {
  return contents_web_view_;
}

void InspectableWebContentsViewViews::ShowDevTools() {
  if (devtools_visible_)
    return;

  devtools_visible_ = true;
  if (devtools_window_) {
    devtools_window_web_view_->SetWebContents(
        inspectable_web_contents_->GetDevToolsWebContents());
    devtools_window_->SetBounds(inspectable_web_contents()->GetDevToolsBounds());
    devtools_window_->Show();
  } else {
    devtools_web_view_->SetVisible(true);
    devtools_web_view_->SetWebContents(
        inspectable_web_contents_->GetDevToolsWebContents());
    devtools_web_view_->RequestFocus();
    Layout();
  }
}

void InspectableWebContentsViewViews::CloseDevTools() {
  if (!devtools_visible_)
    return;

  devtools_visible_ = false;
  if (devtools_window_) {
    inspectable_web_contents()->SaveDevToolsBounds(devtools_window_->GetWindowBoundsInScreen());
    devtools_window_.reset();
    devtools_window_web_view_ = nullptr;
    devtools_window_delegate_ = nullptr;
  } else {
    devtools_web_view_->SetVisible(false);
    devtools_web_view_->SetWebContents(NULL);
    Layout();
  }
}

bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
  return devtools_visible_;
}

bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
  if (devtools_window_web_view_)
    return devtools_window_web_view_->HasFocus();
  else if (devtools_web_view_)
    return devtools_web_view_->HasFocus();
  else
    return false;
}

void InspectableWebContentsViewViews::SetIsDocked(bool docked) {
  CloseDevTools();

  if (!docked) {
    devtools_window_.reset(new views::Widget);
    devtools_window_web_view_ = new views::WebView(NULL);
    devtools_window_delegate_ = new DevToolsWindowDelegate(this,
                                                           devtools_window_web_view_,
                                                           devtools_window_.get());

    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.delegate = GetDevToolsWindowDelegate();
    params.bounds = inspectable_web_contents()->GetDevToolsBounds();

#if defined(USE_X11)
    params.wm_role_name = "devtools";
    if (GetDelegate())
      GetDelegate()->GetDevToolsWindowWMClass(&params.wm_class_name, &params.wm_class_class);
#endif

    devtools_window_->Init(params);
    devtools_window_->UpdateWindowIcon();
  }

  ShowDevTools();
}

void InspectableWebContentsViewViews::SetContentsResizingStrategy(
    const DevToolsContentsResizingStrategy& strategy) {
  strategy_.CopyFrom(strategy);
  Layout();
}

void InspectableWebContentsViewViews::SetTitle(const base::string16& title) {
  if (devtools_window_) {
    GetDevToolsWindowDelegate()->SetWindowTitle(title);
    devtools_window_->UpdateWindowTitle();
  }
}

void InspectableWebContentsViewViews::Layout() {
  if (!devtools_web_view_->visible()) {
    contents_web_view_->SetBoundsRect(GetContentsBounds());
    return;
  }

  gfx::Size container_size(width(), height());
  gfx::Rect new_devtools_bounds;
  gfx::Rect new_contents_bounds;
  ApplyDevToolsContentsResizingStrategy(strategy_, container_size,
      &new_devtools_bounds, &new_contents_bounds);

  // DevTools cares about the specific position, so we have to compensate RTL
  // layout here.
  new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
  new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));

  devtools_web_view_->SetBoundsRect(new_devtools_bounds);
  contents_web_view_->SetBoundsRect(new_contents_bounds);
}

}  // namespace brightray
<|endoftext|>


<commit_before>#include "chacha20.h"

static Nan::Persistent<v8::FunctionTemplate> chacha20_constructor;

ChaCha20::ChaCha20() {}

ChaCha20::~ChaCha20() {}

void ChaCha20::Init(v8::Local<v8::Object> &target) {
  Nan::HandleScope scope;

  v8::Local<v8::FunctionTemplate> tpl =
    Nan::New<v8::FunctionTemplate>(ChaCha20::New);

  chacha20_constructor.Reset(tpl);

  tpl->SetClassName(Nan::New("ChaCha20").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(tpl, "init", ChaCha20::Init);
  Nan::SetPrototypeMethod(tpl, "initIV", ChaCha20::InitIV);
  Nan::SetPrototypeMethod(tpl, "initKey", ChaCha20::InitKey);
  Nan::SetPrototypeMethod(tpl, "encrypt", ChaCha20::Encrypt);
  Nan::SetPrototypeMethod(tpl, "setCounter", ChaCha20::SetCounter);
  Nan::SetPrototypeMethod(tpl, "getCounter", ChaCha20::GetCounter);

  v8::Local<v8::FunctionTemplate> ctor =
      Nan::New<v8::FunctionTemplate>(chacha20_constructor);

  target->Set(Nan::New("ChaCha20").ToLocalChecked(), ctor->GetFunction());
}

NAN_METHOD(ChaCha20::New) {
  ChaCha20* chacha = new ChaCha20();
  chacha->Wrap(info.This());
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(ChaCha20::Init) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> key = info[0].As<v8::Object>();

  if (!key->IsNull() && !key->IsUndefined())
    chacha->InitKey(key);

  if (info.Length() > 1) {
    v8::Local<v8::Object> iv = info[1].As<v8::Object>();
    if (!iv->IsNull() && !iv->IsUndefined()) {
      v8::Local<v8::Value> num = Nan::New<v8::Number>(0);
      if (info.Length() > 2 && info[2]->IsNumber())
        num = v8::Local<v8::Value>::Cast(info[2]);
      chacha->InitIV(iv, num);
    }
  }
}

void ChaCha20::InitKey(v8::Local<v8::Object> &key) {
  Nan::HandleScope scope;

  if (!node::Buffer::HasInstance(key))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  const uint8_t *data = (uint8_t *)node::Buffer::Data(key);
  size_t len = node::Buffer::Length(key);

  if (len != 32)
    return Nan::ThrowError("Invalid key size.");

  chacha20_keysetup(&ctx, data, 32);
}

void ChaCha20::InitIV(v8::Local<v8::Object> &iv, v8::Local<v8::Value> &num) {
  Nan::HandleScope scope;

  if (!node::Buffer::HasInstance(iv))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  uint32_t ctr = 0;

  if (num->IsNumber())
    ctr = v8::Local<v8::Integer>::Cast(num)->Value();

  const uint8_t *data = (uint8_t *)node::Buffer::Data(iv);
  size_t len = node::Buffer::Length(iv);

  if (len != 8 && len != 12)
    return Nan::ThrowError("Invalid IV size.");

  chacha20_ivsetup(&ctx, (uint8_t *)data, (uint8_t)len);
  chacha20_counter_set(&ctx, ctr);
}

NAN_METHOD(ChaCha20::InitIV) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  v8::Local<v8::Value> num = Nan::New<v8::Number>(0);
  if (info.Length() > 1)
    num = v8::Local<v8::Value>::Cast(info[1]);

  chacha->InitIV(buf, num);
}

NAN_METHOD(ChaCha20::InitKey) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  if (!node::Buffer::HasInstance(buf))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  chacha->InitKey(buf);
}

NAN_METHOD(ChaCha20::Encrypt) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.update() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  if (!node::Buffer::HasInstance(buf))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  const uint8_t *data = (uint8_t *)node::Buffer::Data(buf);
  size_t len = node::Buffer::Length(buf);

  chacha20_encrypt(&chacha->ctx, (uint8_t *)data, (uint8_t *)data, len);

  info.GetReturnValue().Set(buf);
}

NAN_METHOD(ChaCha20::SetCounter) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.setCounter() requires arguments.");

  v8::Local<v8::Object> num = info[0].As<v8::Object>();

  if (!num->IsNumber())
    return Nan::ThrowError("First argument must be a number.");

  uint64_t ctr = v8::Local<v8::Integer>::Cast(num)->Value();
  chacha20_counter_set(&chacha->ctx, ctr);
}

NAN_METHOD(ChaCha20::GetCounter) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());
  info.GetReturnValue().Set(
    Nan::New<v8::Number>((double)chacha20_counter_get(&chacha->ctx)));
}
<commit_msg>chacha20: fix 64 bit counters.<commit_after>#include "chacha20.h"

static Nan::Persistent<v8::FunctionTemplate> chacha20_constructor;

ChaCha20::ChaCha20() {}

ChaCha20::~ChaCha20() {}

void ChaCha20::Init(v8::Local<v8::Object> &target) {
  Nan::HandleScope scope;

  v8::Local<v8::FunctionTemplate> tpl =
    Nan::New<v8::FunctionTemplate>(ChaCha20::New);

  chacha20_constructor.Reset(tpl);

  tpl->SetClassName(Nan::New("ChaCha20").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(tpl, "init", ChaCha20::Init);
  Nan::SetPrototypeMethod(tpl, "initIV", ChaCha20::InitIV);
  Nan::SetPrototypeMethod(tpl, "initKey", ChaCha20::InitKey);
  Nan::SetPrototypeMethod(tpl, "encrypt", ChaCha20::Encrypt);
  Nan::SetPrototypeMethod(tpl, "setCounter", ChaCha20::SetCounter);
  Nan::SetPrototypeMethod(tpl, "getCounter", ChaCha20::GetCounter);

  v8::Local<v8::FunctionTemplate> ctor =
      Nan::New<v8::FunctionTemplate>(chacha20_constructor);

  target->Set(Nan::New("ChaCha20").ToLocalChecked(), ctor->GetFunction());
}

NAN_METHOD(ChaCha20::New) {
  ChaCha20* chacha = new ChaCha20();
  chacha->Wrap(info.This());
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(ChaCha20::Init) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> key = info[0].As<v8::Object>();

  if (!key->IsNull() && !key->IsUndefined())
    chacha->InitKey(key);

  if (info.Length() > 1) {
    v8::Local<v8::Object> iv = info[1].As<v8::Object>();
    if (!iv->IsNull() && !iv->IsUndefined()) {
      v8::Local<v8::Value> num = Nan::New<v8::Number>(0);
      if (info.Length() > 2 && info[2]->IsNumber())
        num = v8::Local<v8::Value>::Cast(info[2]);
      chacha->InitIV(iv, num);
    }
  }
}

void
ChaCha20::InitKey(v8::Local<v8::Object> &key) {
  Nan::HandleScope scope;

  if (!node::Buffer::HasInstance(key))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  const uint8_t *data = (uint8_t *)node::Buffer::Data(key);
  size_t len = node::Buffer::Length(key);

  if (len != 32)
    return Nan::ThrowError("Invalid key size.");

  chacha20_keysetup(&ctx, data, 32);
}

void
ChaCha20::InitIV(v8::Local<v8::Object> &iv, v8::Local<v8::Value> &num) {
  Nan::HandleScope scope;

  if (!node::Buffer::HasInstance(iv))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  const uint8_t *data = (uint8_t *)node::Buffer::Data(iv);
  size_t len = node::Buffer::Length(iv);

  if (len != 8 && len != 12)
    return Nan::ThrowError("Invalid IV size.");

  uint64_t ctr = 0;

  if (num->IsNumber())
    ctr = (uint64_t)v8::Local<v8::Integer>::Cast(num)->Value();

  chacha20_ivsetup(&ctx, (uint8_t *)data, (uint8_t)len);
  chacha20_counter_set(&ctx, ctr);
}

NAN_METHOD(ChaCha20::InitIV) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  v8::Local<v8::Value> num = Nan::New<v8::Number>(0);
  if (info.Length() > 1)
    num = v8::Local<v8::Value>::Cast(info[1]);

  chacha->InitIV(buf, num);
}

NAN_METHOD(ChaCha20::InitKey) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.init() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  if (!node::Buffer::HasInstance(buf))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  chacha->InitKey(buf);
}

NAN_METHOD(ChaCha20::Encrypt) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.update() requires arguments.");

  v8::Local<v8::Object> buf = info[0].As<v8::Object>();

  if (!node::Buffer::HasInstance(buf))
    return Nan::ThrowTypeError("First argument must be a Buffer.");

  const uint8_t *data = (uint8_t *)node::Buffer::Data(buf);
  size_t len = node::Buffer::Length(buf);

  chacha20_encrypt(&chacha->ctx, (uint8_t *)data, (uint8_t *)data, len);

  info.GetReturnValue().Set(buf);
}

NAN_METHOD(ChaCha20::SetCounter) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());

  if (info.Length() < 1)
    return Nan::ThrowError("chacha20.setCounter() requires arguments.");

  v8::Local<v8::Object> num = info[0].As<v8::Object>();

  if (!num->IsNumber())
    return Nan::ThrowError("First argument must be a number.");

  uint64_t ctr = v8::Local<v8::Integer>::Cast(num)->Value();
  chacha20_counter_set(&chacha->ctx, ctr);
}

NAN_METHOD(ChaCha20::GetCounter) {
  ChaCha20* chacha = ObjectWrap::Unwrap<ChaCha20>(info.Holder());
  info.GetReturnValue().Set(
    Nan::New<v8::Number>((double)chacha20_counter_get(&chacha->ctx)));
}
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
#endif
#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#include <vector>
#include <string>
#include <map>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>

# include <dune/pymor/parameters/base.hh>

# include <dune/hdd/linearelliptic/testcases/OS2014.hh>
# include <dune/hdd/linearelliptic/testcases/spe10.hh>

# include "linearelliptic-block-swipdg.hh"
# include "linearelliptic-block-swipdg-expectations.hh"

using namespace Dune;
using namespace HDD;

typedef ALUGrid< 2, 2, simplex, conforming > GridType;

typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType;
typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType >             SmoothStudyType;

typedef LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > MultiscaleTestCaseType;
typedef LinearElliptic::Tests::BlockSWIPDGStudy< MultiscaleTestCaseType >   MultiscaleStudyType;

template< class TestCaseType >
void print_parameter_information(const TestCaseType& test_case)
{
  const auto& parameters = test_case.parameters();
  const auto& problem = test_case.problem();
  for (auto parameter : parameters)
    EXPECT_EQ(parameter.second.type(), problem.parameter_type())
        << "          id: " << parameter.first << ", parameter: " << parameter.second;
  const auto& diffusion_factor = *problem.diffusion_factor();
  const auto& diffusion_tensor = *problem.diffusion_tensor();
  const auto& force = *problem.force();
  const auto& dirichlet = *problem.dirichlet();
  const auto& neumann = *problem.neumann();
  EXPECT_TRUE(diffusion_factor.parametric());
  EXPECT_FALSE(diffusion_tensor.parametric());
  EXPECT_FALSE(force.parametric());
  EXPECT_FALSE(dirichlet.parametric());
  EXPECT_FALSE(neumann.parametric());
  DSC_LOG_INFO << "| mu            = " << parameters.at("mu") << "\n"
               << "| mu_bar        = " << parameters.at("mu_bar") << "\n"
               << "| mu_hat        = " << parameters.at("mu_hat") << "\n"
               << "| mu_minimizing = " << parameters.at("mu_minimizing") << "\n";
  const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat"));
  const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat"));
  DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2    = " << std::setprecision(2) << std::scientific
                                                   << 1.0/std::sqrt(alpha) << "\n"
               << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific
                                                   << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n"
               << "+\n";
} // ... print_parameter_information(...)

template< class TestCaseType, class StudyType >
void run_eoc_study(const std::string partitioning,
                   const std::vector< std::string >& only_these_norms,
                   const std::map< std::string, Pymor::Parameter >& parameters,
                   const bool print_header,
                   const std::string visualization)
{
  const TestCaseType test_case(parameters, partitioning);
  if (print_header)
    test_case.print_header(DSC_LOG_INFO);
  print_parameter_information(test_case);
  StudyType study(test_case, only_these_norms, {}, visualization);
  Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO));
} // ... run_eoc_study(...)

TEST(OS2014_parametric_convergence_study, eta_DF_comparison)
{
  const std::string partitioning = "[4 4 1]";
  const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014",
                                                       "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"};
  const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_eta_DF_comparison";
  bool print_header = true;
  for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) {
    const auto mu_hat = Pymor::Parameter("mu", mu_hat_value);
    for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) {
      const auto mu = Pymor::Parameter("mu", mu_value);
      const auto mu_bar = mu;
      run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning,
                                                           only_these_norms,
                                                           {{"mu_hat",        mu_hat},
                                                            {"mu_bar",        mu_bar},
                                                            {"mu",            mu},
                                                            {"mu_minimizing", Pymor::Parameter("mu", 0.1)}},
                                                           print_header,
                                                           visualization_prefix);
      if (print_header)
        print_header = false;
    }
  }
} // TEST(OS2014_parametric_convergence_study, eta_DF_comparison)

TEST(OS2014_parametric_convergence_study, multiscale)
{
  const std::string partitioning = "[20 4 1]";
  const std::vector< std::string > only_these_norms = {"energy_mu", "eta_OS2014", "eta_OS2014_*"};
  const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_spe10_model1";
  bool print_header = true;
  for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) {
    const auto mu_hat = Pymor::Parameter("mu", mu_hat_value);
    for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) {
      const auto mu = Pymor::Parameter("mu", mu_value);
      const auto mu_bar = mu;
      run_eoc_study< MultiscaleTestCaseType, MultiscaleStudyType >(partitioning,
                                                                   only_these_norms,
                                                                   {{"mu_hat",        mu_hat},
                                                                    {"mu_bar",        mu_bar},
                                                                    {"mu",            mu},
                                                                    {"mu_minimizing", Pymor::Parameter("mu", 0.1)}},
                                                                   print_header,
                                                                   visualization_prefix);
      if (print_header)
        print_header = false;
    }
  }
} // TEST(OS2014_parametric_convergence_study, multiscale)

extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >;
extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< MultiscaleTestCaseType >;

#else // HAVE_ALUGRID

TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {}
TEST(DISABLED_OS2014_parametric_convergence_study, multiscale) {}

#endif // HAVE_ALUGRID
<commit_msg>[test.OS2014...] drop mu_minimizing<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS
# define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS 1
#endif
#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#include <vector>
#include <string>
#include <map>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>

# include <dune/pymor/parameters/base.hh>

# include <dune/hdd/linearelliptic/testcases/OS2014.hh>
# include <dune/hdd/linearelliptic/testcases/spe10.hh>

# include "linearelliptic-block-swipdg.hh"
# include "linearelliptic-block-swipdg-expectations.hh"

using namespace Dune;
using namespace HDD;

typedef ALUGrid< 2, 2, simplex, conforming > GridType;

typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType;
typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType >             SmoothStudyType;

typedef LinearElliptic::TestCases::Spe10::ParametricBlockModel1< GridType > MultiscaleTestCaseType;
typedef LinearElliptic::Tests::BlockSWIPDGStudy< MultiscaleTestCaseType >   MultiscaleStudyType;

template< class TestCaseType >
void print_parameter_information(const TestCaseType& test_case)
{
  const auto& parameters = test_case.parameters();
  const auto& problem = test_case.problem();
  for (auto parameter : parameters)
    EXPECT_EQ(parameter.second.type(), problem.parameter_type())
        << "          id: " << parameter.first << ", parameter: " << parameter.second;
  const auto& diffusion_factor = *problem.diffusion_factor();
  const auto& diffusion_tensor = *problem.diffusion_tensor();
  const auto& force = *problem.force();
  const auto& dirichlet = *problem.dirichlet();
  const auto& neumann = *problem.neumann();
  EXPECT_TRUE(diffusion_factor.parametric());
  EXPECT_FALSE(diffusion_tensor.parametric());
  EXPECT_FALSE(force.parametric());
  EXPECT_FALSE(dirichlet.parametric());
  EXPECT_FALSE(neumann.parametric());
  DSC_LOG_INFO << "| mu            = " << parameters.at("mu") << "\n"
               << "| mu_bar        = " << parameters.at("mu_bar") << "\n"
               << "| mu_hat        = " << parameters.at("mu_hat") << "\n";
  const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat"));
  const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat"));
  DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2    = " << std::setprecision(2) << std::scientific
                                                   << 1.0/std::sqrt(alpha) << "\n"
               << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific
                                                   << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n"
               << "+\n";
} // ... print_parameter_information(...)

template< class TestCaseType, class StudyType >
void run_eoc_study(const std::string partitioning,
                   const std::vector< std::string >& only_these_norms,
                   const std::map< std::string, Pymor::Parameter >& parameters,
                   const bool print_header,
                   const std::string visualization)
{
  const TestCaseType test_case(parameters, partitioning);
  if (print_header)
    test_case.print_header(DSC_LOG_INFO);
  print_parameter_information(test_case);
  StudyType study(test_case, only_these_norms, {}, visualization);
  Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO));
} // ... run_eoc_study(...)

TEST(OS2014_parametric_convergence_study, eta_DF_comparison)
{
  const std::string partitioning = "[4 4 1]";
  const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014",
                                                       "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"};
  const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_eta_DF_comparison";
  bool print_header = true;
  for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) {
    const auto mu_hat = Pymor::Parameter("mu", mu_hat_value);
    for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) {
      const auto mu = Pymor::Parameter("mu", mu_value);
      const auto mu_bar = mu;
      run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning,
                                                           only_these_norms,
                                                           {{"mu_hat",        mu_hat},
                                                            {"mu_bar",        mu_bar},
                                                            {"mu",            mu}},
                                                           print_header,
                                                           visualization_prefix);
      if (print_header)
        print_header = false;
    }
  }
} // TEST(OS2014_parametric_convergence_study, eta_DF_comparison)

TEST(OS2014_parametric_convergence_study, multiscale)
{
  const std::string partitioning = "[20 4 1]";
  const std::vector< std::string > only_these_norms = {"energy_mu", "eta_OS2014", "eta_OS2014_*"};
  const std::string visualization_prefix = ""; //"OS2014_parametric_block_convergence_study_spe10_model1";
  bool print_header = true;
  for (auto mu_hat_value : {0.1/*, 0.5*/, 1.0}) {
    const auto mu_hat = Pymor::Parameter("mu", mu_hat_value);
    for (auto mu_value : {0.1/*, 0.3, 0.5, 0.75*/, 1.0}) {
      const auto mu = Pymor::Parameter("mu", mu_value);
      const auto mu_bar = mu;
      run_eoc_study< MultiscaleTestCaseType, MultiscaleStudyType >(partitioning,
                                                                   only_these_norms,
                                                                   {{"mu_hat",        mu_hat},
                                                                    {"mu_bar",        mu_bar},
                                                                    {"mu",            mu}},
                                                                   print_header,
                                                                   visualization_prefix);
      if (print_header)
        print_header = false;
    }
  }
} // TEST(OS2014_parametric_convergence_study, multiscale)

extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >;
extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< MultiscaleTestCaseType >;

#else // HAVE_ALUGRID

TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {}
TEST(DISABLED_OS2014_parametric_convergence_study, multiscale) {}

#endif // HAVE_ALUGRID
<|endoftext|>


<commit_before><commit_msg>fixed vs2017 compile error<commit_after><|endoftext|>


<commit_before><commit_msg>Fix per-application DPI scaling. Make DPI scaling dropdown box require Windows Vista or above.<commit_after><|endoftext|>


<commit_before>// Copyright 2014 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 <GLES2/gl2.h>
#include <GLES2/gl2chromium.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2extchromium.h>

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/process/process_handle.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/image_manager.h"
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gl/gl_image.h"

using testing::_;
using testing::IgnoreResult;
using testing::InvokeWithoutArgs;
using testing::Invoke;
using testing::Return;
using testing::SetArgPointee;
using testing::StrictMock;

namespace gpu {
namespace gles2 {

static const int kImageWidth = 32;
static const int kImageHeight = 32;

class GpuMemoryBufferTest
    : public testing::TestWithParam<gfx::GpuMemoryBuffer::Format> {
 protected:
  void SetUp() override {
    gl_.Initialize(GLManager::Options());
    gl_.MakeCurrent();

    glGenTextures(2, texture_ids_);
    glBindTexture(GL_TEXTURE_2D, texture_ids_[1]);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glGenFramebuffers(1, &framebuffer_id_);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_id_);
    glFramebufferTexture2D(GL_FRAMEBUFFER,
                           GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D,
                           texture_ids_[1],
                           0);
  }

  void TearDown() override {
    glDeleteTextures(2, texture_ids_);
    glDeleteFramebuffers(1, &framebuffer_id_);

    gl_.Destroy();
  }

  GLManager gl_;
  GLuint texture_ids_[2];
  GLuint framebuffer_id_;
};

namespace {

std::vector<uint8> GetTexturePixel(const gfx::GpuMemoryBuffer::Format format) {
  std::vector<uint8> pixel;
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
      pixel.push_back(255u);
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::BGRA_8888:
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return std::vector<uint8>();
  }

  NOTREACHED();
  return std::vector<uint8>();
}

std::vector<uint8> GetFramebufferPixel(
    const gfx::GpuMemoryBuffer::Format format) {
  std::vector<uint8> pixel;
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
    case gfx::GpuMemoryBuffer::BGRA_8888:
      pixel.push_back(255u);
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return std::vector<uint8>();
  }

  NOTREACHED();
  return std::vector<uint8>();
}

GLenum InternalFormat(gfx::GpuMemoryBuffer::Format format) {
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
      return GL_RGBA;
    case gfx::GpuMemoryBuffer::BGRA_8888:
      return GL_BGRA_EXT;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return 0;
  }

  NOTREACHED();
  return 0;
}

}  // namespace

// An end to end test that tests the whole GpuMemoryBuffer lifecycle.
TEST_P(GpuMemoryBufferTest, Lifecycle) {
  scoped_ptr<gfx::GpuMemoryBuffer> buffer(gl_.CreateGpuMemoryBuffer(
      gfx::Size(kImageWidth, kImageHeight), GetParam()));

  // Map buffer for writing.
  void* data;
  bool rv = buffer->Map(&data);
  DCHECK(rv);

  uint8* mapped_buffer = static_cast<uint8*>(data);
  ASSERT_TRUE(mapped_buffer != NULL);

  // Assign a value to each pixel.
  uint32 stride = 0;
  buffer->GetStride(&stride);
  ASSERT_NE(stride, 0u);
  std::vector<uint8> pixel = GetTexturePixel(GetParam());
  for (int y = 0; y < kImageHeight; ++y) {
    for (int x = 0; x < kImageWidth; ++x) {
      std::copy(pixel.begin(), pixel.end(),
                mapped_buffer + y * stride + x * pixel.size());
    }
  }

  // Unmap the buffer.
  buffer->Unmap();

  // Create the image. This should add the image ID to the ImageManager.
  GLuint image_id =
      glCreateImageCHROMIUM(buffer->AsClientBuffer(), kImageWidth, kImageHeight,
                            InternalFormat(GetParam()));
  EXPECT_NE(0u, image_id);
  EXPECT_TRUE(gl_.decoder()->GetImageManager()->LookupImage(image_id) != NULL);

  // Bind the texture and the image.
  glBindTexture(GL_TEXTURE_2D, texture_ids_[0]);
  glBindTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id);

  // Copy texture so we can verify result using CheckPixels.
  glCopyTextureCHROMIUM(GL_TEXTURE_2D, texture_ids_[0], texture_ids_[1],
                        InternalFormat(GetParam()), GL_UNSIGNED_BYTE);
  EXPECT_TRUE(glGetError() == GL_NO_ERROR);

  // Check if pixels match the values that were assigned to the mapped buffer.
  GLTestHelper::CheckPixels(0, 0, kImageWidth, kImageHeight, 0,
                            &GetFramebufferPixel(GetParam()).front());
  EXPECT_TRUE(GL_NO_ERROR == glGetError());

  // Release the image.
  glReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id);

  // Destroy the image.
  glDestroyImageCHROMIUM(image_id);
}

INSTANTIATE_TEST_CASE_P(GpuMemoryBufferTests,
                        GpuMemoryBufferTest,
                        ::testing::Values(gfx::GpuMemoryBuffer::RGBA_8888,
                                          gfx::GpuMemoryBuffer::BGRA_8888));

}  // namespace gles2
}  // namespace gpu
<commit_msg>Test gpu memory buffers drawing directly to the backbuffer.<commit_after>// Copyright 2014 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 <GLES2/gl2.h>
#include <GLES2/gl2chromium.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2extchromium.h>

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/process/process_handle.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/service/command_buffer_service.h"
#include "gpu/command_buffer/service/image_manager.h"
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gl/gl_image.h"

using testing::_;
using testing::IgnoreResult;
using testing::InvokeWithoutArgs;
using testing::Invoke;
using testing::Return;
using testing::SetArgPointee;
using testing::StrictMock;

namespace gpu {
namespace gles2 {

static const int kImageWidth = 32;
static const int kImageHeight = 32;

class GpuMemoryBufferTest
    : public testing::TestWithParam<gfx::GpuMemoryBuffer::Format> {
 protected:
  void SetUp() override {
    GLManager::Options options;
    options.size = gfx::Size(kImageWidth, kImageHeight);
    gl_.Initialize(options);
    gl_.MakeCurrent();
  }

  void TearDown() override {
    gl_.Destroy();
  }

  GLManager gl_;
};

namespace {

#define SHADER(Src) #Src

// clang-format off
const char kVertexShader[] =
SHADER(
  attribute vec4 a_position;
  varying vec2 v_texCoord;
  void main() {
    gl_Position = a_position;
    v_texCoord = vec2((a_position.x + 1.0) * 0.5, (a_position.y + 1.0) * 0.5);
  }
);

const char* kFragmentShader =
SHADER(
  precision mediump float;
  uniform sampler2D a_texture;
  varying vec2 v_texCoord;
  void main() {
    gl_FragColor = texture2D(a_texture, v_texCoord);
  }
);
// clang-format on

std::vector<uint8> GetTexturePixel(const gfx::GpuMemoryBuffer::Format format) {
  std::vector<uint8> pixel;
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
      pixel.push_back(255u);
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::BGRA_8888:
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return std::vector<uint8>();
  }

  NOTREACHED();
  return std::vector<uint8>();
}

std::vector<uint8> GetFramebufferPixel(
    const gfx::GpuMemoryBuffer::Format format) {
  std::vector<uint8> pixel;
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
    case gfx::GpuMemoryBuffer::BGRA_8888:
      pixel.push_back(255u);
      pixel.push_back(0u);
      pixel.push_back(0u);
      pixel.push_back(255u);
      return pixel;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return std::vector<uint8>();
  }

  NOTREACHED();
  return std::vector<uint8>();
}

GLenum InternalFormat(gfx::GpuMemoryBuffer::Format format) {
  switch (format) {
    case gfx::GpuMemoryBuffer::RGBA_8888:
      return GL_RGBA;
    case gfx::GpuMemoryBuffer::BGRA_8888:
      return GL_BGRA_EXT;
    case gfx::GpuMemoryBuffer::ATC:
    case gfx::GpuMemoryBuffer::ATCIA:
    case gfx::GpuMemoryBuffer::DXT1:
    case gfx::GpuMemoryBuffer::DXT5:
    case gfx::GpuMemoryBuffer::ETC1:
    case gfx::GpuMemoryBuffer::RGBX_8888:
      NOTREACHED();
      return 0;
  }

  NOTREACHED();
  return 0;
}

}  // namespace

// An end to end test that tests the whole GpuMemoryBuffer lifecycle.
TEST_P(GpuMemoryBufferTest, Lifecycle) {
  GLuint texture_id = 0;
  glGenTextures(1, &texture_id);
  ASSERT_NE(0u, texture_id);
  glBindTexture(GL_TEXTURE_2D, texture_id);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

  // Create the gpu memory buffer.
  scoped_ptr<gfx::GpuMemoryBuffer> buffer(gl_.CreateGpuMemoryBuffer(
      gfx::Size(kImageWidth, kImageHeight), GetParam()));

  // Map buffer for writing.
  void* data;
  bool rv = buffer->Map(&data);
  DCHECK(rv);

  uint8* mapped_buffer = static_cast<uint8*>(data);
  ASSERT_TRUE(mapped_buffer != NULL);

  // Assign a value to each pixel.
  uint32 stride = 0;
  buffer->GetStride(&stride);
  ASSERT_NE(stride, 0u);
  std::vector<uint8> pixel = GetTexturePixel(GetParam());
  for (int y = 0; y < kImageHeight; ++y) {
    for (int x = 0; x < kImageWidth; ++x) {
      std::copy(pixel.begin(), pixel.end(),
                mapped_buffer + y * stride + x * pixel.size());
    }
  }

  // Unmap the buffer.
  buffer->Unmap();

  // Create the image. This should add the image ID to the ImageManager.
  GLuint image_id =
      glCreateImageCHROMIUM(buffer->AsClientBuffer(), kImageWidth, kImageHeight,
                            InternalFormat(GetParam()));
  ASSERT_NE(0u, image_id);
  ASSERT_TRUE(gl_.decoder()->GetImageManager()->LookupImage(image_id) != NULL);

  // Bind the image.
  glBindTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id);

  // Build program, buffers and draw the texture.
  GLuint vertex_shader =
      GLTestHelper::LoadShader(GL_VERTEX_SHADER, kVertexShader);
  GLuint fragment_shader =
      GLTestHelper::LoadShader(GL_FRAGMENT_SHADER, kFragmentShader);
  GLuint program = GLTestHelper::SetupProgram(vertex_shader, fragment_shader);
  ASSERT_NE(0u, program);
  glUseProgram(program);

  GLint sampler_location = glGetUniformLocation(program, "a_texture");
  ASSERT_NE(-1, sampler_location);
  glUniform1i(sampler_location, 0);

  GLuint vbo =
      GLTestHelper::SetupUnitQuad(glGetAttribLocation(program, "a_position"));
  ASSERT_NE(0u, vbo);
  glViewport(0, 0, kImageWidth, kImageHeight);
  glDrawArrays(GL_TRIANGLES, 0, 6);
  ASSERT_TRUE(glGetError() == GL_NO_ERROR);

  // Check if pixels match the values that were assigned to the mapped buffer.
  GLTestHelper::CheckPixels(0, 0, kImageWidth, kImageHeight, 0,
                            &GetFramebufferPixel(GetParam()).front());
  EXPECT_TRUE(GL_NO_ERROR == glGetError());

  // Release the image.
  glReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id);

  // Clean up.
  glDeleteProgram(program);
  glDeleteShader(vertex_shader);
  glDeleteShader(fragment_shader);
  glDeleteBuffers(1, &vbo);
  glDestroyImageCHROMIUM(image_id);
  glDeleteTextures(1, &texture_id);
}

INSTANTIATE_TEST_CASE_P(GpuMemoryBufferTests,
                        GpuMemoryBufferTest,
                        ::testing::Values(gfx::GpuMemoryBuffer::RGBA_8888,
                                          gfx::GpuMemoryBuffer::BGRA_8888));

}  // namespace gles2
}  // namespace gpu
<|endoftext|>


<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */

#include <granary.h>

using namespace granary;

GRANARY_DEFINE_bool(count_execs, false,
    "Count the number of times each block is executed. This option is only "
    "meaningful for dynamic instrumentation. By default, `count_bbs` does not "
    "count the number of executions of each basic block.",

    "count_bbs");

// Records the static number of basic blocks. This could be an underestimation
// of the total number of basic blocks in the instrumented binary, but an
// overestimate of the total number of *distinct* basic blocks instrumented
// (because of race conditions when two threads simultaneously instrument the
// same basic block).
std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0));

namespace {

// Runtime block execution counter.
class BlockCounter : public MutableMetaData<BlockCounter> {
 public:
  BlockCounter(void)
      : count(0) {}

  uint64_t count;
};

// Simple tool for static and dynamic basic block counting.
class BBCount : public InstrumentationTool {
 public:
  virtual void Init(InitReason) {
    if (FLAG_count_execs) {
      RegisterMetaData<BlockCounter>();
    }
  }

  virtual ~BBCount(void) = default;
  virtual void InstrumentBlock(DecodedBasicBlock *bb) {
    NUM_BBS.fetch_add(1);
    if (!FLAG_count_execs) {
      return;
    }
    Instruction *insert_instr = bb->FirstInstruction();

    // Try to find a good place to insert this instruction such that the
    // placement is before an instruction that kills the flags (but doesn't
    // read them).
    for (auto instr : bb->ReversedAppInstructions()) {
      if (!IsA<ControlFlowInstruction *>(instr) &&
          instr->WritesConditionCodes() &&
          !instr->ReadsConditionCodes()) {
        insert_instr = instr;
      }
    }

    // Now that we have an insertion spot (either first instruction, or before
    // and instruction that kills the flags), go and insert the increment to
    // the block-specific execution counter.
    auto meta = GetMetaData<BlockCounter>(bb);
    MemoryOperand counter_addr(&(meta->count));
    lir::InlineAssembly asm_({&counter_addr});
    asm_.InlineBefore(insert_instr, "INC m64 %0;"_x86_64);
  }
};

}  // namespace

// Initialize the `count_bbs` tool.
GRANARY_CLIENT_INIT({
  RegisterInstrumentationTool<BBCount>("count_bbs");
})
<commit_msg>Minor improvement to the count_bbs tool. Still don't have it report on dynamic execution counters though.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */

#include <granary.h>

using namespace granary;

GRANARY_DEFINE_bool(count_execs, false,
    "Count the number of times each block is executed. This option is only "
    "meaningful for dynamic instrumentation. By default, `count_bbs` does not "
    "count the number of executions of each basic block.",

    "count_bbs");

// Records the static number of basic blocks. This could be an underestimation
// of the total number of basic blocks in the instrumented binary, but an
// overestimate of the total number of *distinct* basic blocks instrumented
// (because of race conditions when two threads simultaneously instrument the
// same basic block).
std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0));

namespace {

// Runtime block execution counter.
class BlockCounter : public MutableMetaData<BlockCounter> {
 public:
  BlockCounter(void)
      : count(0) {}

  uint64_t count;
};

// Simple tool for static and dynamic basic block counting.
class BBCount : public InstrumentationTool {
 public:
  virtual void Init(InitReason) {
    if (FLAG_count_execs) {
      RegisterMetaData<BlockCounter>();
    }
  }

  virtual void Exit(ExitReason) {
    os::Log(os::LogOutput, "%lu blocks were translated.\n",
            NUM_BBS.load());
  }

  virtual ~BBCount(void) = default;
  virtual void InstrumentBlock(DecodedBasicBlock *bb) {
    NUM_BBS.fetch_add(1);
    if (!FLAG_count_execs) {
      return;
    }
    Instruction *insert_instr = bb->FirstInstruction();

    // Try to find a good place to insert this instruction such that the
    // placement is before an instruction that kills the flags (but doesn't
    // read them).
    for (auto instr : bb->ReversedAppInstructions()) {
      if (!IsA<ControlFlowInstruction *>(instr) &&
          instr->WritesConditionCodes() &&
          !instr->ReadsConditionCodes()) {
        insert_instr = instr;
      }
    }

    // Now that we have an insertion spot (either first instruction, or before
    // and instruction that kills the flags), go and insert the increment to
    // the block-specific execution counter.
    auto meta = GetMetaData<BlockCounter>(bb);
    MemoryOperand counter_addr(&(meta->count));
    lir::InlineAssembly asm_({&counter_addr});
    asm_.InlineBefore(insert_instr, "INC m64 %0;"_x86_64);
  }
};

}  // namespace

// Initialize the `count_bbs` tool.
GRANARY_CLIENT_INIT({
  RegisterInstrumentationTool<BBCount>("count_bbs");
})
<|endoftext|>


<commit_before><commit_msg>Remove white spaces.<commit_after><|endoftext|>