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

#include <string>
#include <vector>

#include "ash/desktop_background/desktop_background_controller.h"
#include "ash/desktop_background/desktop_background_controller_observer.h"
#include "ash/shell.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/login/login_manager_test.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wallpaper_manager.h"
#include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/chromeos_paths.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_dbus_thread_manager.h"
#include "chromeos/dbus/fake_session_manager_client.h"
#include "chromeos/dbus/session_manager_client.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include "components/policy/core/common/cloud/policy_builder.h"
#include "crypto/rsa_private_key.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "policy/proto/cloud_policy.pb.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace chromeos {

namespace {

const char kTestUsers[2][19] = { "test-0@example.com", "test-1@example.com" };

const char kRedImageFileName[] = "chromeos/wallpapers/red.jpg";
const char kGreenImageFileName[] = "chromeos/wallpapers/green.jpg";
const char kBlueImageFileName[] = "chromeos/wallpapers/blue.jpg";

const SkColor kRedImageColor = SkColorSetARGB(255, 199, 6, 7);
const SkColor kGreenImageColor = SkColorSetARGB(255, 38, 196, 15);

policy::CloudPolicyStore* GetStoreForUser(const User* user) {
  Profile* profile = UserManager::Get()->GetProfileByUser(user);
  if (!profile) {
    ADD_FAILURE();
    return NULL;
  }
  policy::UserCloudPolicyManagerChromeOS* policy_manager =
      policy::UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile);
  if (!policy_manager) {
    ADD_FAILURE();
    return NULL;
  }
  return policy_manager->core()->store();
}

// Compute the average ARGB color of |bitmap|.
SkColor ComputeAverageColor(const SkBitmap& bitmap) {
  if (bitmap.empty() || bitmap.width() < 1 || bitmap.height() < 1) {
    ADD_FAILURE() << "Empty or invalid bitmap.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  if (bitmap.isNull()) {
    ADD_FAILURE() << "Bitmap has no pixelref.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  if (bitmap.config() == SkBitmap::kNo_Config) {
    ADD_FAILURE() << "Bitmap has not been configured.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  uint64 a = 0, r = 0, g = 0, b = 0;
  bitmap.lockPixels();
  for (int x = 0; x < bitmap.width(); ++x) {
    for (int y = 0; y < bitmap.height(); ++y) {
      const SkColor color = bitmap.getColor(x, y);
      a += SkColorGetA(color);
      r += SkColorGetR(color);
      g += SkColorGetG(color);
      b += SkColorGetB(color);
    }
  }
  bitmap.unlockPixels();
  uint64 pixel_number = bitmap.width() * bitmap.height();
  return SkColorSetARGB((a + pixel_number / 2) / pixel_number,
                        (r + pixel_number / 2) / pixel_number,
                        (g + pixel_number / 2) / pixel_number,
                        (b + pixel_number / 2) / pixel_number);
}

// Obtain background image and return its average ARGB color.
SkColor GetAverageBackgroundColor() {
  const gfx::ImageSkia image =
      ash::Shell::GetInstance()->desktop_background_controller()->
      GetWallpaper();

  const gfx::ImageSkiaRep& representation = image.GetRepresentation(1.);
  if (representation.is_null()) {
    ADD_FAILURE() << "No image representation.";
    return SkColorSetARGB(0, 0, 0, 0);
  }

  const SkBitmap& bitmap = representation.sk_bitmap();
  return ComputeAverageColor(bitmap);
}

}  // namespace

class WallpaperManagerPolicyTest
    : public LoginManagerTest,
      public ash::DesktopBackgroundControllerObserver,
      public testing::WithParamInterface<bool> {
 protected:
  WallpaperManagerPolicyTest()
      : LoginManagerTest(true),
        wallpaper_change_count_(0),
        fake_dbus_thread_manager_(new FakeDBusThreadManager),
        fake_session_manager_client_(new FakeSessionManagerClient) {
    fake_dbus_thread_manager_->SetFakeClients();
    fake_dbus_thread_manager_->SetSessionManagerClient(
        scoped_ptr<SessionManagerClient>(fake_session_manager_client_));
  }

  scoped_ptr<policy::UserPolicyBuilder> GetUserPolicyBuilder(
      const std::string& user_id) {
    scoped_ptr<policy::UserPolicyBuilder>
        user_policy_builder(new policy::UserPolicyBuilder());
    base::FilePath user_keys_dir;
    EXPECT_TRUE(PathService::Get(DIR_USER_POLICY_KEYS, &user_keys_dir));
    const std::string sanitized_user_id =
        CryptohomeClient::GetStubSanitizedUsername(user_id);
    const base::FilePath user_key_file =
        user_keys_dir.AppendASCII(sanitized_user_id)
                     .AppendASCII("policy.pub");
    std::vector<uint8> user_key_bits;
    EXPECT_TRUE(user_policy_builder->GetSigningKey()->
                ExportPublicKey(&user_key_bits));
    EXPECT_TRUE(base::CreateDirectory(user_key_file.DirName()));
    EXPECT_EQ(base::WriteFile(
                  user_key_file,
                  reinterpret_cast<const char*>(user_key_bits.data()),
                  user_key_bits.size()),
              static_cast<int>(user_key_bits.size()));
    user_policy_builder->policy_data().set_username(user_id);
    return user_policy_builder.Pass();
  }

  // LoginManagerTest:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    DBusThreadManager::SetInstanceForTesting(fake_dbus_thread_manager_);
    LoginManagerTest::SetUpInProcessBrowserTestFixture();
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
  }

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // Set the same switches as LoginManagerTest, except that kMultiProfiles is
    // only set when GetParam() is true and except that kLoginProfile is set
    // when GetParam() is false.  The latter seems to be required for the sane
    // start-up of user profiles.
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitch(switches::kForceLoginManagerInTests);
    if (GetParam())
      command_line->AppendSwitch(::switches::kMultiProfiles);
    else
      command_line->AppendSwitchASCII(switches::kLoginProfile, kTestUsers[0]);
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    LoginManagerTest::SetUpOnMainThread();
    ash::Shell::GetInstance()->
        desktop_background_controller()->AddObserver(this);

    // Set up policy signing.
    user_policy_builders_[0] = GetUserPolicyBuilder(kTestUsers[0]);
    user_policy_builders_[1] = GetUserPolicyBuilder(kTestUsers[1]);

    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  }

  virtual void TearDownOnMainThread() OVERRIDE {
    ash::Shell::GetInstance()->
        desktop_background_controller()->RemoveObserver(this);
    LoginManagerTest::TearDownOnMainThread();
  }

  // ash::DesktopBackgroundControllerObserver:
  virtual void OnWallpaperDataChanged() OVERRIDE {
    ++wallpaper_change_count_;
    if (run_loop_)
      run_loop_->Quit();
  }

  void StartLoop() {
    run_loop_.reset(new base::RunLoop);
    run_loop_->Run();
  }

  std::string ConstructPolicy(const std::string& relative_path) const {
    std::string image_data;
    if (!base::ReadFileToString(test_data_dir_.Append(relative_path),
                                &image_data)) {
      ADD_FAILURE();
    }
    std::string policy;
    base::JSONWriter::Write(policy::test::ConstructExternalDataReference(
        embedded_test_server()->GetURL(std::string("/") + relative_path).spec(),
        image_data).get(),
        &policy);
    return policy;
  }

  // Inject |filename| as wallpaper policy for test user |user_number|.  Set
  // empty |filename| to clear policy.
  void InjectPolicy(int user_number, const std::string& filename) {
    ASSERT_TRUE(user_number == 0 || user_number == 1);
    const std::string user_id = kTestUsers[user_number];
    policy::UserPolicyBuilder* builder =
        user_policy_builders_[user_number].get();
    if (filename != "") {
      builder->payload().
          mutable_wallpaperimage()->set_value(ConstructPolicy(filename));
    } else {
      builder->payload().Clear();
    }
    builder->Build();
    fake_session_manager_client_->set_user_policy(user_id, builder->GetBlob());
    const User* user = UserManager::Get()->FindUser(user_id);
    ASSERT_TRUE(user);
    policy::CloudPolicyStore* store = GetStoreForUser(user);
    ASSERT_TRUE(store);
    store->Load();
    ASSERT_EQ(policy::CloudPolicyStore::STATUS_OK, store->status());
    ASSERT_EQ(policy::CloudPolicyValidatorBase::VALIDATION_OK,
              store->validation_status());
  }

  // Obtain WallpaperInfo for |user_number| from WallpaperManager.
  void GetUserWallpaperInfo(int user_number, WallpaperInfo* wallpaper_info) {
    WallpaperManager::Get()->
        GetUserWallpaperInfo(kTestUsers[user_number], wallpaper_info);
  }

  base::FilePath test_data_dir_;
  scoped_ptr<base::RunLoop> run_loop_;
  int wallpaper_change_count_;
  scoped_ptr<policy::UserPolicyBuilder> user_policy_builders_[2];
  FakeDBusThreadManager* fake_dbus_thread_manager_;
  FakeSessionManagerClient* fake_session_manager_client_;

 private:
  DISALLOW_COPY_AND_ASSIGN(WallpaperManagerPolicyTest);
};

IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_SetResetClear) {
  RegisterUser(kTestUsers[0]);
  RegisterUser(kTestUsers[1]);
  StartupUtils::MarkOobeCompleted();
}

// Verifies that the wallpaper can be set and re-set through policy and that
// setting policy for a user that is not logged in doesn't affect the current
// user.  Also verifies that after the policy has been cleared, the wallpaper
// reverts to default.
IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, SetResetClear) {
  WallpaperInfo info;
  LoginUser(kTestUsers[0]);
  base::RunLoop().RunUntilIdle();

  // First user: Wait until default wallpaper has been loaded (happens
  // automatically) and store color to recognize it later.
  if (wallpaper_change_count_ == 0) {
    LOG(INFO) << "No wallpaper change observed, yet.  Starting loop.";
    StartLoop();
  } else {
    LOG(INFO) << "Wallpaper changed already " << wallpaper_change_count_
              << " time(s).  Not starting loop.";
  }
  const SkColor original_background_color = GetAverageBackgroundColor();

  // Second user: Set wallpaper policy to blue image.  This should not result in
  // a wallpaper change, which is checked at the very end of this test.
  InjectPolicy(1, kBlueImageFileName);

  // First user: Set wallpaper policy to red image and verify average color.
  InjectPolicy(0, kRedImageFileName);
  StartLoop();
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::POLICY, info.type);
  ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());

  // First user: Set wallpaper policy to green image and verify average color.
  InjectPolicy(0, kGreenImageFileName);
  StartLoop();
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::POLICY, info.type);
  ASSERT_EQ(kGreenImageColor, GetAverageBackgroundColor());

  // First user: Clear wallpaper policy and verify that the default wallpaper is
  // set again.
  InjectPolicy(0, "");
  StartLoop();
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::DEFAULT, info.type);
  ASSERT_EQ(original_background_color, GetAverageBackgroundColor());

  // Check wallpaper change count to ensure that setting the second user's
  // wallpaper didn't have any effect.
  ASSERT_EQ(4, wallpaper_change_count_);
}

INSTANTIATE_TEST_CASE_P(WallpaperManagerPolicyTestInstantiation,
                        WallpaperManagerPolicyTest, testing::Bool());

}  // namespace chromeos
<commit_msg>Add wallpaper policy browsertest for login screen.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <vector>

#include "ash/desktop_background/desktop_background_controller.h"
#include "ash/desktop_background/desktop_background_controller_observer.h"
#include "ash/shell.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/login/login_manager_test.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wallpaper_manager.h"
#include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/chromeos_paths.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_dbus_thread_manager.h"
#include "chromeos/dbus/fake_session_manager_client.h"
#include "chromeos/dbus/session_manager_client.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include "components/policy/core/common/cloud/policy_builder.h"
#include "crypto/rsa_private_key.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "policy/proto/cloud_policy.pb.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace chromeos {

namespace {

const char kTestUsers[2][19] = { "test-0@example.com", "test-1@example.com" };

const char kRedImageFileName[] = "chromeos/wallpapers/red.jpg";
const char kGreenImageFileName[] = "chromeos/wallpapers/green.jpg";
const char kBlueImageFileName[] = "chromeos/wallpapers/blue.jpg";

const SkColor kRedImageColor = SkColorSetARGB(255, 199, 6, 7);
const SkColor kGreenImageColor = SkColorSetARGB(255, 38, 196, 15);

policy::CloudPolicyStore* GetStoreForUser(const User* user) {
  Profile* profile = UserManager::Get()->GetProfileByUser(user);
  if (!profile) {
    ADD_FAILURE();
    return NULL;
  }
  policy::UserCloudPolicyManagerChromeOS* policy_manager =
      policy::UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile);
  if (!policy_manager) {
    ADD_FAILURE();
    return NULL;
  }
  return policy_manager->core()->store();
}

// Compute the average ARGB color of |bitmap|.
SkColor ComputeAverageColor(const SkBitmap& bitmap) {
  if (bitmap.empty() || bitmap.width() < 1 || bitmap.height() < 1) {
    ADD_FAILURE() << "Empty or invalid bitmap.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  if (bitmap.isNull()) {
    ADD_FAILURE() << "Bitmap has no pixelref.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  if (bitmap.config() == SkBitmap::kNo_Config) {
    ADD_FAILURE() << "Bitmap has not been configured.";
    return SkColorSetARGB(0, 0, 0, 0);
  }
  uint64 a = 0, r = 0, g = 0, b = 0;
  bitmap.lockPixels();
  for (int x = 0; x < bitmap.width(); ++x) {
    for (int y = 0; y < bitmap.height(); ++y) {
      const SkColor color = bitmap.getColor(x, y);
      a += SkColorGetA(color);
      r += SkColorGetR(color);
      g += SkColorGetG(color);
      b += SkColorGetB(color);
    }
  }
  bitmap.unlockPixels();
  uint64 pixel_number = bitmap.width() * bitmap.height();
  return SkColorSetARGB((a + pixel_number / 2) / pixel_number,
                        (r + pixel_number / 2) / pixel_number,
                        (g + pixel_number / 2) / pixel_number,
                        (b + pixel_number / 2) / pixel_number);
}

// Obtain background image and return its average ARGB color.
SkColor GetAverageBackgroundColor() {
  const gfx::ImageSkia image =
      ash::Shell::GetInstance()->desktop_background_controller()->
      GetWallpaper();

  const gfx::ImageSkiaRep& representation = image.GetRepresentation(1.);
  if (representation.is_null()) {
    ADD_FAILURE() << "No image representation.";
    return SkColorSetARGB(0, 0, 0, 0);
  }

  const SkBitmap& bitmap = representation.sk_bitmap();
  return ComputeAverageColor(bitmap);
}

}  // namespace

class WallpaperManagerPolicyTest
    : public LoginManagerTest,
      public ash::DesktopBackgroundControllerObserver,
      public testing::WithParamInterface<bool> {
 protected:
  WallpaperManagerPolicyTest()
      : LoginManagerTest(true),
        wallpaper_change_count_(0),
        fake_dbus_thread_manager_(new FakeDBusThreadManager),
        fake_session_manager_client_(new FakeSessionManagerClient) {
    fake_dbus_thread_manager_->SetFakeClients();
    fake_dbus_thread_manager_->SetSessionManagerClient(
        scoped_ptr<SessionManagerClient>(fake_session_manager_client_));
  }

  scoped_ptr<policy::UserPolicyBuilder> GetUserPolicyBuilder(
      const std::string& user_id) {
    scoped_ptr<policy::UserPolicyBuilder>
        user_policy_builder(new policy::UserPolicyBuilder());
    base::FilePath user_keys_dir;
    EXPECT_TRUE(PathService::Get(DIR_USER_POLICY_KEYS, &user_keys_dir));
    const std::string sanitized_user_id =
        CryptohomeClient::GetStubSanitizedUsername(user_id);
    const base::FilePath user_key_file =
        user_keys_dir.AppendASCII(sanitized_user_id)
                     .AppendASCII("policy.pub");
    std::vector<uint8> user_key_bits;
    EXPECT_TRUE(user_policy_builder->GetSigningKey()->
                ExportPublicKey(&user_key_bits));
    EXPECT_TRUE(base::CreateDirectory(user_key_file.DirName()));
    EXPECT_EQ(base::WriteFile(
                  user_key_file,
                  reinterpret_cast<const char*>(user_key_bits.data()),
                  user_key_bits.size()),
              static_cast<int>(user_key_bits.size()));
    user_policy_builder->policy_data().set_username(user_id);
    return user_policy_builder.Pass();
  }

  // LoginManagerTest:
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    DBusThreadManager::SetInstanceForTesting(fake_dbus_thread_manager_);
    LoginManagerTest::SetUpInProcessBrowserTestFixture();
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_));
  }

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // Set the same switches as LoginManagerTest, except that kMultiProfiles is
    // only set when GetParam() is true and except that kLoginProfile is set
    // when GetParam() is false.  The latter seems to be required for the sane
    // start-up of user profiles.
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitch(switches::kForceLoginManagerInTests);
    if (GetParam())
      command_line->AppendSwitch(::switches::kMultiProfiles);
    else
      command_line->AppendSwitchASCII(switches::kLoginProfile, kTestUsers[0]);
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    LoginManagerTest::SetUpOnMainThread();
    ash::Shell::GetInstance()->
        desktop_background_controller()->AddObserver(this);

    // Set up policy signing.
    user_policy_builders_[0] = GetUserPolicyBuilder(kTestUsers[0]);
    user_policy_builders_[1] = GetUserPolicyBuilder(kTestUsers[1]);

    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  }

  virtual void TearDownOnMainThread() OVERRIDE {
    ash::Shell::GetInstance()->
        desktop_background_controller()->RemoveObserver(this);
    LoginManagerTest::TearDownOnMainThread();
  }

  // ash::DesktopBackgroundControllerObserver:
  virtual void OnWallpaperDataChanged() OVERRIDE {
    ++wallpaper_change_count_;
    if (run_loop_)
      run_loop_->Quit();
  }

  // Runs the loop until wallpaper has changed at least |count| times in total.
  void RunUntilWallpaperChangeCount(int count) {
    while (wallpaper_change_count_ < count) {
      run_loop_.reset(new base::RunLoop);
      run_loop_->Run();
    }
  }

  std::string ConstructPolicy(const std::string& relative_path) const {
    std::string image_data;
    if (!base::ReadFileToString(test_data_dir_.Append(relative_path),
                                &image_data)) {
      ADD_FAILURE();
    }
    std::string policy;
    base::JSONWriter::Write(policy::test::ConstructExternalDataReference(
        embedded_test_server()->GetURL(std::string("/") + relative_path).spec(),
        image_data).get(),
        &policy);
    return policy;
  }

  // Inject |filename| as wallpaper policy for test user |user_number|.  Set
  // empty |filename| to clear policy.
  void InjectPolicy(int user_number, const std::string& filename) {
    ASSERT_TRUE(user_number == 0 || user_number == 1);
    const std::string user_id = kTestUsers[user_number];
    policy::UserPolicyBuilder* builder =
        user_policy_builders_[user_number].get();
    if (filename != "") {
      builder->payload().
          mutable_wallpaperimage()->set_value(ConstructPolicy(filename));
    } else {
      builder->payload().Clear();
    }
    builder->Build();
    fake_session_manager_client_->set_user_policy(user_id, builder->GetBlob());
    const User* user = UserManager::Get()->FindUser(user_id);
    ASSERT_TRUE(user);
    policy::CloudPolicyStore* store = GetStoreForUser(user);
    ASSERT_TRUE(store);
    store->Load();
    ASSERT_EQ(policy::CloudPolicyStore::STATUS_OK, store->status());
    ASSERT_EQ(policy::CloudPolicyValidatorBase::VALIDATION_OK,
              store->validation_status());
  }

  // Obtain WallpaperInfo for |user_number| from WallpaperManager.
  void GetUserWallpaperInfo(int user_number, WallpaperInfo* wallpaper_info) {
    WallpaperManager::Get()->
        GetUserWallpaperInfo(kTestUsers[user_number], wallpaper_info);
  }

  base::FilePath test_data_dir_;
  scoped_ptr<base::RunLoop> run_loop_;
  int wallpaper_change_count_;
  scoped_ptr<policy::UserPolicyBuilder> user_policy_builders_[2];
  FakeDBusThreadManager* fake_dbus_thread_manager_;
  FakeSessionManagerClient* fake_session_manager_client_;

 private:
  DISALLOW_COPY_AND_ASSIGN(WallpaperManagerPolicyTest);
};

IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_SetResetClear) {
  RegisterUser(kTestUsers[0]);
  RegisterUser(kTestUsers[1]);
  StartupUtils::MarkOobeCompleted();
}

// Verifies that the wallpaper can be set and re-set through policy and that
// setting policy for a user that is not logged in doesn't affect the current
// user.  Also verifies that after the policy has been cleared, the wallpaper
// reverts to default.
IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, SetResetClear) {
  WallpaperInfo info;
  LoginUser(kTestUsers[0]);
  base::RunLoop().RunUntilIdle();

  // First user: Wait until default wallpaper has been loaded (happens
  // automatically) and store color to recognize it later.
  RunUntilWallpaperChangeCount(1);
  const SkColor original_background_color = GetAverageBackgroundColor();

  // Second user: Set wallpaper policy to blue image.  This should not result in
  // a wallpaper change, which is checked at the very end of this test.
  InjectPolicy(1, kBlueImageFileName);

  // First user: Set wallpaper policy to red image and verify average color.
  InjectPolicy(0, kRedImageFileName);
  RunUntilWallpaperChangeCount(2);
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::POLICY, info.type);
  ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());

  // First user: Set wallpaper policy to green image and verify average color.
  InjectPolicy(0, kGreenImageFileName);
  RunUntilWallpaperChangeCount(3);
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::POLICY, info.type);
  ASSERT_EQ(kGreenImageColor, GetAverageBackgroundColor());

  // First user: Clear wallpaper policy and verify that the default wallpaper is
  // set again.
  InjectPolicy(0, "");
  RunUntilWallpaperChangeCount(4);
  GetUserWallpaperInfo(0, &info);
  ASSERT_EQ(User::DEFAULT, info.type);
  ASSERT_EQ(original_background_color, GetAverageBackgroundColor());

  // Check wallpaper change count to ensure that setting the second user's
  // wallpaper didn't have any effect.
  ASSERT_EQ(4, wallpaper_change_count_);
}

IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest,
                       PRE_PRE_WallpaperOnLoginScreen) {
  RegisterUser(kTestUsers[0]);
  StartupUtils::MarkOobeCompleted();
}

IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, PRE_WallpaperOnLoginScreen) {
  LoginUser(kTestUsers[0]);

  // Wait until default wallpaper has been loaded.
  RunUntilWallpaperChangeCount(1);

  // Set wallpaper policy to red image.
  InjectPolicy(0, kRedImageFileName);

  // Run until wallpaper has changed.
  RunUntilWallpaperChangeCount(2);
}

IN_PROC_BROWSER_TEST_P(WallpaperManagerPolicyTest, WallpaperOnLoginScreen) {
  // Wait for active pod's wallpaper to be loaded.
  RunUntilWallpaperChangeCount(1);
  ASSERT_EQ(kRedImageColor, GetAverageBackgroundColor());
}

INSTANTIATE_TEST_CASE_P(WallpaperManagerPolicyTestInstantiation,
                        WallpaperManagerPolicyTest, testing::Bool());

}  // namespace chromeos
<|endoftext|>


<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include "CameraServer.h"
#include "WPIErrors.h"
#include "Utility.h"

#include <iostream>
#include <chrono>
#include <cstring>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>

constexpr uint8_t CameraServer::kMagicNumber[];

CameraServer* CameraServer::GetInstance() {
  static CameraServer instance;
  return &instance;
}

CameraServer::CameraServer()
    : m_camera(),
      m_serverThread(&CameraServer::Serve, this),
      m_captureThread(),
      m_imageMutex(),
      m_newImageVariable(),
      m_dataPool(3),
      m_quality(50),
      m_autoCaptureStarted(false),
      m_hwClient(true),
      m_imageData(nullptr, 0, 0, false) {
  for (int i = 0; i < 3; i++) m_dataPool.push_back(new uint8_t[kMaxImageSize]);
}

void CameraServer::FreeImageData(
    std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData) {
  if (std::get<3>(imageData))
    imaqDispose(std::get<0>(imageData));
  else if (std::get<0>(imageData) != nullptr) {
    std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
    m_dataPool.push_back(std::get<0>(imageData));
  }
}

void CameraServer::SetImageData(uint8_t* data, unsigned int size,
                                unsigned int start, bool imaqData) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  FreeImageData(m_imageData);
  m_imageData = std::make_tuple(data, size, start, imaqData);
  m_newImageVariable.notify_all();
}

void CameraServer::SetImage(Image const* image) {
  unsigned int dataSize = 0;
  uint8_t* data =
      (uint8_t*)imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG,
                            10 * m_quality, &dataSize);

  // If we're using a HW camera, then find the start of the data
  bool hwClient;
  {
    // Make a local copy of the hwClient variable so that we can safely use it.
    std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
    hwClient = m_hwClient;
  }
  unsigned int start = 0;
  if (hwClient) {
    while (start < dataSize - 1) {
      if (data[start] == 0xFF && data[start + 1] == 0xD8)
        break;
      else
        start++;
    }
  }
  dataSize -= start;

  wpi_assert(dataSize > 2);
  SetImageData(data, dataSize, start, true);
}

void CameraServer::AutoCapture() {
  Image* frame = imaqCreateImage(IMAQ_IMAGE_RGB, 0);

  while (true) {
    bool hwClient;
    uint8_t* data = nullptr;
    {
      std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
      hwClient = m_hwClient;
      if (hwClient) {
        data = m_dataPool.back();
        m_dataPool.pop_back();
      }
    }

    if (hwClient) {
      unsigned int size = m_camera->GetImageData(data, kMaxImageSize);
      SetImageData(data, size);
    } else {
      m_camera->GetImage(frame);
      SetImage(frame);
    }
  }
}

void CameraServer::StartAutomaticCapture(char const* cameraName) {
  std::shared_ptr<USBCamera> camera =
      std::make_shared<USBCamera>(cameraName, true);
  camera->OpenCamera();
  StartAutomaticCapture(camera);
}

void CameraServer::StartAutomaticCapture(std::shared_ptr<USBCamera> camera) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  if (m_autoCaptureStarted) return;

  m_camera = camera;
  m_camera->StartCapture();

  m_captureThread = std::thread(&CameraServer::AutoCapture, this);
  m_captureThread.detach();
  m_autoCaptureStarted = true;
}

bool CameraServer::IsAutoCaptureStarted() {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  return m_autoCaptureStarted;
}

void CameraServer::SetSize(unsigned int size) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  if (!m_camera) return;
  if (size == kSize160x120)
    m_camera->SetSize(160, 120);
  else if (size == kSize320x240)
    m_camera->SetSize(320, 240);
  else if (size == kSize640x480)
    m_camera->SetSize(640, 480);
}

void CameraServer::SetQuality(unsigned int quality) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  m_quality = quality > 100 ? 100 : quality;
}

unsigned int CameraServer::GetQuality() {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  return m_quality;
}

void CameraServer::Serve() {
  int sock = socket(AF_INET, SOCK_STREAM, 0);

  if (sock == -1) {
    wpi_setErrnoError();
    return;
  }

  int reuseAddr = 1;
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr,
                 sizeof(reuseAddr)) == -1)
    wpi_setErrnoError();

  sockaddr_in address, clientAddress;

  memset(&address, 0, sizeof(address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = htonl(INADDR_ANY);
  address.sin_port = htons(kPort);

  if (bind(sock, (struct sockaddr*)&address, sizeof(address)) == -1)
    wpi_setErrnoError();

  if (listen(sock, 10) == -1) wpi_setErrnoError();

  while (true) {
    socklen_t clientAddressLen = sizeof(clientAddress);

    int conn =
        accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen);
    if (conn == -1) {
      wpi_setErrnoError();
      continue;
    }

    Request req;
    if (read(conn, &req, sizeof(req)) == -1) {
      wpi_setErrnoError();
      close(conn);
      continue;
    } else {
      req.fps = ntohl(req.fps);
      req.compression = ntohl(req.compression);
      req.size = ntohl(req.size);
    }

    // TODO: Support the SW Compression. The rest of the code below will work as
    // though this
    // check isn't here
    if (req.compression != kHardwareCompression) {
      wpi_setWPIErrorWithContext(IncompatibleState,
                                 "Choose \"USB Camera HW\" on the dashboard");
      close(conn);
      continue;
    }

    {
      // Wait for the camera to be setw
      std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);
      if (!m_camera) {
        std::cout << "Camera not yet ready, awaiting first image" << std::endl;
        m_newImageVariable.wait(lock);
      }
      m_hwClient = req.compression == kHardwareCompression;
      if (!m_hwClient)
        SetQuality(100 - req.compression);
      else if (m_camera)
        m_camera->SetFPS(req.fps);
      SetSize(req.size);
    }

    auto period = std::chrono::microseconds(1000000) / req.fps;
    while (true) {
      auto startTime = std::chrono::steady_clock::now();
      std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData;
      {
        std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);
        m_newImageVariable.wait(lock);
        imageData = m_imageData;
        m_imageData = std::make_tuple<uint8_t*>(nullptr, 0, 0, false);
      }

      unsigned int size = std::get<1>(imageData);
      unsigned int netSize = htonl(size);
      unsigned int start = std::get<2>(imageData);
      uint8_t* data = std::get<0>(imageData);

      if (data == nullptr) continue;

      if (write(conn, kMagicNumber, sizeof(kMagicNumber)) == -1) {
        wpi_setErrnoErrorWithContext(
            "[CameraServer] Error sending magic number");
        FreeImageData(imageData);
        break;
      }
      if (write(conn, &netSize, sizeof(netSize)) == -1) {
        wpi_setErrnoErrorWithContext("[CameraServer] Error sending image size");
        FreeImageData(imageData);
        break;
      }
      if (write(conn, &data[start], sizeof(uint8_t) * size) == -1) {
        wpi_setErrnoErrorWithContext("[CameraServer] Error sending image data");
        FreeImageData(imageData);
        break;
      }
      FreeImageData(imageData);
      std::this_thread::sleep_until(startTime + period);
    }
    close(conn);
  }
  close(sock);
}
<commit_msg>Fix C++ CameraServer request handling.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include "CameraServer.h"
#include "WPIErrors.h"
#include "Utility.h"

#include <iostream>
#include <chrono>
#include <cstring>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>

constexpr uint8_t CameraServer::kMagicNumber[];

CameraServer* CameraServer::GetInstance() {
  static CameraServer instance;
  return &instance;
}

CameraServer::CameraServer()
    : m_camera(),
      m_serverThread(&CameraServer::Serve, this),
      m_captureThread(),
      m_imageMutex(),
      m_newImageVariable(),
      m_dataPool(3),
      m_quality(50),
      m_autoCaptureStarted(false),
      m_hwClient(true),
      m_imageData(nullptr, 0, 0, false) {
  for (int i = 0; i < 3; i++) m_dataPool.push_back(new uint8_t[kMaxImageSize]);
}

void CameraServer::FreeImageData(
    std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData) {
  if (std::get<3>(imageData))
    imaqDispose(std::get<0>(imageData));
  else if (std::get<0>(imageData) != nullptr) {
    std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
    m_dataPool.push_back(std::get<0>(imageData));
  }
}

void CameraServer::SetImageData(uint8_t* data, unsigned int size,
                                unsigned int start, bool imaqData) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  FreeImageData(m_imageData);
  m_imageData = std::make_tuple(data, size, start, imaqData);
  m_newImageVariable.notify_all();
}

void CameraServer::SetImage(Image const* image) {
  unsigned int dataSize = 0;
  uint8_t* data =
      (uint8_t*)imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG,
                            10 * m_quality, &dataSize);

  // If we're using a HW camera, then find the start of the data
  bool hwClient;
  {
    // Make a local copy of the hwClient variable so that we can safely use it.
    std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
    hwClient = m_hwClient;
  }
  unsigned int start = 0;
  if (hwClient) {
    while (start < dataSize - 1) {
      if (data[start] == 0xFF && data[start + 1] == 0xD8)
        break;
      else
        start++;
    }
  }
  dataSize -= start;

  wpi_assert(dataSize > 2);
  SetImageData(data, dataSize, start, true);
}

void CameraServer::AutoCapture() {
  Image* frame = imaqCreateImage(IMAQ_IMAGE_RGB, 0);

  while (true) {
    bool hwClient;
    uint8_t* data = nullptr;
    {
      std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
      hwClient = m_hwClient;
      if (hwClient) {
        data = m_dataPool.back();
        m_dataPool.pop_back();
      }
    }

    if (hwClient) {
      unsigned int size = m_camera->GetImageData(data, kMaxImageSize);
      SetImageData(data, size);
    } else {
      m_camera->GetImage(frame);
      SetImage(frame);
    }
  }
}

void CameraServer::StartAutomaticCapture(char const* cameraName) {
  std::shared_ptr<USBCamera> camera =
      std::make_shared<USBCamera>(cameraName, true);
  camera->OpenCamera();
  StartAutomaticCapture(camera);
}

void CameraServer::StartAutomaticCapture(std::shared_ptr<USBCamera> camera) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  if (m_autoCaptureStarted) return;

  m_camera = camera;
  m_camera->StartCapture();

  m_captureThread = std::thread(&CameraServer::AutoCapture, this);
  m_captureThread.detach();
  m_autoCaptureStarted = true;
}

bool CameraServer::IsAutoCaptureStarted() {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  return m_autoCaptureStarted;
}

void CameraServer::SetSize(unsigned int size) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  if (!m_camera) return;
  if (size == kSize160x120)
    m_camera->SetSize(160, 120);
  else if (size == kSize320x240)
    m_camera->SetSize(320, 240);
  else if (size == kSize640x480)
    m_camera->SetSize(640, 480);
}

void CameraServer::SetQuality(unsigned int quality) {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  m_quality = quality > 100 ? 100 : quality;
}

unsigned int CameraServer::GetQuality() {
  std::lock_guard<priority_recursive_mutex> lock(m_imageMutex);
  return m_quality;
}

void CameraServer::Serve() {
  int sock = socket(AF_INET, SOCK_STREAM, 0);

  if (sock == -1) {
    wpi_setErrnoError();
    return;
  }

  int reuseAddr = 1;
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr,
                 sizeof(reuseAddr)) == -1)
    wpi_setErrnoError();

  sockaddr_in address, clientAddress;

  memset(&address, 0, sizeof(address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = htonl(INADDR_ANY);
  address.sin_port = htons(kPort);

  if (bind(sock, (struct sockaddr*)&address, sizeof(address)) == -1)
    wpi_setErrnoError();

  if (listen(sock, 10) == -1) wpi_setErrnoError();

  while (true) {
    socklen_t clientAddressLen = sizeof(clientAddress);

    int conn =
        accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen);
    if (conn == -1) {
      wpi_setErrnoError();
      continue;
    }

    Request req;
    char reqBuf[sizeof(req)];
    size_t reqPos = 0;

    while (reqPos < sizeof(req)) {
      ssize_t sizeRead = read(conn, &reqBuf[reqPos], sizeof(req) - reqPos);
      if (sizeRead < 0) break;
      reqPos += sizeRead;
    }

    if (reqPos < sizeof(req)) {
      wpi_setErrnoError();
      close(conn);
      continue;
    }

    memcpy(&req, reqBuf, sizeof(req));
    req.fps = ntohl(req.fps);
    req.compression = ntohl(req.compression);
    req.size = ntohl(req.size);

    // TODO: Support the SW Compression. The rest of the code below will work as
    // though this
    // check isn't here
    if (req.compression != kHardwareCompression) {
      wpi_setWPIErrorWithContext(IncompatibleState,
                                 "Choose \"USB Camera HW\" on the dashboard");
      close(conn);
      continue;
    }

    {
      // Wait for the camera to be setw
      std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);
      if (!m_camera) {
        std::cout << "Camera not yet ready, awaiting first image" << std::endl;
        m_newImageVariable.wait(lock);
      }
      m_hwClient = req.compression == kHardwareCompression;
      if (!m_hwClient)
        SetQuality(100 - req.compression);
      else if (m_camera)
        m_camera->SetFPS(req.fps);
      SetSize(req.size);
    }

    auto period = std::chrono::microseconds(1000000) / req.fps;
    while (true) {
      auto startTime = std::chrono::steady_clock::now();
      std::tuple<uint8_t*, unsigned int, unsigned int, bool> imageData;
      {
        std::unique_lock<priority_recursive_mutex> lock(m_imageMutex);
        m_newImageVariable.wait(lock);
        imageData = m_imageData;
        m_imageData = std::make_tuple<uint8_t*>(nullptr, 0, 0, false);
      }

      unsigned int size = std::get<1>(imageData);
      unsigned int netSize = htonl(size);
      unsigned int start = std::get<2>(imageData);
      uint8_t* data = std::get<0>(imageData);

      if (data == nullptr) continue;

      if (write(conn, kMagicNumber, sizeof(kMagicNumber)) == -1) {
        wpi_setErrnoErrorWithContext(
            "[CameraServer] Error sending magic number");
        FreeImageData(imageData);
        break;
      }
      if (write(conn, &netSize, sizeof(netSize)) == -1) {
        wpi_setErrnoErrorWithContext("[CameraServer] Error sending image size");
        FreeImageData(imageData);
        break;
      }
      if (write(conn, &data[start], sizeof(uint8_t) * size) == -1) {
        wpi_setErrnoErrorWithContext("[CameraServer] Error sending image data");
        FreeImageData(imageData);
        break;
      }
      FreeImageData(imageData);
      std::this_thread::sleep_until(startTime + period);
    }
    close(conn);
  }
  close(sock);
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include <hdfs.h>
#include "THDFSFileTransport.h"

using namespace std;
using std::shared_ptr;

namespace apache { namespace thrift { namespace transport {

void THDFSFileTransport::open() {
  // THDFSFileTransport does not handle resource alloc/release.
  // An open HDFSFile handle must exist by now
  if (!isOpen()) {
    throw TTransportException(TTransportException::NOT_OPEN,
                              "THDFSFileTransport::open()");
  }
}

void THDFSFileTransport::close() {
  // THDFSFileTransport does not handle resource alloc/release
  return;
}

uint32_t THDFSFileTransport::read(uint8_t* buf, uint32_t len) {
  tSize rv = hdfsRead(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);
  if (rv < 0) {
    int errno_copy = errno;
    throw TTransportException(TTransportException::UNKNOWN,
                              "THDFSFileTransport::read()",
                              errno_copy);
  } else if (rv == 0) {
    throw TTransportException(TTransportException::END_OF_FILE,
                              "THDFSFileTransport::read()");
  }
  return rv;
}

void THDFSFileTransport::write(const uint8_t* buf, uint32_t len) {
  tSize rv = hdfsWrite(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);
  if (rv < 0) {
    int errno_copy = errno;
    throw TTransportException(TTransportException::UNKNOWN,
                              "THDFSFileTransport::write()",
                              errno_copy);
  } else if (rv != len) {
      throw TTransportException(TTransportException::INTERRUPTED,
                                "THDFSFileTransport::write()");
  }
}

}}} // apache::thrift::transport
<commit_msg>Fix header ordering lint failures<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include "THDFSFileTransport.h"
#include <hdfs.h>

using namespace std;
using std::shared_ptr;

namespace apache { namespace thrift { namespace transport {

void THDFSFileTransport::open() {
  // THDFSFileTransport does not handle resource alloc/release.
  // An open HDFSFile handle must exist by now
  if (!isOpen()) {
    throw TTransportException(TTransportException::NOT_OPEN,
                              "THDFSFileTransport::open()");
  }
}

void THDFSFileTransport::close() {
  // THDFSFileTransport does not handle resource alloc/release
  return;
}

uint32_t THDFSFileTransport::read(uint8_t* buf, uint32_t len) {
  tSize rv = hdfsRead(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);
  if (rv < 0) {
    int errno_copy = errno;
    throw TTransportException(TTransportException::UNKNOWN,
                              "THDFSFileTransport::read()",
                              errno_copy);
  } else if (rv == 0) {
    throw TTransportException(TTransportException::END_OF_FILE,
                              "THDFSFileTransport::read()");
  }
  return rv;
}

void THDFSFileTransport::write(const uint8_t* buf, uint32_t len) {
  tSize rv = hdfsWrite(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len);
  if (rv < 0) {
    int errno_copy = errno;
    throw TTransportException(TTransportException::UNKNOWN,
                              "THDFSFileTransport::write()",
                              errno_copy);
  } else if (rv != len) {
      throw TTransportException(TTransportException::INTERRUPTED,
                                "THDFSFileTransport::write()");
  }
}

}}} // apache::thrift::transport
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const deUint32 knownDriverIds[] =
{
	// Specified in the Vulkan registry (vk.xml)
	1,	// author = "Advanced Micro Devices, Inc."   comment = "AMD proprietary driver"
	2,	// author = "Advanced Micro Devices, Inc."   comment = "AMD open-source driver"
	3,	// author = "Mesa open source project"       comment = "Mesa RADV driver"
	4,	// author = "NVIDIA Corporation"             comment = "NVIDIA proprietary driver"
	5,	// author = "Intel Corporation"              comment = "Intel proprietary Windows driver"
	6,	// author = "Intel Corporation"              comment = "Intel open-source Mesa driver"
	7,	// author = "Imagination Technologies"       comment = "Imagination proprietary driver"
	8,	// author = "Qualcomm Technologies, Inc."    comment = "Qualcomm proprietary driver"
	9,	// author = "Arm Limited"                    comment = "Arm proprietary driver"
	10,	// <enum value="10"      name="VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR"        comment="Google LLC"/>
	11,	// <enum value="11"      name="VK_DRIVER_ID_GGP_PROPRIETARY_KHR"           comment="Google LLC"/>
	12,	// <enum value="12"      name="VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR"      comment="Broadcom Inc."/>
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
	makeConformanceVersion(1, 1, 2, 3),
	makeConformanceVersion(1, 1, 2, 2),
	makeConformanceVersion(1, 1, 2, 1),
	makeConformanceVersion(1, 1, 2, 0),
	makeConformanceVersion(1, 1, 1, 3),
	makeConformanceVersion(1, 1, 1, 2),
	makeConformanceVersion(1, 1, 1, 1),
	makeConformanceVersion(1, 1, 1, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)
	{
		if (deviceDriverProperties.driverID == *pDriverId)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<commit_msg>Whitelist Vulkan CTS 1.2.1.0<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const deUint32 knownDriverIds[] =
{
	// Specified in the Vulkan registry (vk.xml)
	1,	// author = "Advanced Micro Devices, Inc."   comment = "AMD proprietary driver"
	2,	// author = "Advanced Micro Devices, Inc."   comment = "AMD open-source driver"
	3,	// author = "Mesa open source project"       comment = "Mesa RADV driver"
	4,	// author = "NVIDIA Corporation"             comment = "NVIDIA proprietary driver"
	5,	// author = "Intel Corporation"              comment = "Intel proprietary Windows driver"
	6,	// author = "Intel Corporation"              comment = "Intel open-source Mesa driver"
	7,	// author = "Imagination Technologies"       comment = "Imagination proprietary driver"
	8,	// author = "Qualcomm Technologies, Inc."    comment = "Qualcomm proprietary driver"
	9,	// author = "Arm Limited"                    comment = "Arm proprietary driver"
	10,	// <enum value="10"      name="VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR"        comment="Google LLC"/>
	11,	// <enum value="11"      name="VK_DRIVER_ID_GGP_PROPRIETARY_KHR"           comment="Google LLC"/>
	12,	// <enum value="12"      name="VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR"      comment="Broadcom Inc."/>
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 1, 0),
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
	makeConformanceVersion(1, 1, 2, 3),
	makeConformanceVersion(1, 1, 2, 2),
	makeConformanceVersion(1, 1, 2, 1),
	makeConformanceVersion(1, 1, 2, 0),
	makeConformanceVersion(1, 1, 1, 3),
	makeConformanceVersion(1, 1, 1, 2),
	makeConformanceVersion(1, 1, 1, 1),
	makeConformanceVersion(1, 1, 1, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)
	{
		if (deviceDriverProperties.driverID == *pDriverId)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<|endoftext|>


<commit_before>#include "gamestates/introstate.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RenderWindow.hpp>

#include <iostream>

namespace qrw
{

IntroState::IntroState(sf::RenderWindow* renderWindow)
	: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)
{
}

IntroState::~IntroState()
{
}

void IntroState::init(GameState* previousState)
{
	// Create render window
	_renderWindow->create(
		sf::VideoMode(640, 240),
		"Quad-Ruled War - Loading...",
		sf::Style::None
	);

	_advanceToNextState = false;

	_splashTexture = new sf::Texture();
	_splashTexture->loadFromFile("./res/img/splash.png");
	_splashSprite = new sf::Sprite();
	_splashSprite->setTexture(*_splashTexture);
}

EGameStateId IntroState::update()
{
	if(_advanceToNextState)
	{
		delete _splashTexture;
		delete _splashSprite;

		return EGameStateId::EGSID_MAIN_MENU_STATE;
	}

	return EGameStateId::EGSID_NO_CHANGE;
}

void IntroState::draw()
{
	_renderWindow->draw(*_splashSprite);
}

void IntroState::handleEvent(sf::Event& event)
{
	std::cout << "Handle event\n";

	if(event.type == sf::Event::KeyPressed)
		_advanceToNextState = true;
}

} // namespace qrw
<commit_msg>Intro state loads resources.<commit_after>#include "gamestates/introstate.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RenderWindow.hpp>

#include <iostream>

#include "config/settings.hpp"
#include "config/tilesetprocessor.hpp"
#include "gui/imagemanager.hpp"
#include "gui/texturemanager.hpp"

namespace qrw
{

IntroState::IntroState(sf::RenderWindow* renderWindow)
	: GameState(renderWindow, EGameStateId::EGSID_INTRO_STATE)
{
}

IntroState::~IntroState()
{
}

void IntroState::init(GameState* previousState)
{
	// Create render window
	_renderWindow->create(
		sf::VideoMode(640, 240),
		"Quad-Ruled War - Loading...",
		sf::Style::None
	);

	_advanceToNextState = false;

	_splashTexture = new sf::Texture();
	_splashTexture->loadFromFile("./res/img/splash.png");
	_splashSprite = new sf::Sprite();
	_splashSprite->setTexture(*_splashTexture);
}

EGameStateId IntroState::update()
{
	if(_advanceToNextState)
	{
		delete _splashTexture;
		delete _splashSprite;

		return EGameStateId::EGSID_MAIN_MENU_STATE;
	}

	return EGameStateId::EGSID_NO_CHANGE;
}

void IntroState::draw()
{
	_renderWindow->draw(*_splashSprite);
	_renderWindow->display();

	// Start initialization of qrw...
	// Load Settings
	qrw::Settings* settings = qrw::Settings::getInstance();
	settings->loadFromFile();

	// Preload image resources
	qrw::ImageManager* imgmgr = qrw::ImageManager::getInstance();
	imgmgr->loadImage("p1swordman", "./res/img/units/p1swordman.png");
	imgmgr->loadImage("p1archer", "./res/img/units/p1archer.png");
	imgmgr->loadImage("p1spearman", "./res/img/units/p1spearman.png");
	imgmgr->loadImage("p2swordman", "./res/img/units/p2swordman.png");
	imgmgr->loadImage("p2archer", "./res/img/units/p2archer.png");
	imgmgr->loadImage("p2spearman", "./res/img/units/p2spearman.png");
	imgmgr->loadImage("plainsquare", "./res/img/plainsquare.png");

	TextureManager::getInstance()->loadTexture("mainmenubackground", "./res/img/mainmenubackground.png");

	// Loading tilesets
	qrw::TilesetProcessor tilesetprocessor;
	tilesetprocessor.loadTileset(settings->getEntityTilesetPath());
	tilesetprocessor.loadTileset(settings->getGuiTilesetPath());
}

void IntroState::handleEvent(sf::Event& event)
{
	std::cout << "Handle event\n";

	if(event.type == sf::Event::KeyPressed)
		_advanceToNextState = true;
}

} // namespace qrw
<|endoftext|>


<commit_before>/* dtkComposerNodeFile.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Thu Jul  8 13:28:18 2010 (+0200)
 * Version: $Id$
 * Last-Updated: Tue Aug 30 10:52:37 2011 (+0200)
 *           By: Thibaud Kloczko
 *     Update #: 94
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerNodeFile.h"
#include "dtkComposerNodeProperty.h"

#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>

#include <dtkGui/dtkTextEditor.h>

#include <QtGui/QFileDialog>

class dtkComposerNodeFilePrivate
{
public:
    dtkComposerNodeProperty *property_output_file_name;
    dtkComposerNodeProperty *property_output_file_text;

public:
    QString file;
};

dtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)
{
    d->property_output_file_name = new dtkComposerNodeProperty("name", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
    d->property_output_file_text = new dtkComposerNodeProperty("text", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);

    this->setTitle("File");
    this->setKind(dtkComposerNode::Atomic);
    this->setType("dtkComposerFile");

    this->addOutputProperty(d->property_output_file_name);
    this->addOutputProperty(d->property_output_file_text);

    this->addAction("Choose file", this, SLOT(getFileName()));
    this->addAction("Edit file", this, SLOT(editFile()));

    d->file = QString();
}

dtkComposerNodeFile::~dtkComposerNodeFile(void)
{
    delete d;

    d = NULL;
}

QVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)
{
    if(property == d->property_output_file_name) {
        emit elapsed("00:00::000.001");
        emit progressed(QString("File name: %1").arg(d->file));
        emit progressed(100);
        return QVariant(d->file);
    }

    return QVariant();
}

void dtkComposerNodeFile::editFile(void)
{
    dtkTextEditor *editor = new dtkTextEditor;
    editor->open(d->file);
    editor->show();

    connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));
}

void dtkComposerNodeFile::getFileName(void)
{
    QFileDialog dialog(0, tr("Choose file"));
    dialog.setFileMode(QFileDialog::ExistingFile);
    if (dialog.exec())
        d->file = dialog.selectedFiles().first();

    //d->file = QFileDialog::getOpenFileName(0, tr("Choose file"));
}

void dtkComposerNodeFile::setFileName(const QString& file)
{
    d->file = file;
}

void dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
    Q_UNUSED(edge);
    Q_UNUSED(property);
}

void dtkComposerNodeFile::run(void)
{
    if (d->file.isEmpty())
        dtkDebug() << "File has not been initialized.";

    return;
}

void dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
    Q_UNUSED(edge);
    Q_UNUSED(property);
}
<commit_msg>Setting default stylesheet for node file when opening filedialog box.<commit_after>/* dtkComposerNodeFile.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Thu Jul  8 13:28:18 2010 (+0200)
 * Version: $Id$
 * Last-Updated: Wed Sep 28 17:26:00 2011 (+0200)
 *           By: Thibaud Kloczko
 *     Update #: 97
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerNodeFile.h"
#include "dtkComposerNodeProperty.h"

#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>

#include <dtkGui/dtkTextEditor.h>

#include <QtGui/QFileDialog>

class dtkComposerNodeFilePrivate
{
public:
    dtkComposerNodeProperty *property_output_file_name;
    dtkComposerNodeProperty *property_output_file_text;

public:
    QString file;
};

dtkComposerNodeFile::dtkComposerNodeFile(dtkComposerNode *parent) : dtkComposerNode(parent), d(new dtkComposerNodeFilePrivate)
{
    d->property_output_file_name = new dtkComposerNodeProperty("name", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);
    d->property_output_file_text = new dtkComposerNodeProperty("text", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, this);

    this->setTitle("File");
    this->setKind(dtkComposerNode::Atomic);
    this->setType("dtkComposerFile");

    this->addOutputProperty(d->property_output_file_name);
    this->addOutputProperty(d->property_output_file_text);

    this->addAction("Choose file", this, SLOT(getFileName()));
    this->addAction("Edit file", this, SLOT(editFile()));

    d->file = QString();
}

dtkComposerNodeFile::~dtkComposerNodeFile(void)
{
    delete d;

    d = NULL;
}

QVariant dtkComposerNodeFile::value(dtkComposerNodeProperty *property)
{
    if(property == d->property_output_file_name) {
        emit elapsed("00:00::000.001");
        emit progressed(QString("File name: %1").arg(d->file));
        emit progressed(100);
        return QVariant(d->file);
    }

    return QVariant();
}

void dtkComposerNodeFile::editFile(void)
{
    dtkTextEditor *editor = new dtkTextEditor;
    editor->open(d->file);
    editor->show();

    connect(editor, SIGNAL(closed()), editor, SLOT(deleteLater()));
}

void dtkComposerNodeFile::getFileName(void)
{
    QFileDialog dialog(0, tr("Choose file"));
    dialog.setStyleSheet("background-color: none ; color: none;");
    dialog.setFileMode(QFileDialog::ExistingFile);
    if (dialog.exec())
        d->file = dialog.selectedFiles().first();

    // d->file = QFileDialog::getOpenFileName(0, tr("Choose file"));
}

void dtkComposerNodeFile::setFileName(const QString& file)
{
    d->file = file;
}

void dtkComposerNodeFile::pull(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
    Q_UNUSED(edge);
    Q_UNUSED(property);
}

void dtkComposerNodeFile::run(void)
{
    if (d->file.isEmpty())
        dtkDebug() << "File has not been initialized.";

    return;
}

void dtkComposerNodeFile::push(dtkComposerEdge *edge, dtkComposerNodeProperty *property)
{
    Q_UNUSED(edge);
    Q_UNUSED(property);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkRectShaderImageFilter.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkFlattenableBuffers.h"
#include "SkShader.h"

SkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {
    SkASSERT(s);
    return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));
}

SkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)
  : INHERITED(NULL)
  , fShader(s)
  , fRect(rect) {
    SkASSERT(s);
    s->ref();
}

SkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)
  : INHERITED(buffer) {
    fShader = buffer.readFlattenableT<SkShader>();
    buffer.readRect(&fRect);
}

void SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);

    buffer.writeFlattenable(fShader);
    buffer.writeRect(fRect);
}

SkRectShaderImageFilter::~SkRectShaderImageFilter() {
    SkSafeUnref(fShader);
}

bool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,
                                        const SkBitmap& source,
                                        const SkMatrix& matrix,
                                        SkBitmap* result,
                                        SkIPoint* loc) {
    SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(fRect.width()),
                                                      SkScalarCeilToInt(fRect.height())));
    SkCanvas canvas(device.get());
    SkPaint paint;
    paint.setShader(fShader);
    canvas.drawRect(fRect, paint);
    *result = device.get()->accessBitmap(false);
    return true;
}
<commit_msg>Adding a bit of rebustness to SkRectShaderImageFilter<commit_after>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkRectShaderImageFilter.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDevice.h"
#include "SkFlattenableBuffers.h"
#include "SkShader.h"

SkRectShaderImageFilter* SkRectShaderImageFilter::Create(SkShader* s, const SkRect& rect) {
    SkASSERT(s);
    return SkNEW_ARGS(SkRectShaderImageFilter, (s, rect));
}

SkRectShaderImageFilter::SkRectShaderImageFilter(SkShader* s, const SkRect& rect)
  : INHERITED(NULL)
  , fShader(s)
  , fRect(rect) {
    SkASSERT(s);
    s->ref();
}

SkRectShaderImageFilter::SkRectShaderImageFilter(SkFlattenableReadBuffer& buffer)
  : INHERITED(buffer) {
    fShader = buffer.readFlattenableT<SkShader>();
    buffer.readRect(&fRect);
}

void SkRectShaderImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);

    buffer.writeFlattenable(fShader);
    buffer.writeRect(fRect);
}

SkRectShaderImageFilter::~SkRectShaderImageFilter() {
    SkSafeUnref(fShader);
}

bool SkRectShaderImageFilter::onFilterImage(Proxy* proxy,
                                            const SkBitmap& source,
                                            const SkMatrix&,
                                            SkBitmap* result,
                                            SkIPoint*) {
    SkRect rect(fRect);
    if (rect.isEmpty()) {
        rect = SkRect::MakeWH(source.width(), source.height());
    }

    if (rect.isEmpty()) {
        return false;
    }

    SkAutoTUnref<SkDevice> device(proxy->createDevice(SkScalarCeilToInt(rect.width()),
                                                      SkScalarCeilToInt(rect.height())));
    SkCanvas canvas(device.get());
    SkPaint paint;
    paint.setShader(fShader);
    canvas.drawRect(rect, paint);
    *result = device.get()->accessBitmap(false);
    return true;
}
<|endoftext|>