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

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "chrome/browser/extensions/activity_log/dom_actions.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/prerender/prerender_handle.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/dom_action_types.h"
#include "chrome/common/extensions/extension_builder.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "sql/statement.h"
#include "testing/gtest/include/gtest/gtest.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/device_settings_service.h"
#endif

namespace {

const char kExtensionId[] = "abc";

}  // namespace

namespace extensions {

class ActivityLogTest : public testing::Test {
 protected:
  ActivityLogTest()
      : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
        saved_cmdline_(CommandLine::NO_PROGRAM) {
#if defined OS_CHROMEOS
    test_user_manager_.reset(new chromeos::ScopedTestUserManager());
#endif
    CommandLine command_line(CommandLine::NO_PROGRAM);
    saved_cmdline_ = *CommandLine::ForCurrentProcess();
    profile_.reset(new TestingProfile());
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogging);
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogTesting);
    ActivityLog::RecomputeLoggingIsEnabled(true);  // Logging now enabled.
    extension_service_ = static_cast<TestExtensionSystem*>(
        ExtensionSystem::Get(profile_.get()))->CreateExtensionService
            (&command_line, base::FilePath(), false);
    ActivityLog::GetInstance(profile_.get())->Init();
    base::RunLoop().RunUntilIdle();
  }

  virtual ~ActivityLogTest() {
#if defined OS_CHROMEOS
    test_user_manager_.reset();
#endif
    base::RunLoop().RunUntilIdle();
    profile_.reset(NULL);
    base::RunLoop().RunUntilIdle();
    // Restore the original command line and undo the affects of SetUp().
    *CommandLine::ForCurrentProcess() = saved_cmdline_;
    ActivityLog::RecomputeLoggingIsEnabled(false);  // Logging now disabled.
  }

  static void RetrieveActions_LogAndFetchActions(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    ASSERT_EQ(2, static_cast<int>(i->size()));
  }

  static void RetrieveActions_LogAndFetchPathActions(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    std::string args;
    ASSERT_EQ(1U, i->size());
    scoped_refptr<Action> last = i->front();
    if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kEnableExtensionActivityLogTesting))
      args = "Injected scripts () onto "
              "http://www.google.com/foo?bar extra";
    else
      args = "Injected scripts () onto "
              "http://www.google.com/foo extra";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  static void Arguments_Missing(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    scoped_refptr<Action> last = i->front();
    std::string id(kExtensionId);
    std::string noargs = "ID: " + id + ", CATEGORY: "
        "call, API: tabs.testMethod, ARGS: ";
    ASSERT_EQ(noargs, last->PrintForDebug());
  }

  static void Arguments_Present(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    scoped_refptr<Action> last = i->front();
    std::string id(kExtensionId);
    std::string args = "ID: " + id + ", CATEGORY: "
        "call, API: extension.connect, ARGS: \"hello\", \"world\"";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  void SetPolicy(bool log_arguments) {
    ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
    if (log_arguments)
      activity_log->SetDefaultPolicy(ActivityLogPolicy::POLICY_FULLSTREAM);
    else
      activity_log->SetDefaultPolicy(ActivityLogPolicy::POLICY_NOARGS);
  }

 protected:
  scoped_ptr<TestingProfile> profile_;
  ExtensionService* extension_service_;

  content::TestBrowserThreadBundle thread_bundle_;

  // Used to preserve a copy of the original command line.
  // The test framework will do this itself as well. However, by then,
  // it is too late to call ActivityLog::RecomputeLoggingIsEnabled() in
  // TearDown().
  CommandLine saved_cmdline_;

#if defined OS_CHROMEOS
  chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
  chromeos::ScopedTestCrosSettings test_cros_settings_;
  scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
#endif
};

class RenderViewActivityLogTest : public ChromeRenderViewHostTestHarness {
 protected:
  RenderViewActivityLogTest() : saved_cmdline_(CommandLine::NO_PROGRAM) {}

  virtual void SetUp() OVERRIDE {
    ChromeRenderViewHostTestHarness::SetUp();
#if defined OS_CHROMEOS
    test_user_manager_.reset(new chromeos::ScopedTestUserManager());
#endif
    CommandLine command_line(CommandLine::NO_PROGRAM);
    saved_cmdline_ = *CommandLine::ForCurrentProcess();
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogging);
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogTesting);
    ActivityLog::RecomputeLoggingIsEnabled(true);  // Logging is now enabled.
    extension_service_ = static_cast<TestExtensionSystem*>(
        ExtensionSystem::Get(profile()))->CreateExtensionService(
            &command_line, base::FilePath(), false);
    ActivityLog::GetInstance(profile())->Init();
    base::RunLoop().RunUntilIdle();
  }

  virtual void TearDown() OVERRIDE {
#if defined OS_CHROMEOS
    test_user_manager_.reset();
#endif
    ChromeRenderViewHostTestHarness::TearDown();
    *CommandLine::ForCurrentProcess() = saved_cmdline_;
    ActivityLog::RecomputeLoggingIsEnabled(false);  // Logging is now disabled.
  }

  static void Arguments_Prerender(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    ASSERT_EQ(1U, i->size());
    scoped_refptr<Action> last = i->front();
    std::string args = "Injected scripts (\"script \") "
        "onto http://www.google.com/ (prerender)";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  ExtensionService* extension_service_;
  // Used to preserve a copy of the original command line.
  // The test framework will do this itself as well. However, by then,
  // it is too late to call ActivityLog::RecomputeLoggingIsEnabled() in
  // TearDown().
  CommandLine saved_cmdline_;

 private:
#if defined OS_CHROMEOS
  chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
  chromeos::ScopedTestCrosSettings test_cros_settings_;
  scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
#endif
};

TEST_F(ActivityLogTest, Enabled) {
  ASSERT_TRUE(ActivityLog::IsLogEnabledOnAnyProfile());
}

TEST_F(ActivityLogTest, Construct) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
}

TEST_F(ActivityLogTest, LogAndFetchActions) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  // Write some API calls
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
  activity_log->LogDOMAction(kExtensionId,
                             GURL("http://www.google.com"),
                             string16(),
                             std::string("document.write"),
                             args.get(),
                             DomActionType::METHOD,
                             std::string("extra"));
  activity_log->GetActions(
      kExtensionId,
      0,
      base::Bind(ActivityLogTest::RetrieveActions_LogAndFetchActions));
}

TEST_F(ActivityLogTest, LogAndFetchPathActions) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  activity_log->LogDOMAction(kExtensionId,
                             GURL("http://www.google.com/foo?bar"),
                             string16(),
                             std::string("document.write"),
                             args.get(),
                             DomActionType::INSERTED,
                             std::string("extra"));
  activity_log->GetActions(
      kExtensionId,
      0,
      base::Bind(ActivityLogTest::RetrieveActions_LogAndFetchPathActions));
}

TEST_F(ActivityLogTest, LogWithoutArguments) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  SetPolicy(false);
  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Set(0, new base::StringValue("hello"));
  args->Set(1, new base::StringValue("world"));
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
  activity_log->GetActions(
      kExtensionId, 0, base::Bind(ActivityLogTest::Arguments_Missing));
  SetPolicy(true);
}

TEST_F(ActivityLogTest, LogWithArguments) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile_.get());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Set(0, new base::StringValue("hello"));
  args->Set(1, new base::StringValue("world"));
  activity_log->LogAPIAction(kExtensionId,
                             std::string("extension.connect"),
                             args.get(),
                             std::string());
  activity_log->GetActions(
      kExtensionId, 0, base::Bind(ActivityLogTest::Arguments_Present));
}

TEST_F(RenderViewActivityLogTest, LogPrerender) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder()
          .SetManifest(DictionaryBuilder()
                       .Set("name", "Test extension")
                       .Set("version", "1.0.0")
                       .Set("manifest_version", 2))
          .Build();
  extension_service_->AddExtension(extension.get());
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  GURL url("http://www.google.com");

  prerender::PrerenderManager* prerender_manager =
      prerender::PrerenderManagerFactory::GetForProfile(
          Profile::FromBrowserContext(profile()));

  const gfx::Size kSize(640, 480);
  scoped_ptr<prerender::PrerenderHandle> prerender_handle(
      prerender_manager->AddPrerenderFromLocalPredictor(
          url,
          web_contents()->GetController().GetDefaultSessionStorageNamespace(),
          kSize));

  const std::vector<content::WebContents*> contentses =
      prerender_manager->GetAllPrerenderingContents();
  ASSERT_EQ(1U, contentses.size());
  content::WebContents *contents = contentses[0];
  ASSERT_TRUE(prerender_manager->IsWebContentsPrerendering(contents, NULL));

  TabHelper::ScriptExecutionObserver::ExecutingScriptsMap executing_scripts;
  executing_scripts[extension->id()].insert("script");

  static_cast<TabHelper::ScriptExecutionObserver*>(activity_log)->
      OnScriptsExecuted(contents, executing_scripts, 0, url);

  activity_log->GetActions(
      extension->id(), 0, base::Bind(
          RenderViewActivityLogTest::Arguments_Prerender));

  prerender_manager->CancelAllPrerenders();
}

}  // namespace extensions

<commit_msg>[Activity Log] Refactoring unit tests / code cleanup<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "chrome/browser/extensions/activity_log/dom_actions.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/prerender/prerender_handle.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/dom_action_types.h"
#include "chrome/common/extensions/extension_builder.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "sql/statement.h"
#include "testing/gtest/include/gtest/gtest.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/device_settings_service.h"
#endif

namespace {

const char kExtensionId[] = "abc";

}  // namespace

namespace extensions {

class ActivityLogTest : public ChromeRenderViewHostTestHarness {
 protected:
  ActivityLogTest() : saved_cmdline_(CommandLine::NO_PROGRAM) {}

  virtual void SetUp() OVERRIDE {
    ChromeRenderViewHostTestHarness::SetUp();
#if defined OS_CHROMEOS
    test_user_manager_.reset(new chromeos::ScopedTestUserManager());
#endif
    CommandLine command_line(CommandLine::NO_PROGRAM);
    saved_cmdline_ = *CommandLine::ForCurrentProcess();
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogging);
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kEnableExtensionActivityLogTesting);
    ActivityLog::RecomputeLoggingIsEnabled(true);  // Logging now enabled.
    extension_service_ = static_cast<TestExtensionSystem*>(
        ExtensionSystem::Get(profile()))->CreateExtensionService
            (&command_line, base::FilePath(), false);
    ActivityLog::GetInstance(profile())->Init();
    base::RunLoop().RunUntilIdle();
  }

  virtual void TearDown() OVERRIDE {
#if defined OS_CHROMEOS
    test_user_manager_.reset();
#endif
    base::RunLoop().RunUntilIdle();
    // Restore the original command line and undo the affects of SetUp().
    *CommandLine::ForCurrentProcess() = saved_cmdline_;
    ActivityLog::RecomputeLoggingIsEnabled(false);  // Logging now disabled.
    ChromeRenderViewHostTestHarness::TearDown();
  }

  static void RetrieveActions_LogAndFetchActions(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    ASSERT_EQ(2, static_cast<int>(i->size()));
  }

  static void RetrieveActions_LogAndFetchPathActions(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    std::string args;
    ASSERT_EQ(1U, i->size());
    scoped_refptr<Action> last = i->front();
    if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kEnableExtensionActivityLogTesting))
      args = "Injected scripts () onto "
              "http://www.google.com/foo?bar extra";
    else
      args = "Injected scripts () onto "
              "http://www.google.com/foo extra";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  static void Arguments_Missing(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    scoped_refptr<Action> last = i->front();
    std::string id(kExtensionId);
    std::string noargs = "ID: " + id + ", CATEGORY: "
        "call, API: tabs.testMethod, ARGS: ";
    ASSERT_EQ(noargs, last->PrintForDebug());
  }

  static void Arguments_Present(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    scoped_refptr<Action> last = i->front();
    std::string id(kExtensionId);
    std::string args = "ID: " + id + ", CATEGORY: "
        "call, API: extension.connect, ARGS: \"hello\", \"world\"";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  void SetPolicy(bool log_arguments) {
    ActivityLog* activity_log = ActivityLog::GetInstance(profile());
    if (log_arguments)
      activity_log->SetDefaultPolicy(ActivityLogPolicy::POLICY_FULLSTREAM);
    else
      activity_log->SetDefaultPolicy(ActivityLogPolicy::POLICY_NOARGS);
  }

  static void Arguments_Prerender(
      scoped_ptr<std::vector<scoped_refptr<Action> > > i) {
    ASSERT_EQ(1U, i->size());
    scoped_refptr<Action> last = i->front();
    std::string args = "Injected scripts (\"script \") "
        "onto http://www.google.com/ (prerender)";
    ASSERT_EQ(args, last->PrintForDebug());
  }

  ExtensionService* extension_service_;
  // Used to preserve a copy of the original command line.
  // The test framework will do this itself as well. However, by then,
  // it is too late to call ActivityLog::RecomputeLoggingIsEnabled() in
  // TearDown().
  CommandLine saved_cmdline_;

#if defined OS_CHROMEOS
  chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
  chromeos::ScopedTestCrosSettings test_cros_settings_;
  scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
#endif
};

TEST_F(ActivityLogTest, Enabled) {
  ASSERT_TRUE(ActivityLog::IsLogEnabledOnAnyProfile());
}

TEST_F(ActivityLogTest, Construct) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
}

TEST_F(ActivityLogTest, LogAndFetchActions) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  // Write some API calls
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
  activity_log->LogDOMAction(kExtensionId,
                             GURL("http://www.google.com"),
                             string16(),
                             std::string("document.write"),
                             args.get(),
                             DomActionType::METHOD,
                             std::string("extra"));
  activity_log->GetActions(
      kExtensionId,
      0,
      base::Bind(ActivityLogTest::RetrieveActions_LogAndFetchActions));
}

TEST_F(ActivityLogTest, LogAndFetchPathActions) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  scoped_ptr<base::ListValue> args(new base::ListValue());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  activity_log->LogDOMAction(kExtensionId,
                             GURL("http://www.google.com/foo?bar"),
                             string16(),
                             std::string("document.write"),
                             args.get(),
                             DomActionType::INSERTED,
                             std::string("extra"));
  activity_log->GetActions(
      kExtensionId,
      0,
      base::Bind(ActivityLogTest::RetrieveActions_LogAndFetchPathActions));
}

TEST_F(ActivityLogTest, LogWithoutArguments) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  SetPolicy(false);
  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Set(0, new base::StringValue("hello"));
  args->Set(1, new base::StringValue("world"));
  activity_log->LogAPIAction(
      kExtensionId, std::string("tabs.testMethod"), args.get(), std::string());
  activity_log->GetActions(
      kExtensionId, 0, base::Bind(ActivityLogTest::Arguments_Missing));
  SetPolicy(true);
}

TEST_F(ActivityLogTest, LogWithArguments) {
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  ASSERT_TRUE(activity_log->IsLogEnabled());

  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Set(0, new base::StringValue("hello"));
  args->Set(1, new base::StringValue("world"));
  activity_log->LogAPIAction(kExtensionId,
                             std::string("extension.connect"),
                             args.get(),
                             std::string());
  activity_log->GetActions(
      kExtensionId, 0, base::Bind(ActivityLogTest::Arguments_Present));
}

TEST_F(ActivityLogTest, LogPrerender) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder()
          .SetManifest(DictionaryBuilder()
                       .Set("name", "Test extension")
                       .Set("version", "1.0.0")
                       .Set("manifest_version", 2))
          .Build();
  extension_service_->AddExtension(extension.get());
  ActivityLog* activity_log = ActivityLog::GetInstance(profile());
  ASSERT_TRUE(activity_log->IsLogEnabled());
  GURL url("http://www.google.com");

  prerender::PrerenderManager* prerender_manager =
      prerender::PrerenderManagerFactory::GetForProfile(
          Profile::FromBrowserContext(profile()));

  const gfx::Size kSize(640, 480);
  scoped_ptr<prerender::PrerenderHandle> prerender_handle(
      prerender_manager->AddPrerenderFromLocalPredictor(
          url,
          web_contents()->GetController().GetDefaultSessionStorageNamespace(),
          kSize));

  const std::vector<content::WebContents*> contentses =
      prerender_manager->GetAllPrerenderingContents();
  ASSERT_EQ(1U, contentses.size());
  content::WebContents *contents = contentses[0];
  ASSERT_TRUE(prerender_manager->IsWebContentsPrerendering(contents, NULL));

  TabHelper::ScriptExecutionObserver::ExecutingScriptsMap executing_scripts;
  executing_scripts[extension->id()].insert("script");

  static_cast<TabHelper::ScriptExecutionObserver*>(activity_log)->
      OnScriptsExecuted(contents, executing_scripts, 0, url);

  activity_log->GetActions(
      extension->id(), 0, base::Bind(ActivityLogTest::Arguments_Prerender));

  prerender_manager->CancelAllPrerenders();
}

}  // namespace extensions

<|endoftext|>


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

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/base/mock_host_resolver.h"

// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  void SetUpInProcessBrowserTestFixture() OVERRIDE {
    // Start up the test server and get us ready for calling the install
    // API functions.
    host_resolver()->AddRule("www.example.com", "127.0.0.1");
    ASSERT_TRUE(test_server()->Start());
    BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true);
    BeginInstallWithManifestFunction::SetAutoConfirmForTests(true);
    ExtensionInstallUI::DisableFailureUIForTests();
  }

 protected:
  // Returns a test server URL, but with host 'www.example.com' so it matches
  // the web store app's extent that we set up via command line flags.
  GURL GetTestServerURL(const std::string& path) {
    GURL url = test_server()->GetURL(
        std::string("files/extensions/api_test/webstore_private/") + path);

    // Replace the host with 'www.example.com' so it matches the web store
    // app's extent.
    GURL::Replacements replace_host;
    std::string host_str("www.example.com");
    replace_host.SetHostStr(host_str);

    return url.ReplaceComponents(replace_host);
  }

  // Navigates to |page| and runs the Extension API test there.
  bool RunInstallTest(const std::string& page) {
    GURL crx_url = GetTestServerURL("extension.crx");
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kAppsGalleryUpdateURL, crx_url.spec());

    GURL page_url = GetTestServerURL(page);
    return RunPageTest(page_url.spec());
  }

  ExtensionService* service() {
    return browser()->profile()->GetExtensionService();
  }
};

// Tests several basic install cases.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, Install) {
  // Test cases where the user accepts the install confirmation dialog.
  ASSERT_TRUE(RunInstallTest("accepted.html"));

  // Now test the case where the user cancels the confirmation dialog.
  BeginInstallWithManifestFunction::SetAutoConfirmForTests(false);
  ASSERT_TRUE(RunInstallTest("cancelled.html"));

  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest1) {
  ui_test_utils::WindowedNotificationObserver observer(
      NotificationType::EXTENSION_INSTALL_ERROR,
      NotificationService::AllSources());
  ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html"));
  observer.Wait();
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest2) {
  ui_test_utils::WindowedNotificationObserver observer(
      NotificationType::EXTENSION_INSTALL_ERROR,
      NotificationService::AllSources());
  ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html"));
  observer.Wait();
}
<commit_msg>Split ExtensionWebstorePrivateApiTest.Install into 3  parts.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/base/mock_host_resolver.h"

// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  void SetUpInProcessBrowserTestFixture() OVERRIDE {
    // Start up the test server and get us ready for calling the install
    // API functions.
    host_resolver()->AddRule("www.example.com", "127.0.0.1");
    ASSERT_TRUE(test_server()->Start());
    BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true);
    BeginInstallWithManifestFunction::SetAutoConfirmForTests(true);
    ExtensionInstallUI::DisableFailureUIForTests();
  }

 protected:
  // Returns a test server URL, but with host 'www.example.com' so it matches
  // the web store app's extent that we set up via command line flags.
  GURL GetTestServerURL(const std::string& path) {
    GURL url = test_server()->GetURL(
        std::string("files/extensions/api_test/webstore_private/") + path);

    // Replace the host with 'www.example.com' so it matches the web store
    // app's extent.
    GURL::Replacements replace_host;
    std::string host_str("www.example.com");
    replace_host.SetHostStr(host_str);

    return url.ReplaceComponents(replace_host);
  }

  // Navigates to |page| and runs the Extension API test there.
  bool RunInstallTest(const std::string& page) {
    GURL crx_url = GetTestServerURL("extension.crx");
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kAppsGalleryUpdateURL, crx_url.spec());

    GURL page_url = GetTestServerURL(page);
    return RunPageTest(page_url.spec());
  }

  ExtensionService* service() {
    return browser()->profile()->GetExtensionService();
  }
};

// Test cases where the user accepts the install confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {
  ASSERT_TRUE(RunInstallTest("accepted.html"));
}

// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
  BeginInstallWithManifestFunction::SetAutoConfirmForTests(false);
  ASSERT_TRUE(RunInstallTest("cancelled.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallNoGesture) {
  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest1) {
  ui_test_utils::WindowedNotificationObserver observer(
      NotificationType::EXTENSION_INSTALL_ERROR,
      NotificationService::AllSources());
  ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html"));
  observer.Wait();
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest2) {
  ui_test_utils::WindowedNotificationObserver observer(
      NotificationType::EXTENSION_INSTALL_ERROR,
      NotificationService::AllSources());
  ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html"));
  observer.Wait();
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 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/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "content/public/test/test_utils.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/events/event_constants.h"

class IncognitoSelectionClipboardTest : public InProcessBrowserTest {
 protected:
  static ui::Clipboard* clipboard() {
    static ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
    return clipboard;
  }

  static void ExpectStringInClipboard(const string16& pattern,
                               ui::Clipboard::Buffer buffer) {
    string16 content;
    clipboard()->ReadText(buffer, &content);
    EXPECT_EQ(pattern, content);
  }

  void CloseBrowser(Browser* browser) {
    content::WindowedNotificationObserver signal(
        chrome::NOTIFICATION_BROWSER_CLOSED,
        content::Source<Browser>(browser));
    chrome::CloseWindow(browser);

    signal.Wait();
  }

  static void SendKeyForBrowser(const Browser* browser,
                                ui::KeyboardCode key,
                                int modifiers) {
    ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
        browser, key,
        (modifiers & ui::EF_CONTROL_DOWN) != 0,
        (modifiers & ui::EF_SHIFT_DOWN) != 0,
        (modifiers & ui::EF_ALT_DOWN) != 0,
        (modifiers & ui::EF_COMMAND_DOWN) != 0));
  }

  static void WriteClipboardCallback(ui::Clipboard::Buffer expected,
                                     const base::Closure& closure,
                                     ui::Clipboard::Buffer actual) {
    if (expected == actual)
      closure.Run();
  }
};

// Tests that data selected in content area of incognito window is destroyed in
// the selection clipboard after profile destruction.
// The test is executed on Linux only because it's the only OS with the
// selection clipboard.
#if defined(USE_X11) && !defined(OS_CHROMEOS)
// This test is flaky. See http://crbug.com/177140
IN_PROC_BROWSER_TEST_F(IncognitoSelectionClipboardTest,
                       DISABLED_ClearContentDataOnSelect) {
  EXPECT_FALSE(browser()->profile()->IsOffTheRecord());
  Browser* browser_incognito = CreateIncognitoBrowser();
  ui_test_utils::NavigateToURL(browser_incognito, GURL("data:text/plain,foo"));
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser_incognito));
  // Select web-page content.
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_A,
                                            ui::EF_CONTROL_DOWN));
  // Run message loop until data have been written to the selection clipboard.
  // This happens on UI thread.
  scoped_refptr<content::MessageLoopRunner> message_loop_runner(
      new content::MessageLoopRunner);
  clipboard()->set_write_objects_callback_for_testing(
      base::Bind(&WriteClipboardCallback,
                 ui::Clipboard::BUFFER_SELECTION,
                 message_loop_runner->QuitClosure()));
  message_loop_runner->Run();
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_SELECTION);

  CloseBrowser(browser_incognito);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_SELECTION);
}
#endif

// Tests that data copied in content area of incognito window is destroyed in
// the selection clipboard after profile destruction.
// The test is executed on Linux only because it's the only OS with the
// selection clipboard.
#if defined(USE_X11) && !defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(IncognitoSelectionClipboardTest,
                       ClearContentDataOnCopy) {
  EXPECT_FALSE(browser()->profile()->IsOffTheRecord());
  Browser* browser_incognito = CreateIncognitoBrowser();
  ui_test_utils::NavigateToURL(browser_incognito, GURL("data:text/plain,foo"));
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser_incognito));
  // Select and copy web-page content.
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_A,
                                            ui::EF_CONTROL_DOWN));
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_C,
                                            ui::EF_CONTROL_DOWN));
  // Run message loop until data have been written to the primary clipboard and
  // automatically propagated to the selection clipboard by ui::Clipboard.
  // This happens on UI thread.
  scoped_refptr<content::MessageLoopRunner> message_loop_runner(
      new content::MessageLoopRunner);
  clipboard()->set_write_objects_callback_for_testing(
      base::Bind(&WriteClipboardCallback,
                 ui::Clipboard::BUFFER_STANDARD,
                 message_loop_runner->QuitClosure()));
  message_loop_runner->Run();
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_SELECTION);
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_STANDARD);

  CloseBrowser(browser_incognito);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_SELECTION);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_STANDARD);
}
#endif
<commit_msg>Fixed flaky IncognitoSelectionClipboardTest.ClearContentDataOnSelect. Former version failed because text wasn't copied to selection clipboard. Now the code is more concerned about focus.<commit_after>// Copyright (c) 2013 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/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "content/public/test/test_utils.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/events/event_constants.h"

class IncognitoSelectionClipboardTest : public InProcessBrowserTest {
 protected:
  static ui::Clipboard* clipboard() {
    static ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
    return clipboard;
  }

  static void ExpectStringInClipboard(const string16& pattern,
                               ui::Clipboard::Buffer buffer) {
    string16 content;
    clipboard()->ReadText(buffer, &content);
    EXPECT_EQ(pattern, content);
  }

  void CloseBrowser(Browser* browser) {
    content::WindowedNotificationObserver signal(
        chrome::NOTIFICATION_BROWSER_CLOSED,
        content::Source<Browser>(browser));
    chrome::CloseWindow(browser);

    signal.Wait();
  }

  static void SendKeyForBrowser(const Browser* browser,
                                ui::KeyboardCode key,
                                int modifiers) {
    ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
        browser, key,
        (modifiers & ui::EF_CONTROL_DOWN) != 0,
        (modifiers & ui::EF_SHIFT_DOWN) != 0,
        (modifiers & ui::EF_ALT_DOWN) != 0,
        (modifiers & ui::EF_COMMAND_DOWN) != 0));
  }

  static void WriteClipboardCallback(ui::Clipboard::Buffer expected,
                                     const base::Closure& closure,
                                     ui::Clipboard::Buffer actual) {
    if (expected == actual)
      closure.Run();
  }
};

// Tests that data selected in content area of incognito window is destroyed in
// the selection clipboard after profile destruction.
// The test is executed on Linux only because it's the only OS with the
// selection clipboard.
#if defined(USE_X11) && !defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(IncognitoSelectionClipboardTest,
                       ClearContentDataOnSelect) {
  EXPECT_FALSE(browser()->profile()->IsOffTheRecord());
  Browser* browser_incognito = CreateIncognitoBrowser();
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser_incognito));
  ui_test_utils::NavigateToURL(browser_incognito, GURL("data:text/plain,foo"));
  ui_test_utils::ClickOnView(browser_incognito, VIEW_ID_TAB_CONTAINER);
  ASSERT_TRUE(ui_test_utils::IsViewFocused(browser_incognito,
                                           VIEW_ID_TAB_CONTAINER));
  // Select web-page content.
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_A,
                                            ui::EF_CONTROL_DOWN));
  // Run message loop until data have been written to the selection clipboard.
  // This happens on UI thread.
  scoped_refptr<content::MessageLoopRunner> message_loop_runner(
      new content::MessageLoopRunner);
  clipboard()->set_write_objects_callback_for_testing(
      base::Bind(&WriteClipboardCallback,
                 ui::Clipboard::BUFFER_SELECTION,
                 message_loop_runner->QuitClosure()));
  message_loop_runner->Run();
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_SELECTION);

  CloseBrowser(browser_incognito);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_SELECTION);
}
#endif

// Tests that data copied in content area of incognito window is destroyed in
// the selection clipboard after profile destruction.
// The test is executed on Linux only because it's the only OS with the
// selection clipboard.
#if defined(USE_X11) && !defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(IncognitoSelectionClipboardTest,
                       ClearContentDataOnCopy) {
  EXPECT_FALSE(browser()->profile()->IsOffTheRecord());
  Browser* browser_incognito = CreateIncognitoBrowser();
  ui_test_utils::NavigateToURL(browser_incognito, GURL("data:text/plain,foo"));
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser_incognito));
  // Select and copy web-page content.
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_A,
                                            ui::EF_CONTROL_DOWN));
  ASSERT_NO_FATAL_FAILURE(SendKeyForBrowser(browser_incognito,
                                            ui::VKEY_C,
                                            ui::EF_CONTROL_DOWN));
  // Run message loop until data have been written to the primary clipboard and
  // automatically propagated to the selection clipboard by ui::Clipboard.
  // This happens on UI thread.
  scoped_refptr<content::MessageLoopRunner> message_loop_runner(
      new content::MessageLoopRunner);
  clipboard()->set_write_objects_callback_for_testing(
      base::Bind(&WriteClipboardCallback,
                 ui::Clipboard::BUFFER_STANDARD,
                 message_loop_runner->QuitClosure()));
  message_loop_runner->Run();
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_SELECTION);
  ExpectStringInClipboard(ASCIIToUTF16("foo"), ui::Clipboard::BUFFER_STANDARD);

  CloseBrowser(browser_incognito);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_SELECTION);
  ExpectStringInClipboard(string16(), ui::Clipboard::BUFFER_STANDARD);
}
#endif
<|endoftext|>


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

#include <oleacc.h>

#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  IAccessible* acc_obj = NULL;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  // TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
  // "about:blank - Chromium"
  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
                        ROLE_SYSTEM_WINDOW);

  acc_obj->Release();
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<commit_msg>Fix flakyness of browser_tests:BrowserViewsAccessibilityTest.TestChromeWindowAccObj<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "app/l10n_util.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title =
      l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
      ASCIIToWide(chrome::kAboutBlankURL));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<|endoftext|>


<commit_before>#include "CPUBipartiteGraphAnnealer.h"
#include <cmath>
#include <float.h>
#include <algorithm>
#include <exception>
#include "CPUFormulas.h"

using namespace sqaod;

template<class real>
CPUBipartiteGraphAnnealer<real>::CPUBipartiteGraphAnnealer() {
    m_ = -1;
    annState_ = annNone;
    annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
#ifdef _OPENMP
    nProcs_ = omp_get_num_procs();
    log("# processors: %d", nProcs_);
#else
    nProcs_ = 1;
#endif
    random_ = new Random[nProcs_];
}

template<class real>
CPUBipartiteGraphAnnealer<real>::~CPUBipartiteGraphAnnealer() {
    delete [] random_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::seed(unsigned long seed) {
    for (int idx = 0; idx < nProcs_; ++idx)
        random_[idx].seed(seed + 17 * idx);
    annState_ |= annRandSeedGiven;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::selectAlgorithm(Algorithm algo) {
    switch (algo) {
    case algoNaive:
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepNaive;
        break;
    case algoColoring:
    case algoDefault:
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
        break;
    default:
        log("Uknown algo, %s, defaulting to %s.", algoToName(algo), algoToName(algoColoring));
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
    }
}

template<class real>
Algorithm CPUBipartiteGraphAnnealer<real>::algorithm() const {
    if (annealMethod_ == &CPUBipartiteGraphAnnealer::annealOneStepNaive)
        return algoNaive;
    if (annealMethod_ == &CPUBipartiteGraphAnnealer::annealOneStepColoring)
        return algoColoring;
    abort_("Must not reach here.");
    return algoDefault; /* to suppress warning. */
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
    *N0 = N0_;
    *N1 = N1_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::setProblem(const Vector &b0, const Vector &b1,
                                                 const Matrix &W, OptimizeMethod om) {
    N0_ = (int)b0.size;
    N1_ = (int)b1.size;
    h0_.resize(N0_);
    h1_.resize(N1_);
    J_.resize(N1_, N0_);
    Vector h0(mapFrom(h0_)), h1(mapFrom(h1_));
    Matrix J(mapFrom(J_));
    BGFuncs<real>::calculate_hJc(&h0, &h1, &J, &c_, b0, b1, W);

    om_ = om;
    if (om_ == optMaximize) {
        h0_ *= real(-1.);
        h1_ *= real(-1.);
        J_ *= real(-1.);
        c_ *= real(-1.);
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::setNumTrotters(SizeType m) {
    throwErrorIf(m <= 0, "# trotters must be a positive integer.");
    m_ = m;
    matQ0_.resize(m_, N0_);
    matQ1_.resize(m_, N1_);
    E_.resize(m_);
    annState_ |= annNTrottersGiven;
}

template<class real>
const BitsPairArray &CPUBipartiteGraphAnnealer<real>::get_x() const {
    return bitsPairX_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::set_x(const Bits &x0, const Bits &x1) {
    EigenRowVector ex0 = mapToRowVector(x0).cast<real>();
    EigenRowVector ex1 = mapToRowVector(x1).cast<real>();
    matQ0_ = (ex0.array() * 2 - 1).matrix();
    matQ1_ = (ex1.array() * 2 - 1).matrix();
    annState_ |= annQSet;
}

template<class real>
const VectorType<real> &CPUBipartiteGraphAnnealer<real>::get_E() const {
    return E_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::get_hJc(Vector *h0, Vector *h1,
                                              Matrix *J, real *c) const {
    mapToRowVector(*h0) = h0_;
    mapToRowVector(*h1) = h1_;
    mapTo(*J) = J_;
    *c = c_;
}

template<class real>
const BitsPairArray &CPUBipartiteGraphAnnealer<real>::get_q() const {
    return bitsPairQ_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::randomize_q() {
    real *q = matQ0_.data();
#ifndef _OPENMP
    {
        Random &random = random_[0];
#else
#pragma omp parallel shared(q)
    {
        sqaod::Random &random = random_[omp_get_thread_num()];
#pragma omp for
#endif
        for (int idx = 0; idx < IdxType(N0_ * m_); ++idx) {
            q[idx] = random.randInt(2) ? real(1.) : real(-1.);
        }
        q = matQ1_.data();
#ifdef _OPENMP
#pragma omp for
#endif
        for (int idx = 0; idx < IdxType(N1_ * m_); ++idx) {
            q[idx] = random.randInt(2) ? real(1.) : real(-1.);
        }
    }
    annState_ |= annQSet;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::calculate_E() {
    BGFuncs<real>::calculate_E(&E_, mapFrom(h0_), mapFrom(h1_), mapFrom(J_), c_,
                               mapFrom(matQ0_), mapFrom(matQ1_));
    if (om_ == optMaximize)
        mapToRowVector(E_) *= real(-1.);
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::initAnneal() {
    if (!(annState_ & annRandSeedGiven))
        for (int idx = 0; idx < nProcs_; ++idx)
            random_[idx].seed();
    annState_ |= annRandSeedGiven;
    if (!(annState_ & annNTrottersGiven))
        setNumTrotters((N0_ + N1_) / 4);
    annState_ |= annNTrottersGiven;
    if (!(annState_ & annQSet))
        randomize_q();
    annState_ |= annQSet;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::finAnneal() {
    syncBits();
    calculate_E();
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::annealOneStepNaive(real G, real kT) {
    real twoDivM = real(2.) / real(m_);
    real coef = std::log(std::tanh(G / kT / m_)) / kT;
    Random &random = random_[0];
    int N = N0_ + N1_;
    for (int loop = 0; loop < IdxType(N * m_); ++loop) {
        int x = random.randInt(N);
        int y = random.randInt(m_);
        if (x < N0_) {
            real qyx = matQ0_(y, x);
            real sum = J_.transpose().row(x).dot(matQ1_.row(y));
            real dE = - twoDivM * qyx * (h0_(x) + sum);
            int neibour0 = (y == 0) ? m_ - 1 : y - 1;
            int neibour1 = (y == m_ - 1) ? 0 : y + 1;
            dE -= qyx * (matQ0_(neibour0, x) + matQ0_(neibour1, x)) * coef;
            real threshold = (dE < real(0.)) ? real(1.) : std::exp(-dE / kT);
            if (threshold > random.random<real>())
                matQ0_(y, x) = - qyx;
        }
        else {
            x -= N0_;
            real qyx = matQ1_(y, x);
            real sum = J_.row(x).dot(matQ0_.row(y));
            real dE = - twoDivM * qyx * (h1_(x) + sum);
            int neibour0 = (y == 0) ? m_ - 1 : y - 1;
            int neibour1 = (y == m_ - 1) ? 0 : y + 1;
            dE -= qyx * (matQ1_(neibour0, x) + matQ1_(neibour1, x)) * coef;
            real threshold = (dE < real(0.)) ? real(1.) : std::exp(-dE / kT);
            if (threshold > random.random<real>())
                matQ1_(y, x) = - qyx;
        }
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::annealOneStepColoring(real G, real kT) {
    annealHalfStepColoring(N1_, matQ1_, h1_, J_, matQ0_, G, kT);
    annealHalfStepColoring(N0_, matQ0_, h0_, J_.transpose(), matQ1_, G, kT);
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::
annealHalfStepColoring(int N, EigenMatrix &qAnneal,
                       const EigenRowVector &h, const EigenMatrix &J,
                       const EigenMatrix &qFixed, real G, real kT) {
    EigenMatrix dEmat = J * qFixed.transpose();
    real twoDivM = real(2.) / m_;
    real tempCoef = std::log(std::tanh(G / kT / m_)) / kT;
    real invKT = real(1.) / kT;

#ifndef _OPENMP
    {
        Random &random = random_[0];
#else
#pragma omp parallel
    {
        Random &random = random_[omp_get_thread_num()];
#pragma omp for
#endif
        for (int im = 0; im < m_; im += 2) {
            for (int iq = 0; iq < N; ++iq) {
                real q = qAnneal(im, iq);
                real dE = - twoDivM * q * (h[iq] + dEmat(iq, im));
                int mNeibour0 = (im + m_ - 1) % m_;
                int mNeibour1 = (im + 1) % m_;
                dE -= q * (qAnneal(mNeibour0, iq) + qAnneal(mNeibour1, iq)) * tempCoef;
                real thresh = dE < real(0.) ? real(1.) : std::exp(- dE * invKT);
                if (thresh > random.random<real>())
                    qAnneal(im, iq) = -q;
            }
        }
#ifdef _OPENMP
#pragma omp for
#endif
        for (int im = 1; im < m_; im += 2) {
            for (int iq = 0; iq < N; ++iq) {
                real q = qAnneal(im, iq);
                real dE = - twoDivM * q * (h[iq] + dEmat(iq, im));
                int mNeibour0 = (im + m_ - 1) % m_;
                int mNeibour1 = (im + 1) % m_;
                dE -= q * (qAnneal(mNeibour0, iq) + qAnneal(mNeibour1, iq)) * tempCoef;
                real thresh = dE < real(0.) ? real(1.) : std::exp(-dE * invKT);
                if (thresh > random.random<real>())
                    qAnneal(im, iq) = -q;
            }
        }
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::syncBits() {
    bitsPairX_.clear();
    bitsPairQ_.clear();
    Bits x0, x1;
    for (int idx = 0; idx < IdxType(m_); ++idx) {
        Bits q0 = extractRow<char>(matQ0_, idx);
        Bits q1 = extractRow<char>(matQ1_, idx);
        bitsPairQ_.pushBack(BitsPairArray::ValueType(q0, q1));
        Bits x0 = x_from_q(q0), x1 = x_from_q(q1);
        bitsPairX_.pushBack(BitsPairArray::ValueType(x0, x1));
    }
}

template class sqaod::CPUBipartiteGraphAnnealer<float>;
template class sqaod::CPUBipartiteGraphAnnealer<double>;
<commit_msg>Cleaning up, and checked with g++.<commit_after>#include "CPUBipartiteGraphAnnealer.h"
#include <cmath>
#include <float.h>
#include <algorithm>
#include <exception>
#include "CPUFormulas.h"

using namespace sqaod;

template<class real>
CPUBipartiteGraphAnnealer<real>::CPUBipartiteGraphAnnealer() {
    m_ = -1;
    annState_ = annNone;
    annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
#ifdef _OPENMP
    nProcs_ = omp_get_num_procs();
    log("# processors: %d", nProcs_);
#else
    nProcs_ = 1;
#endif
    random_ = new Random[nProcs_];
}

template<class real>
CPUBipartiteGraphAnnealer<real>::~CPUBipartiteGraphAnnealer() {
    delete [] random_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::seed(unsigned long seed) {
    for (int idx = 0; idx < nProcs_; ++idx)
        random_[idx].seed(seed + 17 * idx);
    annState_ |= annRandSeedGiven;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::selectAlgorithm(Algorithm algo) {
    switch (algo) {
    case algoNaive:
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepNaive;
        break;
    case algoColoring:
    case algoDefault:
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
        break;
    default:
        log("Uknown algo, %s, defaulting to %s.", algoToName(algo), algoToName(algoColoring));
        annealMethod_ = &CPUBipartiteGraphAnnealer::annealOneStepColoring;
    }
}

template<class real>
Algorithm CPUBipartiteGraphAnnealer<real>::algorithm() const {
    if (annealMethod_ == &CPUBipartiteGraphAnnealer::annealOneStepNaive)
        return algoNaive;
    if (annealMethod_ == &CPUBipartiteGraphAnnealer::annealOneStepColoring)
        return algoColoring;
    abort_("Must not reach here.");
    return algoDefault; /* to suppress warning. */
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::getProblemSize(SizeType *N0, SizeType *N1) const {
    *N0 = N0_;
    *N1 = N1_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::setProblem(const Vector &b0, const Vector &b1,
                                                 const Matrix &W, OptimizeMethod om) {
    N0_ = (int)b0.size;
    N1_ = (int)b1.size;
    h0_.resize(N0_);
    h1_.resize(N1_);
    J_.resize(N1_, N0_);
    Vector h0(mapFrom(h0_)), h1(mapFrom(h1_));
    Matrix J(mapFrom(J_));
    BGFuncs<real>::calculate_hJc(&h0, &h1, &J, &c_, b0, b1, W);

    om_ = om;
    if (om_ == optMaximize) {
        h0_ *= real(-1.);
        h1_ *= real(-1.);
        J_ *= real(-1.);
        c_ *= real(-1.);
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::setNumTrotters(SizeType m) {
    throwErrorIf(m <= 0, "# trotters must be a positive integer.");
    m_ = m;
    matQ0_.resize(m_, N0_);
    matQ1_.resize(m_, N1_);
    E_.resize(m_);
    annState_ |= annNTrottersGiven;
}

template<class real>
const BitsPairArray &CPUBipartiteGraphAnnealer<real>::get_x() const {
    return bitsPairX_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::set_x(const Bits &x0, const Bits &x1) {
    EigenRowVector ex0 = mapToRowVector(x0).cast<real>();
    EigenRowVector ex1 = mapToRowVector(x1).cast<real>();
    matQ0_ = (ex0.array() * 2 - 1).matrix();
    matQ1_ = (ex1.array() * 2 - 1).matrix();
    annState_ |= annQSet;
}

template<class real>
const VectorType<real> &CPUBipartiteGraphAnnealer<real>::get_E() const {
    return E_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::get_hJc(Vector *h0, Vector *h1,
                                              Matrix *J, real *c) const {
    mapToRowVector(*h0) = h0_;
    mapToRowVector(*h1) = h1_;
    mapTo(*J) = J_;
    *c = c_;
}

template<class real>
const BitsPairArray &CPUBipartiteGraphAnnealer<real>::get_q() const {
    return bitsPairQ_;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::randomize_q() {
#ifndef _OPENMP
    {
        Random &random = random_[0];
        real *q = matQ0_.data();
#else
#pragma omp parallel
    {
        sqaod::Random &random = random_[omp_get_thread_num()];
        real *q = matQ0_.data();
#pragma omp for
#endif
        for (int idx = 0; idx < IdxType(N0_ * m_); ++idx)
            q[idx] = random.randInt(2) ? real(1.) : real(-1.);
        q = matQ1_.data();
#ifdef _OPENMP
#pragma omp for
#endif
        for (int idx = 0; idx < IdxType(N1_ * m_); ++idx)
            q[idx] = random.randInt(2) ? real(1.) : real(-1.);
    }
    annState_ |= annQSet;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::calculate_E() {
    BGFuncs<real>::calculate_E(&E_, mapFrom(h0_), mapFrom(h1_), mapFrom(J_), c_,
                               mapFrom(matQ0_), mapFrom(matQ1_));
    if (om_ == optMaximize)
        mapToRowVector(E_) *= real(-1.);
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::initAnneal() {
    if (!(annState_ & annRandSeedGiven))
        for (int idx = 0; idx < nProcs_; ++idx)
            random_[idx].seed();
    annState_ |= annRandSeedGiven;
    if (!(annState_ & annNTrottersGiven))
        setNumTrotters((N0_ + N1_) / 4);
    annState_ |= annNTrottersGiven;
    if (!(annState_ & annQSet))
        randomize_q();
    annState_ |= annQSet;
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::finAnneal() {
    syncBits();
    calculate_E();
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::annealOneStepNaive(real G, real kT) {
    real twoDivM = real(2.) / real(m_);
    real coef = std::log(std::tanh(G / kT / m_)) / kT;
    Random &random = random_[0];
    int N = N0_ + N1_;
    for (int loop = 0; loop < IdxType(N * m_); ++loop) {
        int x = random.randInt(N);
        int y = random.randInt(m_);
        if (x < N0_) {
            real qyx = matQ0_(y, x);
            real sum = J_.transpose().row(x).dot(matQ1_.row(y));
            real dE = - twoDivM * qyx * (h0_(x) + sum);
            int neibour0 = (y == 0) ? m_ - 1 : y - 1;
            int neibour1 = (y == m_ - 1) ? 0 : y + 1;
            dE -= qyx * (matQ0_(neibour0, x) + matQ0_(neibour1, x)) * coef;
            real threshold = (dE < real(0.)) ? real(1.) : std::exp(-dE / kT);
            if (threshold > random.random<real>())
                matQ0_(y, x) = - qyx;
        }
        else {
            x -= N0_;
            real qyx = matQ1_(y, x);
            real sum = J_.row(x).dot(matQ0_.row(y));
            real dE = - twoDivM * qyx * (h1_(x) + sum);
            int neibour0 = (y == 0) ? m_ - 1 : y - 1;
            int neibour1 = (y == m_ - 1) ? 0 : y + 1;
            dE -= qyx * (matQ1_(neibour0, x) + matQ1_(neibour1, x)) * coef;
            real threshold = (dE < real(0.)) ? real(1.) : std::exp(-dE / kT);
            if (threshold > random.random<real>())
                matQ1_(y, x) = - qyx;
        }
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::annealOneStepColoring(real G, real kT) {
    annealHalfStepColoring(N1_, matQ1_, h1_, J_, matQ0_, G, kT);
    annealHalfStepColoring(N0_, matQ0_, h0_, J_.transpose(), matQ1_, G, kT);
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::
annealHalfStepColoring(int N, EigenMatrix &qAnneal,
                       const EigenRowVector &h, const EigenMatrix &J,
                       const EigenMatrix &qFixed, real G, real kT) {
    EigenMatrix dEmat = J * qFixed.transpose();
    real twoDivM = real(2.) / m_;
    real tempCoef = std::log(std::tanh(G / kT / m_)) / kT;
    real invKT = real(1.) / kT;

#ifndef _OPENMP
    {
        Random &random = random_[0];
#else
#pragma omp parallel
    {
        Random &random = random_[omp_get_thread_num()];
#pragma omp for
#endif
        for (int im = 0; im < m_; im += 2) {
            for (int iq = 0; iq < N; ++iq) {
                real q = qAnneal(im, iq);
                real dE = - twoDivM * q * (h[iq] + dEmat(iq, im));
                int mNeibour0 = (im + m_ - 1) % m_;
                int mNeibour1 = (im + 1) % m_;
                dE -= q * (qAnneal(mNeibour0, iq) + qAnneal(mNeibour1, iq)) * tempCoef;
                real thresh = dE < real(0.) ? real(1.) : std::exp(- dE * invKT);
                if (thresh > random.random<real>())
                    qAnneal(im, iq) = -q;
            }
        }
#ifdef _OPENMP
#pragma omp for
#endif
        for (int im = 1; im < m_; im += 2) {
            for (int iq = 0; iq < N; ++iq) {
                real q = qAnneal(im, iq);
                real dE = - twoDivM * q * (h[iq] + dEmat(iq, im));
                int mNeibour0 = (im + m_ - 1) % m_;
                int mNeibour1 = (im + 1) % m_;
                dE -= q * (qAnneal(mNeibour0, iq) + qAnneal(mNeibour1, iq)) * tempCoef;
                real thresh = dE < real(0.) ? real(1.) : std::exp(-dE * invKT);
                if (thresh > random.random<real>())
                    qAnneal(im, iq) = -q;
            }
        }
    }
}

template<class real>
void CPUBipartiteGraphAnnealer<real>::syncBits() {
    bitsPairX_.clear();
    bitsPairQ_.clear();
    Bits x0, x1;
    for (int idx = 0; idx < IdxType(m_); ++idx) {
        Bits q0 = extractRow<char>(matQ0_, idx);
        Bits q1 = extractRow<char>(matQ1_, idx);
        bitsPairQ_.pushBack(BitsPairArray::ValueType(q0, q1));
        Bits x0 = x_from_q(q0), x1 = x_from_q(q1);
        bitsPairX_.pushBack(BitsPairArray::ValueType(x0, x1));
    }
}

template class sqaod::CPUBipartiteGraphAnnealer<float>;
template class sqaod::CPUBipartiteGraphAnnealer<double>;
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#ifndef VAST_SYSTEM_RUN_writer_HPP
#define VAST_SYSTEM_RUN_writer_HPP

#include "vast/system/writer_command_base.hpp"

#include <memory>
#include <string>
#include <string_view>

#include <caf/scoped_actor.hpp>
#include <caf/typed_actor.hpp>
#include <caf/typed_event_based_actor.hpp>

#include "vast/expression.hpp"
#include "vast/logger.hpp"

#include "vast/system/node_command.hpp"
#include "vast/system/signal_monitor.hpp"
#include "vast/system/source.hpp"
#include "vast/system/tracker.hpp"

#include "vast/concept/parseable/to.hpp"

#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/parseable/vast/schema.hpp"

using namespace std::chrono_literals;
using namespace caf;

namespace vast::system {

int writer_command_base::run_impl(caf::actor_system& sys, option_map& options,
                              caf::message args) {
  // Get a convenient and blocking way to interact with actors.
  scoped_actor self{sys};
  // Get VAST node.
  auto node_opt = spawn_or_connect_to_node(self, options);
  if (!node_opt)
    return EXIT_FAILURE;
  auto node = std::move(*node_opt);
  /// Spawn an actor that takes care of CTRL+C and friends.
  auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, self);
  auto guard = caf::detail::make_scope_guard([&] {
    self->send_exit(sig_mon, exit_reason::user_shutdown);
  });
  // Spawn a sink.
  VAST_DEBUG("spawning sink with parameters:", deep_to_string(options));
  auto snk_opt = make_sink(self, options, args);
  if (!snk_opt) {
    std::cerr << "unable to spawn sink: " << sys.render(snk_opt.error())
              << std::endl;
    return EXIT_FAILURE;
  }
  auto snk = std::move(*snk_opt);
  // Spawn exporter at the node.
  actor exp;
  // TODO: we need to also include arguments in CLI format from the export
  //       command; we really should forward `options` to the node actor
  //       instead to clean this up
  args = make_message("exporter") + args;
  if (get_or<bool>(options, "continuous", false))
    args += make_message("--continuous");
  if (get_or<bool>(options, "historical", false))
    args += make_message("--historical");
  if (get_or<bool>(options, "unified", false))
    args += make_message("--unified");
  auto max_events = get_or<uint64_t>(options, "events", 0u);
  args += make_message("-e", std::to_string(max_events));
  VAST_DEBUG("spawning exporter with parameters:", to_string(args));
  self->request(node, infinite, "spawn", args).receive(
    [&](const actor& a) {
      exp = a;
    },
    [&](const error& e) {
      VAST_IGNORE_UNUSED(e);
      VAST_ERROR("failed to spawn exporter:", self->system().render(e));
    }
  );
  if (!exp) {
    self->send_exit(snk, exit_reason::user_shutdown);
    return 1;
  }
  // Start the exporter.
  self->send(exp, system::sink_atom::value, snk);
  self->send(exp, system::run_atom::value);
  self->monitor(snk);
  self->monitor(exp);
  auto rc = 0;
  auto stop = false;
  self->do_receive(
    [&](const down_msg& msg) {
      if (msg.source == node)  {
        VAST_DEBUG("received DOWN from node");
        self->send_exit(snk, exit_reason::user_shutdown);
        self->send_exit(exp, exit_reason::user_shutdown);
        rc = 1;
      } else if (msg.source == exp) {
        VAST_DEBUG("received DOWN from exporter");
        self->send_exit(snk, exit_reason::user_shutdown);
      } else if (msg.source == snk) {
        VAST_DEBUG("received DOWN from sink");
        self->send_exit(exp, exit_reason::user_shutdown);
        rc = 1;
      } else {
        VAST_ASSERT(!"received DOWN from inexplicable actor");
      }
      stop = true;
    },
    [&](system::signal_atom, int signal) {
      VAST_DEBUG("got " << ::strsignal(signal));
      if (signal == SIGINT || signal == SIGTERM) {
        self->send_exit(exp, exit_reason::user_shutdown);
        self->send_exit(snk, exit_reason::user_shutdown);
      }
    }
  ).until([&] { return stop; });
  return rc;
}

} // namespace vast::system

#endif
<commit_msg>Fix non-terminating export commands<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#ifndef VAST_SYSTEM_RUN_writer_HPP
#define VAST_SYSTEM_RUN_writer_HPP

#include "vast/system/writer_command_base.hpp"

#include <memory>
#include <string>
#include <string_view>

#include <caf/scoped_actor.hpp>
#include <caf/typed_actor.hpp>
#include <caf/typed_event_based_actor.hpp>

#include "vast/expression.hpp"
#include "vast/logger.hpp"

#include "vast/system/node_command.hpp"
#include "vast/system/signal_monitor.hpp"
#include "vast/system/source.hpp"
#include "vast/system/tracker.hpp"

#include "vast/concept/parseable/to.hpp"

#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/parseable/vast/schema.hpp"

using namespace std::chrono_literals;
using namespace caf;

namespace vast::system {

int writer_command_base::run_impl(caf::actor_system& sys, option_map& options,
                              caf::message args) {
  // Get a convenient and blocking way to interact with actors.
  scoped_actor self{sys};
  // Get VAST node.
  auto node_opt = spawn_or_connect_to_node(self, options);
  if (!node_opt)
    return EXIT_FAILURE;
  auto node = std::move(*node_opt);
  /// Spawn an actor that takes care of CTRL+C and friends.
  auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, self);
  auto guard = caf::detail::make_scope_guard([&] {
    self->send_exit(sig_mon, exit_reason::user_shutdown);
  });
  // Spawn a sink.
  VAST_DEBUG("spawning sink with parameters:", deep_to_string(options));
  auto snk_opt = make_sink(self, options, args);
  if (!snk_opt) {
    std::cerr << "unable to spawn sink: " << sys.render(snk_opt.error())
              << std::endl;
    return EXIT_FAILURE;
  }
  auto snk = std::move(*snk_opt);
  // Spawn exporter at the node.
  actor exp;
  // TODO: we need to also include arguments in CLI format from the export
  //       command; we really should forward `options` to the node actor
  //       instead to clean this up
  args = make_message("exporter") + args;
  if (get_or<bool>(options, "continuous", false))
    args += make_message("--continuous");
  if (get_or<bool>(options, "historical", false))
    args += make_message("--historical");
  if (get_or<bool>(options, "unified", false))
    args += make_message("--unified");
  auto max_events = get_or<uint64_t>(options, "events", 0u);
  args += make_message("-e", std::to_string(max_events));
  VAST_DEBUG("spawning exporter with parameters:", to_string(args));
  self->request(node, infinite, "spawn", args).receive(
    [&](const actor& a) {
      exp = a;
    },
    [&](const error& e) {
      VAST_IGNORE_UNUSED(e);
      VAST_ERROR("failed to spawn exporter:", self->system().render(e));
    }
  );
  if (!exp) {
    self->send_exit(snk, exit_reason::user_shutdown);
    return 1;
  }
  // Start the exporter.
  self->send(exp, system::sink_atom::value, snk);
  self->send(exp, system::run_atom::value);
  self->monitor(snk);
  self->monitor(exp);
  auto rc = 0;
  auto stop = false;
  self->do_receive(
    [&](const down_msg& msg) {
      if (msg.source == node)  {
        VAST_DEBUG("received DOWN from node");
        self->send_exit(snk, exit_reason::user_shutdown);
        self->send_exit(exp, exit_reason::user_shutdown);
        rc = 1;
      } else if (msg.source == exp) {
        VAST_DEBUG("received DOWN from exporter");
        self->send_exit(snk, exit_reason::user_shutdown);
      } else if (msg.source == snk) {
        VAST_DEBUG("received DOWN from sink");
        self->send_exit(exp, exit_reason::user_shutdown);
        rc = 1;
      } else {
        VAST_ASSERT(!"received DOWN from inexplicable actor");
      }
      stop = true;
    },
    [&](system::signal_atom, int signal) {
      VAST_DEBUG("got " << ::strsignal(signal));
      if (signal == SIGINT || signal == SIGTERM) {
        self->send_exit(exp, exit_reason::user_shutdown);
        self->send_exit(snk, exit_reason::user_shutdown);
      }
    }
  ).until([&] { return stop; });
  cleanup(node);
  return rc;
}

} // namespace vast::system

#endif
<|endoftext|>


<commit_before>//
//  file    : KGantt.C
//  date    : 26 oct 2000
//  changed : 10 jan 2001
//  author  : jh
//

#include "KGantt.h"

#include <qcolor.h>
#include <qstylefactory.h>
#include <qscrollview.h>

KGantt::KGantt(KGanttItem* toplevelitem,
	       QWidget* parent, const char * name, WFlags f)
  : QWidget(parent,name,f)
{
#ifdef _DEBUG_
  printf("KGantt::KGantt()\n");
#endif

  if(toplevelitem == 0) {
    _toplevelitem = new KGanttItem(0, "toplevelitem",
			   QDateTime::currentDateTime(),
			   QDateTime::currentDateTime() );
    _toplevelitem->setMode(KGanttItem::Rubberband);
    _deleteItem = true;
  }
  else {
    _toplevelitem = toplevelitem;
    _deleteItem = false;
  }

  setBackgroundColor(QColor(white));

  _splitter = new QSplitter(this);
  QStyle *cdestyle=QStyleFactory::create("CDE");
  if(cdestyle)
	  _splitter->setStyle(cdestyle);

  QPalette pal1(_splitter->palette());
  QPalette pal(_splitter->palette());
  QColorGroup cg(pal.active());
  cg.setColor( QColorGroup::Foreground, blue );
  cg.setColor( QColorGroup::Background, white );
  pal.setActive( cg );

  _splitter->setPalette(pal);

  _ganttlist = new xQGanttListView(_toplevelitem, _splitter);
  _ganttlist->setMinimumWidth(1);
  _ganttlist->setPalette(pal1);

  _ganttbar = new xQGanttBarView(_toplevelitem, _splitter);
  _ganttbar->setPalette(pal1);

  connect(_ganttbar, SIGNAL(contentsMoving(int,int)),
	  _ganttlist, SLOT(contentsMoved(int,int)));

  _ganttlist->setBarView(_ganttbar);

}

KGantt::~KGantt()
///////////////////
{
  if(_deleteItem)
    delete _toplevelitem;
}

void
KGantt::dumpItems()
/////////////////////////
{
  QTextOStream cout(stdout);

  cout << "\n<Gantt>\n";
  cout << " start : " << _toplevelitem->getStart().toString() << endl;
  cout << " end :   " << _toplevelitem->getEnd().toString() << endl;

  _toplevelitem->dump(cout, "  ");

  cout << "</Gantt>\n\n";

}

#include "KGantt.moc"
<commit_msg>Use the standard colors for the splitter, and not the CDE style and white background.<commit_after>//
//  file    : KGantt.C
//  date    : 26 oct 2000
//  changed : 10 jan 2001
//  author  : jh
//

#include "KGantt.h"

#include <qcolor.h>
#include <qstylefactory.h>
#include <qscrollview.h>

KGantt::KGantt(KGanttItem* toplevelitem,
	       QWidget* parent, const char * name, WFlags f)
  : QWidget(parent,name,f)
{
#ifdef _DEBUG_
  printf("KGantt::KGantt()\n");
#endif

  if(toplevelitem == 0) {
    _toplevelitem = new KGanttItem(0, "toplevelitem",
			   QDateTime::currentDateTime(),
			   QDateTime::currentDateTime() );
    _toplevelitem->setMode(KGanttItem::Rubberband);
    _deleteItem = true;
  }
  else {
    _toplevelitem = toplevelitem;
    _deleteItem = false;
  }

  setBackgroundColor(QColor(white));

  _splitter = new QSplitter(this);
/*
//  QStyle *cdestyle=QStyleFactory::create("CDE");
//  if(cdestyle)
//	  _splitter->setStyle(cdestyle);
*/
  QPalette pal1(_splitter->palette());
/*  QPalette pal(_splitter->palette());
  QColorGroup cg(pal.active());
  cg.setColor( QColorGroup::Foreground, blue );
  cg.setColor( QColorGroup::Background, white );
  pal.setActive( cg );

  _splitter->setPalette(pal);*/

  _ganttlist = new xQGanttListView(_toplevelitem, _splitter);
  _ganttlist->setMinimumWidth(1);
  _ganttlist->setPalette(pal1);

  _ganttbar = new xQGanttBarView(_toplevelitem, _splitter);
  _ganttbar->setPalette(pal1);

  connect(_ganttbar, SIGNAL(contentsMoving(int,int)),
	  _ganttlist, SLOT(contentsMoved(int,int)));

  _ganttlist->setBarView(_ganttbar);

}

KGantt::~KGantt()
///////////////////
{
  if(_deleteItem)
    delete _toplevelitem;
}

void
KGantt::dumpItems()
/////////////////////////
{
  QTextOStream cout(stdout);

  cout << "\n<Gantt>\n";
  cout << " start : " << _toplevelitem->getStart().toString() << endl;
  cout << " end :   " << _toplevelitem->getEnd().toString() << endl;

  _toplevelitem->dump(cout, "  ");

  cout << "</Gantt>\n\n";

}

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