<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 "chrome/browser/extensions/external_extension_provider_impl.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_extension_provider_interface.h"
#include "chrome/browser/extensions/external_policy_extension_loader.h"
#include "chrome/browser/extensions/external_pref_extension_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/policy/app_pack_updater.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#endif

#if !defined(OS_CHROMEOS)
#include "chrome/browser/extensions/default_apps.h"
#endif

#if defined(OS_WIN)
#include "chrome/browser/extensions/external_registry_extension_loader_win.h"
#endif

using content::BrowserThread;

// Constants for keeping track of extension preferences in a dictionary.
const char ExternalExtensionProviderImpl::kExternalCrx[] = "external_crx";
const char ExternalExtensionProviderImpl::kExternalVersion[] =
    "external_version";
const char ExternalExtensionProviderImpl::kExternalUpdateUrl[] =
    "external_update_url";
const char ExternalExtensionProviderImpl::kSupportedLocales[] =
    "supported_locales";

ExternalExtensionProviderImpl::ExternalExtensionProviderImpl(
    VisitorInterface* service,
    ExternalExtensionLoader* loader,
    Extension::Location crx_location,
    Extension::Location download_location,
    int creation_flags)
  : crx_location_(crx_location),
    download_location_(download_location),
    service_(service),
    prefs_(NULL),
    ready_(false),
    loader_(loader),
    creation_flags_(creation_flags),
    auto_acknowledge_(false) {
  loader_->Init(this);
}

ExternalExtensionProviderImpl::~ExternalExtensionProviderImpl() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  loader_->OwnerShutdown();
}

void ExternalExtensionProviderImpl::VisitRegisteredExtension() {
  // The loader will call back to SetPrefs.
  loader_->StartLoading();
}

void ExternalExtensionProviderImpl::SetPrefs(DictionaryValue* prefs) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Check if the service is still alive. It is possible that it went
  // away while |loader_| was working on the FILE thread.
  if (!service_) return;

  prefs_.reset(prefs);
  ready_ = true; // Queries for extensions are allowed from this point.

  // Set of unsupported extensions that need to be deleted from prefs_.
  std::set<std::string> unsupported_extensions;

  // Notify ExtensionService about all the extensions this provider has.
  for (DictionaryValue::key_iterator i = prefs_->begin_keys();
       i != prefs_->end_keys(); ++i) {
    const std::string& extension_id = *i;
    DictionaryValue* extension;

    if (!Extension::IdIsValid(extension_id)) {
      LOG(WARNING) << "Malformed extension dictionary: key "
                   << extension_id.c_str() << " is not a valid id.";
      continue;
    }

    if (!prefs_->GetDictionaryWithoutPathExpansion(extension_id, &extension)) {
      LOG(WARNING) << "Malformed extension dictionary: key "
                   << extension_id.c_str()
                   << " has a value that is not a dictionary.";
      continue;
    }

    FilePath::StringType external_crx;
    std::string external_version;
    std::string external_update_url;

    bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
    bool has_external_version = extension->GetString(kExternalVersion,
                                                     &external_version);
    bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
                                                        &external_update_url);
    if (has_external_crx != has_external_version) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str() << ".  " << kExternalCrx
                   << " and " << kExternalVersion << " must be used together.";
      continue;
    }

    if (has_external_crx == has_external_update_url) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str() << ".  Exactly one of the "
                   << "followng keys should be used: " << kExternalCrx
                   << ", " << kExternalUpdateUrl << ".";
      continue;
    }

    // Check that extension supports current browser locale.
    ListValue* supported_locales = NULL;
    if (extension->GetList(kSupportedLocales, &supported_locales)) {
      std::vector<std::string> browser_locales;
      l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
                                  &browser_locales);

      size_t num_locales = supported_locales->GetSize();
      bool locale_supported = false;
      for (size_t j = 0; j < num_locales; j++) {
        std::string current_locale;
        if (supported_locales->GetString(j, &current_locale) &&
            l10n_util::IsValidLocaleSyntax(current_locale)) {
          current_locale = l10n_util::NormalizeLocale(current_locale);
          if (std::find(browser_locales.begin(), browser_locales.end(),
                        current_locale) != browser_locales.end()) {
            locale_supported = true;
            break;
          }
        } else {
          LOG(WARNING) << "Unrecognized locale '" << current_locale
                       << "' found as supported locale for extension: "
                       << extension_id;
        }
      }

      if (!locale_supported) {
        unsupported_extensions.insert(extension_id);
        LOG(INFO) << "Skip installing (or uninstall) external extension: "
                  << extension_id << " because the extension doesn't support "
                  << "the browser locale.";
        continue;
      }
    }

    if (has_external_crx) {
      if (crx_location_ == Extension::INVALID) {
        LOG(WARNING) << "This provider does not support installing external "
                     << "extensions from crx files.";
        continue;
      }
      if (external_crx.find(FilePath::kParentDirectory) !=
          base::StringPiece::npos) {
        LOG(WARNING) << "Path traversal not allowed in path: "
                     << external_crx.c_str();
        continue;
      }

      // If the path is relative, and the provider has a base path,
      // build the absolute path to the crx file.
      FilePath path(external_crx);
      if (!path.IsAbsolute()) {
        FilePath base_path = loader_->GetBaseCrxFilePath();
        if (base_path.empty()) {
          LOG(WARNING) << "File path " << external_crx.c_str()
                       << " is relative.  An absolute path is required.";
          continue;
        }
        path = base_path.Append(external_crx);
      }

      scoped_ptr<Version> version;
      version.reset(Version::GetVersionFromString(external_version));
      if (!version.get()) {
        LOG(WARNING) << "Malformed extension dictionary for extension: "
                     << extension_id.c_str() << ".  Invalid version string \""
                     << external_version << "\".";
        continue;
      }
      service_->OnExternalExtensionFileFound(extension_id, version.get(), path,
                                             crx_location_, creation_flags_,
                                             auto_acknowledge_);
    } else { // if (has_external_update_url)
      CHECK(has_external_update_url);  // Checking of keys above ensures this.
      if (download_location_ == Extension::INVALID) {
        LOG(WARNING) << "This provider does not support installing external "
                     << "extensions from update URLs.";
        continue;
      }
      GURL update_url(external_update_url);
      if (!update_url.is_valid()) {
        LOG(WARNING) << "Malformed extension dictionary for extension: "
                     << extension_id.c_str() << ".  Key " << kExternalUpdateUrl
                     << " has value \"" << external_update_url
                     << "\", which is not a valid URL.";
        continue;
      }
      service_->OnExternalExtensionUpdateUrlFound(
          extension_id, update_url, download_location_);
    }
  }

  for (std::set<std::string>::iterator it = unsupported_extensions.begin();
       it != unsupported_extensions.end(); ++it) {
    // Remove extension for the list of know external extensions. The extension
    // will be uninstalled later because provider doesn't provide it anymore.
    prefs_->Remove(*it, NULL);
  }

  service_->OnExternalProviderReady(this);
}

void ExternalExtensionProviderImpl::ServiceShutdown() {
  service_ = NULL;
}

bool ExternalExtensionProviderImpl::IsReady() const {
  return ready_;
}

int ExternalExtensionProviderImpl::GetCreationFlags() const {
  return creation_flags_;
}

bool ExternalExtensionProviderImpl::HasExtension(
    const std::string& id) const {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CHECK(prefs_.get());
  CHECK(ready_);
  return prefs_->HasKey(id);
}

bool ExternalExtensionProviderImpl::GetExtensionDetails(
    const std::string& id, Extension::Location* location,
    scoped_ptr<Version>* version) const {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CHECK(prefs_.get());
  CHECK(ready_);
  DictionaryValue* extension = NULL;
  if (!prefs_->GetDictionary(id, &extension))
    return false;

  Extension::Location loc = Extension::INVALID;
  if (extension->HasKey(kExternalUpdateUrl)) {
    loc = download_location_;

  } else if (extension->HasKey(kExternalCrx)) {
    loc = crx_location_;

    std::string external_version;
    if (!extension->GetString(kExternalVersion, &external_version))
      return false;

    if (version)
      version->reset(Version::GetVersionFromString(external_version));

  } else {
    NOTREACHED();  // Chrome should not allow prefs to get into this state.
    return false;
  }

  if (location)
    *location = loc;

  return true;
}

// static
void ExternalExtensionProviderImpl::CreateExternalProviders(
    VisitorInterface* service,
    Profile* profile,
    ProviderCollection* provider_list) {

  // On Mac OS, items in /Library/... should be written by the superuser.
  // Check that all components of the path are writable by root only.
  ExternalPrefExtensionLoader::Options check_admin_permissions_on_mac;
#if defined(OS_MACOSX)
  check_admin_permissions_on_mac =
    ExternalPrefExtensionLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
#else
  check_admin_permissions_on_mac = ExternalPrefExtensionLoader::NONE;
#endif

  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_EXTERNAL_EXTENSIONS,
                  check_admin_permissions_on_mac),
              Extension::EXTERNAL_PREF,
              Extension::EXTERNAL_PREF_DOWNLOAD,
#if defined(OS_CHROMEOS)
              Extension::FROM_WEBSTORE)));
#else
              Extension::NO_FLAGS)));
#endif

#if defined(OS_CHROMEOS) || defined (OS_MACOSX)
  // Define a per-user source of external extensions.
  // On Chrome OS, this serves as a source for OEM customization.
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_USER_EXTERNAL_EXTENSIONS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::EXTERNAL_PREF_DOWNLOAD,
              Extension::NO_FLAGS)));
#endif
#if defined(OS_WIN)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalRegistryExtensionLoader,
              Extension::EXTERNAL_REGISTRY,
              Extension::INVALID,
              Extension::NO_FLAGS)));
#endif

#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::EXTERNAL_PREF_DOWNLOAD,
              Extension::NO_FLAGS)));
#endif

  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPolicyExtensionLoader(profile),
              Extension::INVALID,
              Extension::EXTERNAL_POLICY_DOWNLOAD,
              Extension::NO_FLAGS)));

#if !defined(OS_CHROMEOS)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new default_apps::Provider(
              profile,
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_DEFAULT_APPS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::INVALID,
              Extension::FROM_BOOKMARK)));
#endif

#if defined(OS_CHROMEOS)
  chromeos::UserManager* user_manager = chromeos::UserManager::Get();
  policy::BrowserPolicyConnector* connector =
      g_browser_process->browser_policy_connector();
  if (user_manager && user_manager->IsLoggedInAsDemoUser() &&
      connector->GetDeviceMode() == policy::DEVICE_MODE_KIOSK &&
      connector->GetAppPackUpdater()) {
    provider_list->push_back(
        linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              connector->GetAppPackUpdater()->CreateExternalExtensionLoader(),
              Extension::EXTERNAL_PREF,
              Extension::INVALID,
              Extension::NO_FLAGS)));
  }
#endif
}
<commit_msg>Don't load external extensions for kiosk sessions.<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 "chrome/browser/extensions/external_extension_provider_impl.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_extension_provider_interface.h"
#include "chrome/browser/extensions/external_policy_extension_loader.h"
#include "chrome/browser/extensions/external_pref_extension_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/policy/app_pack_updater.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#endif

#if !defined(OS_CHROMEOS)
#include "chrome/browser/extensions/default_apps.h"
#endif

#if defined(OS_WIN)
#include "chrome/browser/extensions/external_registry_extension_loader_win.h"
#endif

using content::BrowserThread;

// Constants for keeping track of extension preferences in a dictionary.
const char ExternalExtensionProviderImpl::kExternalCrx[] = "external_crx";
const char ExternalExtensionProviderImpl::kExternalVersion[] =
    "external_version";
const char ExternalExtensionProviderImpl::kExternalUpdateUrl[] =
    "external_update_url";
const char ExternalExtensionProviderImpl::kSupportedLocales[] =
    "supported_locales";

ExternalExtensionProviderImpl::ExternalExtensionProviderImpl(
    VisitorInterface* service,
    ExternalExtensionLoader* loader,
    Extension::Location crx_location,
    Extension::Location download_location,
    int creation_flags)
  : crx_location_(crx_location),
    download_location_(download_location),
    service_(service),
    prefs_(NULL),
    ready_(false),
    loader_(loader),
    creation_flags_(creation_flags),
    auto_acknowledge_(false) {
  loader_->Init(this);
}

ExternalExtensionProviderImpl::~ExternalExtensionProviderImpl() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  loader_->OwnerShutdown();
}

void ExternalExtensionProviderImpl::VisitRegisteredExtension() {
  // The loader will call back to SetPrefs.
  loader_->StartLoading();
}

void ExternalExtensionProviderImpl::SetPrefs(DictionaryValue* prefs) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Check if the service is still alive. It is possible that it went
  // away while |loader_| was working on the FILE thread.
  if (!service_) return;

  prefs_.reset(prefs);
  ready_ = true; // Queries for extensions are allowed from this point.

  // Set of unsupported extensions that need to be deleted from prefs_.
  std::set<std::string> unsupported_extensions;

  // Notify ExtensionService about all the extensions this provider has.
  for (DictionaryValue::key_iterator i = prefs_->begin_keys();
       i != prefs_->end_keys(); ++i) {
    const std::string& extension_id = *i;
    DictionaryValue* extension;

    if (!Extension::IdIsValid(extension_id)) {
      LOG(WARNING) << "Malformed extension dictionary: key "
                   << extension_id.c_str() << " is not a valid id.";
      continue;
    }

    if (!prefs_->GetDictionaryWithoutPathExpansion(extension_id, &extension)) {
      LOG(WARNING) << "Malformed extension dictionary: key "
                   << extension_id.c_str()
                   << " has a value that is not a dictionary.";
      continue;
    }

    FilePath::StringType external_crx;
    std::string external_version;
    std::string external_update_url;

    bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
    bool has_external_version = extension->GetString(kExternalVersion,
                                                     &external_version);
    bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
                                                        &external_update_url);
    if (has_external_crx != has_external_version) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str() << ".  " << kExternalCrx
                   << " and " << kExternalVersion << " must be used together.";
      continue;
    }

    if (has_external_crx == has_external_update_url) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str() << ".  Exactly one of the "
                   << "followng keys should be used: " << kExternalCrx
                   << ", " << kExternalUpdateUrl << ".";
      continue;
    }

    // Check that extension supports current browser locale.
    ListValue* supported_locales = NULL;
    if (extension->GetList(kSupportedLocales, &supported_locales)) {
      std::vector<std::string> browser_locales;
      l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
                                  &browser_locales);

      size_t num_locales = supported_locales->GetSize();
      bool locale_supported = false;
      for (size_t j = 0; j < num_locales; j++) {
        std::string current_locale;
        if (supported_locales->GetString(j, &current_locale) &&
            l10n_util::IsValidLocaleSyntax(current_locale)) {
          current_locale = l10n_util::NormalizeLocale(current_locale);
          if (std::find(browser_locales.begin(), browser_locales.end(),
                        current_locale) != browser_locales.end()) {
            locale_supported = true;
            break;
          }
        } else {
          LOG(WARNING) << "Unrecognized locale '" << current_locale
                       << "' found as supported locale for extension: "
                       << extension_id;
        }
      }

      if (!locale_supported) {
        unsupported_extensions.insert(extension_id);
        LOG(INFO) << "Skip installing (or uninstall) external extension: "
                  << extension_id << " because the extension doesn't support "
                  << "the browser locale.";
        continue;
      }
    }

    if (has_external_crx) {
      if (crx_location_ == Extension::INVALID) {
        LOG(WARNING) << "This provider does not support installing external "
                     << "extensions from crx files.";
        continue;
      }
      if (external_crx.find(FilePath::kParentDirectory) !=
          base::StringPiece::npos) {
        LOG(WARNING) << "Path traversal not allowed in path: "
                     << external_crx.c_str();
        continue;
      }

      // If the path is relative, and the provider has a base path,
      // build the absolute path to the crx file.
      FilePath path(external_crx);
      if (!path.IsAbsolute()) {
        FilePath base_path = loader_->GetBaseCrxFilePath();
        if (base_path.empty()) {
          LOG(WARNING) << "File path " << external_crx.c_str()
                       << " is relative.  An absolute path is required.";
          continue;
        }
        path = base_path.Append(external_crx);
      }

      scoped_ptr<Version> version;
      version.reset(Version::GetVersionFromString(external_version));
      if (!version.get()) {
        LOG(WARNING) << "Malformed extension dictionary for extension: "
                     << extension_id.c_str() << ".  Invalid version string \""
                     << external_version << "\".";
        continue;
      }
      service_->OnExternalExtensionFileFound(extension_id, version.get(), path,
                                             crx_location_, creation_flags_,
                                             auto_acknowledge_);
    } else { // if (has_external_update_url)
      CHECK(has_external_update_url);  // Checking of keys above ensures this.
      if (download_location_ == Extension::INVALID) {
        LOG(WARNING) << "This provider does not support installing external "
                     << "extensions from update URLs.";
        continue;
      }
      GURL update_url(external_update_url);
      if (!update_url.is_valid()) {
        LOG(WARNING) << "Malformed extension dictionary for extension: "
                     << extension_id.c_str() << ".  Key " << kExternalUpdateUrl
                     << " has value \"" << external_update_url
                     << "\", which is not a valid URL.";
        continue;
      }
      service_->OnExternalExtensionUpdateUrlFound(
          extension_id, update_url, download_location_);
    }
  }

  for (std::set<std::string>::iterator it = unsupported_extensions.begin();
       it != unsupported_extensions.end(); ++it) {
    // Remove extension for the list of know external extensions. The extension
    // will be uninstalled later because provider doesn't provide it anymore.
    prefs_->Remove(*it, NULL);
  }

  service_->OnExternalProviderReady(this);
}

void ExternalExtensionProviderImpl::ServiceShutdown() {
  service_ = NULL;
}

bool ExternalExtensionProviderImpl::IsReady() const {
  return ready_;
}

int ExternalExtensionProviderImpl::GetCreationFlags() const {
  return creation_flags_;
}

bool ExternalExtensionProviderImpl::HasExtension(
    const std::string& id) const {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CHECK(prefs_.get());
  CHECK(ready_);
  return prefs_->HasKey(id);
}

bool ExternalExtensionProviderImpl::GetExtensionDetails(
    const std::string& id, Extension::Location* location,
    scoped_ptr<Version>* version) const {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CHECK(prefs_.get());
  CHECK(ready_);
  DictionaryValue* extension = NULL;
  if (!prefs_->GetDictionary(id, &extension))
    return false;

  Extension::Location loc = Extension::INVALID;
  if (extension->HasKey(kExternalUpdateUrl)) {
    loc = download_location_;

  } else if (extension->HasKey(kExternalCrx)) {
    loc = crx_location_;

    std::string external_version;
    if (!extension->GetString(kExternalVersion, &external_version))
      return false;

    if (version)
      version->reset(Version::GetVersionFromString(external_version));

  } else {
    NOTREACHED();  // Chrome should not allow prefs to get into this state.
    return false;
  }

  if (location)
    *location = loc;

  return true;
}

// static
void ExternalExtensionProviderImpl::CreateExternalProviders(
    VisitorInterface* service,
    Profile* profile,
    ProviderCollection* provider_list) {

  // On Mac OS, items in /Library/... should be written by the superuser.
  // Check that all components of the path are writable by root only.
  ExternalPrefExtensionLoader::Options check_admin_permissions_on_mac;
#if defined(OS_MACOSX)
  check_admin_permissions_on_mac =
    ExternalPrefExtensionLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
#else
  check_admin_permissions_on_mac = ExternalPrefExtensionLoader::NONE;
#endif

  bool is_chromeos_demo_session = false;
  int bundled_extension_creation_flags = Extension::NO_FLAGS;
#if defined(OS_CHROMEOS)
  chromeos::UserManager* user_manager = chromeos::UserManager::Get();
  is_chromeos_demo_session =
      user_manager && user_manager->IsLoggedInAsDemoUser() &&
      g_browser_process->browser_policy_connector()->GetDeviceMode() ==
          policy::DEVICE_MODE_KIOSK;
  bundled_extension_creation_flags = Extension::FROM_WEBSTORE;
#endif

  if (!is_chromeos_demo_session) {
    provider_list->push_back(
        linked_ptr<ExternalExtensionProviderInterface>(
            new ExternalExtensionProviderImpl(
                service,
                new ExternalPrefExtensionLoader(
                    chrome::DIR_EXTERNAL_EXTENSIONS,
                    check_admin_permissions_on_mac),
                Extension::EXTERNAL_PREF,
                Extension::EXTERNAL_PREF_DOWNLOAD,
                bundled_extension_creation_flags)));
  }

#if defined(OS_CHROMEOS) || defined (OS_MACOSX)
  // Define a per-user source of external extensions.
  // On Chrome OS, this serves as a source for OEM customization.
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_USER_EXTERNAL_EXTENSIONS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::EXTERNAL_PREF_DOWNLOAD,
              Extension::NO_FLAGS)));
#endif
#if defined(OS_WIN)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalRegistryExtensionLoader,
              Extension::EXTERNAL_REGISTRY,
              Extension::INVALID,
              Extension::NO_FLAGS)));
#endif

#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::EXTERNAL_PREF_DOWNLOAD,
              Extension::NO_FLAGS)));
#endif

  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              new ExternalPolicyExtensionLoader(profile),
              Extension::INVALID,
              Extension::EXTERNAL_POLICY_DOWNLOAD,
              Extension::NO_FLAGS)));

#if !defined(OS_CHROMEOS)
  provider_list->push_back(
      linked_ptr<ExternalExtensionProviderInterface>(
          new default_apps::Provider(
              profile,
              service,
              new ExternalPrefExtensionLoader(
                  chrome::DIR_DEFAULT_APPS,
                  ExternalPrefExtensionLoader::NONE),
              Extension::EXTERNAL_PREF,
              Extension::INVALID,
              Extension::FROM_BOOKMARK)));
#endif

#if defined(OS_CHROMEOS)
  policy::BrowserPolicyConnector* connector =
      g_browser_process->browser_policy_connector();
  if (is_chromeos_demo_session && connector->GetAppPackUpdater()) {
    provider_list->push_back(
        linked_ptr<ExternalExtensionProviderInterface>(
          new ExternalExtensionProviderImpl(
              service,
              connector->GetAppPackUpdater()->CreateExternalExtensionLoader(),
              Extension::EXTERNAL_PREF,
              Extension::INVALID,
              Extension::NO_FLAGS)));
  }
#endif
}
<|endoftext|>


<commit_before>#include "IwGx.h"
#include "IwTween.h"
#include "audio.h"
#include "scene.h"
#include "grid.h"
#include "game.h"
#include "blankObject.h"
#include "resources.h"
#include "main.h"

using namespace IwTween;

Grid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)
{
	int map[11][17] = {
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
	};

	Width = num_columns;
	Height = num_rows;
	GameObjects = new GameObject* [num_columns * (num_rows + 1)];

	int bm_width = (int)g_pResources->GetRock()->GetWidth();
	GameObjectSize = (IwGxGetScreenWidth() * bm_width) / GRAPHIC_DESIGN_WIDTH;

	float gem_scale = (float)GameObjectSize / bm_width;

	GridOriginX = offset_x;
	GridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;

	for (int y = 0; y < num_rows; y++)
	{
		for (int x = 0; x < num_columns; x++)
		{
			switch (map[x][y])
			{
			case 0:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 0));
				GameObjects[x + Width*y] = new BlankObject();
				GameObjects[x + Width*y]->setId(0);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 1:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 1));
				GameObjects[x + Width*y] = new Rock();
				GameObjects[x + Width*y]->setId(1);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 2:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 2));
				GameObjects[x + Width*y] = new Player();
				GameObjects[x + Width*y]->setId(2);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;
			}
		}
	}
}

Grid::~Grid()
{
	if (GameObjects != 0)
		delete[] GameObjects;
}

void Grid::movePlayerLeft()
{
	int index = getIndex();

	int distance = getDistance(LEFT, index);

	float new_X = GameObjects[index]->m_X - (distance * GameObjectSize);

	Game* game = (Game*)g_pSceneManager->Find("game");

	game->GetTweener().Tween(0.5f,
		FLOAT, &GameObjects[index]->m_X, new_X,
		EASING, Ease::sineInOut,
		END);

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	GameObjects[index]->updatePosition(new_X, GameObjects[index]->m_Y);
	GameObjects[index]->setGridCoords(x - distance, y);
	GameObjects[index]->setId(0);
	GameObjects[index - distance]->setId(2);
}

void Grid::movePlayerRight()
{
	int index = getIndex();

	int distance = getDistance(RIGHT, index);

	float new_X = GameObjects[index]->m_X + (distance * GameObjectSize);

	Game* game = (Game*)g_pSceneManager->Find("game");

	game->GetTweener().Tween(0.5f,
		FLOAT, &GameObjects[index]->m_X, new_X,
		EASING, Ease::sineInOut,
		END);

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	GameObjects[index]->updatePosition(new_X, GameObjects[index]->m_Y);
	GameObjects[index]->setGridCoords(x + distance, y);
	GameObjects[index]->setId(0);
	GameObjects[index + distance]->setId(2);
}

void Grid::movePlayerUp()
{
}

void Grid::movePlayerDown()
{
}

int Grid::getIndex()
{
	int index = 0;

	for (int y = 0; y < Height; y++)
	{
		for (int x = 0; x < Width; x++)
		{
			if (GameObjects[x + Width * y]->getId() == 2)
			{
				index = x + Width * y;
			}
		}
	}

	IwTrace(APP, ("index =  %d", index));

	return index;
}

int Grid::getDistance(Grid::Direction dir, int index)
{
	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	IwTrace(APP, ("coords [%d][%d]", x, y));

	int distance = 0;

	switch (dir)
	{
	case LEFT:
		while (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0)
		{
			distance++;
		}
		break;
	case RIGHT:
		while (GameObjects[(x + (distance + 1)) + Width*y]->getId() == 0)
		{
			distance++;
		}
		break;
	case UP:
		while (GameObjects[(x + (Width*y - (distance + 1)))]->getId() == 0)
		{
			distance++;
		}
		break;
	case DOWN:
		while (GameObjects[(x + (Width*y - (distance - 1)))]->getId() == 0)
		{
			distance++;
		}
		break;
	}

	IwTrace(APP, ("distance is %d", distance));

	return distance;
}
<commit_msg>moved tween, still not working<commit_after>#include "IwGx.h"
#include "IwTween.h"
#include "audio.h"
#include "scene.h"
#include "grid.h"
#include "game.h"
#include "blankObject.h"
#include "resources.h"
#include "main.h"

using namespace IwTween;

Grid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)
{
	int map[11][17] = {
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
	};

	Width = num_columns;
	Height = num_rows;
	GameObjects = new GameObject* [num_columns * (num_rows + 1)];

	int bm_width = (int)g_pResources->GetRock()->GetWidth();
	GameObjectSize = (IwGxGetScreenWidth() * bm_width) / GRAPHIC_DESIGN_WIDTH;

	float gem_scale = (float)GameObjectSize / bm_width;

	GridOriginX = offset_x;
	GridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;

	for (int y = 0; y < num_rows; y++)
	{
		for (int x = 0; x < num_columns; x++)
		{
			switch (map[x][y])
			{
			case 0:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 0));
				GameObjects[x + Width*y] = new BlankObject();
				GameObjects[x + Width*y]->setId(0);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 1:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 1));
				GameObjects[x + Width*y] = new Rock();
				GameObjects[x + Width*y]->setId(1);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 2:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 2));
				GameObjects[x + Width*y] = new Player();
				GameObjects[x + Width*y]->setId(2);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;
			}
		}
	}
}

Grid::~Grid()
{
	if (GameObjects != 0)
		delete[] GameObjects;
}

void Grid::movePlayerLeft()
{
	int index = getIndex();

	int distance = getDistance(LEFT, index);

	float new_X = GameObjects[index]->m_X - (distance * GameObjectSize);

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	GameObjects[index]->updatePosition(new_X, GameObjects[index]->m_Y);
	GameObjects[index]->setGridCoords(x - distance, y);
	GameObjects[index]->setId(0);
	GameObjects[index - distance]->setId(2);

	Game* game = (Game*)g_pSceneManager->Find("game");

	game->GetTweener().Tween(0.5f,
		FLOAT, &GameObjects[index]->m_X, new_X,
		EASING, Ease::sineInOut,
		END);
}

void Grid::movePlayerRight()
{
	int index = getIndex();

	int distance = getDistance(RIGHT, index);

	float new_X = GameObjects[index]->m_X + (distance * GameObjectSize);

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	GameObjects[index]->updatePosition(new_X, GameObjects[index]->m_Y);
	GameObjects[index]->setGridCoords(x + distance, y);
	GameObjects[index]->setId(0);
	GameObjects[index + distance]->setId(2);

	Game* game = (Game*)g_pSceneManager->Find("game");

	game->GetTweener().Tween(0.5f,
		FLOAT, &GameObjects[index]->m_X, new_X,
		EASING, Ease::sineInOut,
		END);
}

void Grid::movePlayerUp()
{
}

void Grid::movePlayerDown()
{
}

int Grid::getIndex()
{
	int index = 0;

	for (int y = 0; y < Height; y++)
	{
		for (int x = 0; x < Width; x++)
		{
			if (GameObjects[x + Width * y]->getId() == 2)
			{
				index = x + Width * y;
			}
		}
	}

	IwTrace(APP, ("index =  %d", index));

	return index;
}

int Grid::getDistance(Grid::Direction dir, int index)
{
	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	IwTrace(APP, ("coords [%d][%d]", x, y));

	int distance = 0;

	switch (dir)
	{
	case LEFT:
		while (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0)
		{
			distance++;
		}
		break;
	case RIGHT:
		while (GameObjects[(x + (distance + 1)) + Width*y]->getId() == 0)
		{
			distance++;
		}
		break;
	case UP:
		while (GameObjects[(x + (Width*y - (distance + 1)))]->getId() == 0)
		{
			distance++;
		}
		break;
	case DOWN:
		while (GameObjects[(x + (Width*y - (distance - 1)))]->getId() == 0)
		{
			distance++;
		}
		break;
	}

	IwTrace(APP, ("distance is %d", distance));

	return distance;
}
<|endoftext|>


<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.

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.
==============================================================================*/

// gRPC server implementation of
// tensorflow_serving/apis/prediction_service.proto.
//
// It bring up a standard server to serve a single TensorFlow model using
// command line flags, or multiple models via config file.
//
// ModelServer prioritizes easy invocation over flexibility,
// and thus serves a statically configured set of models. New versions of these
// models will be loaded and managed over time using the
// AvailabilityPreservingPolicy at:
//     tensorflow_serving/core/availability_preserving_policy.h.
// by AspiredVersionsManager at:
//     tensorflow_serving/core/aspired_versions_manager.h
//
// ModelServer has inter-request batching support built-in, by using the
// BatchingSession at:
//     tensorflow_serving/batching/batching_session.h
//
// To serve a single model, run with:
//     $path_to_binary/tensorflow_model_server \
//     --model_base_path=[/tmp/my_model | gs://gcs_address]
// IMPORTANT: Be sure the base path excludes the version directory. For
// example for a model at /tmp/my_model/123, where 123 is the version, the base
// path is /tmp/my_model.
//
// To specify model name (default "default"): --model_name=my_name
// To specify port (default 8500): --port=my_port
// To enable batching (default disabled): --enable_batching
// To override the default batching parameters: --batching_parameters_file

#include <iostream>
#include <vector>

#include "tensorflow/c/c_api.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow_serving/model_servers/server.h"
#include "tensorflow_serving/model_servers/version.h"

#if defined(LIBTPU_ON_GCE) || defined(PLATFORM_CLOUD_TPU)
#include "tensorflow/core/protobuf/tpu/topology.proto.h"
#include "tensorflow/core/tpu/tpu_global_init.h"

void InitializeTPU(tensorflow::serving::main::Server::Options& server_options) {
  std::cout << "Initializing TPU system.";
  tensorflow::tpu::TopologyProto tpu_topology;
  TF_QCHECK_OK(tensorflow::InitializeTPUSystemGlobally(
      tensorflow::Env::Default(), &tpu_topology))
      << "Failed to initialize TPU system.";
  std::cout << "Initialized TPU topology: " << tpu_topology.DebugString();
  server_options.num_request_iterations_for_warmup =
      tpu_topology.num_tpu_devices_per_task();
  server_options.enforce_session_run_timeout = false;
  if (server_options.saved_model_tags.empty()) {
    server_options.saved_model_tags = "tpu,serve";
  }
}
#endif

int main(int argc, char** argv) {
  tensorflow::serving::main::Server::Options options;
  bool display_version = false;
  bool xla_cpu_compilation_enabled = false;
  std::vector<tensorflow::Flag> flag_list = {
      tensorflow::Flag("port", &options.grpc_port,
                       "TCP port to listen on for gRPC/HTTP API. Disabled if "
                       "port set to zero."),
      tensorflow::Flag("grpc_socket_path", &options.grpc_socket_path,
                       "If non-empty, listen to a UNIX socket for gRPC API "
                       "on the given path. Can be either relative or absolute "
                       "path."),
      tensorflow::Flag("rest_api_port", &options.http_port,
                       "Port to listen on for HTTP/REST API. If set to zero "
                       "HTTP/REST API will not be exported. This port must be "
                       "different than the one specified in --port."),
      tensorflow::Flag("rest_api_num_threads", &options.http_num_threads,
                       "Number of threads for HTTP/REST API processing. If not "
                       "set, will be auto set based on number of CPUs."),
      tensorflow::Flag("rest_api_timeout_in_ms", &options.http_timeout_in_ms,
                       "Timeout for HTTP/REST API calls."),
      tensorflow::Flag("rest_api_enable_cors_support",
                       &options.enable_cors_support,
                       "Enable CORS headers in response"),
      tensorflow::Flag("enable_batching", &options.enable_batching,
                       "enable batching"),
      tensorflow::Flag(
          "allow_version_labels_for_unavailable_models",
          &options.allow_version_labels_for_unavailable_models,
          "If true, allows assigning unused version labels to models that are "
          "not available yet."),
      tensorflow::Flag("batching_parameters_file",
                       &options.batching_parameters_file,
                       "If non-empty, read an ascii BatchingParameters "
                       "protobuf from the supplied file name and use the "
                       "contained values instead of the defaults."),
      tensorflow::Flag("model_config_file", &options.model_config_file,
                       "If non-empty, read an ascii ModelServerConfig "
                       "protobuf from the supplied file name, and serve the "
                       "models in that file. This config file can be used to "
                       "specify multiple models to serve and other advanced "
                       "parameters including non-default version policy. (If "
                       "used, --model_name, --model_base_path are ignored.)"),
      tensorflow::Flag("model_config_file_poll_wait_seconds",
                       &options.fs_model_config_poll_wait_seconds,
                       "Interval in seconds between each poll of the filesystem"
                       "for model_config_file. If unset or set to zero, "
                       "poll will be done exactly once and not periodically. "
                       "Setting this to negative is reserved for testing "
                       "purposes only."),
      tensorflow::Flag("model_name", &options.model_name,
                       "name of model (ignored "
                       "if --model_config_file flag is set)"),
      tensorflow::Flag("model_base_path", &options.model_base_path,
                       "path to export (ignored if --model_config_file flag "
                       "is set, otherwise required)"),
      tensorflow::Flag("num_load_threads", &options.num_load_threads,
                       "The number of threads in the thread-pool used to load "
                       "servables. If set as 0, we don't use a thread-pool, "
                       "and servable loads are performed serially in the "
                       "manager's main work loop, may casue the Serving "
                       "request to be delayed. Default: 0"),
      tensorflow::Flag("num_unload_threads", &options.num_unload_threads,
                       "The number of threads in the thread-pool used to "
                       "unload servables. If set as 0, we don't use a "
                       "thread-pool, and servable loads are performed serially "
                       "in the manager's main work loop, may casue the Serving "
                       "request to be delayed. Default: 0"),
      tensorflow::Flag("max_num_load_retries", &options.max_num_load_retries,
                       "maximum number of times it retries loading a model "
                       "after the first failure, before giving up. "
                       "If set to 0, a load is attempted only once. "
                       "Default: 5"),
      tensorflow::Flag("load_retry_interval_micros",
                       &options.load_retry_interval_micros,
                       "The interval, in microseconds, between each servable "
                       "load retry. If set negative, it doesn't wait. "
                       "Default: 1 minute"),
      tensorflow::Flag("file_system_poll_wait_seconds",
                       &options.file_system_poll_wait_seconds,
                       "Interval in seconds between each poll of the "
                       "filesystem for new model version. If set to zero "
                       "poll will be exactly done once and not periodically. "
                       "Setting this to negative value will disable polling "
                       "entirely causing ModelServer to indefinitely wait for "
                       "a new model at startup. Negative values are reserved "
                       "for testing purposes only."),
      tensorflow::Flag("flush_filesystem_caches",
                       &options.flush_filesystem_caches,
                       "If true (the default), filesystem caches will be "
                       "flushed after the initial load of all servables, and "
                       "after each subsequent individual servable reload (if "
                       "the number of load threads is 1). This reduces memory "
                       "consumption of the model server, at the potential cost "
                       "of cache misses if model files are accessed after "
                       "servables are loaded."),
      tensorflow::Flag("tensorflow_session_parallelism",
                       &options.tensorflow_session_parallelism,
                       "Number of threads to use for running a "
                       "Tensorflow session. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag(
          "tensorflow_session_config_file",
          &options.tensorflow_session_config_file,
          "If non-empty, read an ascii TensorFlow Session "
          "ConfigProto protobuf from the supplied file name. Note, "
          "parts of the session config (threads, parallelism etc.) "
          "can be overridden if needed, via corresponding command "
          "line flags."),
      tensorflow::Flag("tensorflow_intra_op_parallelism",
                       &options.tensorflow_intra_op_parallelism,
                       "Number of threads to use to parallelize the execution"
                       "of an individual op. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag("tensorflow_inter_op_parallelism",
                       &options.tensorflow_inter_op_parallelism,
                       "Controls the number of operators that can be executed "
                       "simultaneously. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag("use_alts_credentials", &options.use_alts_credentials,
                       "Use Google ALTS credentials"),
      tensorflow::Flag(
          "ssl_config_file", &options.ssl_config_file,
          "If non-empty, read an ascii SSLConfig protobuf from "
          "the supplied file name and set up a secure gRPC channel"),
      tensorflow::Flag("platform_config_file", &options.platform_config_file,
                       "If non-empty, read an ascii PlatformConfigMap protobuf "
                       "from the supplied file name, and use that platform "
                       "config instead of the Tensorflow platform. (If used, "
                       "--enable_batching is ignored.)"),
      tensorflow::Flag(
          "per_process_gpu_memory_fraction",
          &options.per_process_gpu_memory_fraction,
          "Fraction that each process occupies of the GPU memory space "
          "the value is between 0.0 and 1.0 (with 0.0 as the default) "
          "If 1.0, the server will allocate all the memory when the server "
          "starts, If 0.0, Tensorflow will automatically select a value."),
      tensorflow::Flag("saved_model_tags", &options.saved_model_tags,
                       "Comma-separated set of tags corresponding to the meta "
                       "graph def to load from SavedModel."),
      tensorflow::Flag("grpc_channel_arguments",
                       &options.grpc_channel_arguments,
                       "A comma separated list of arguments to be passed to "
                       "the grpc server. (e.g. "
                       "grpc.max_connection_age_ms=2000)"),
      tensorflow::Flag("grpc_max_threads", &options.grpc_max_threads,
                       "Max grpc server threads to handle grpc messages."),
      tensorflow::Flag("enable_model_warmup", &options.enable_model_warmup,
                       "Enables model warmup, which triggers lazy "
                       "initializations (such as TF optimizations) at load "
                       "time, to reduce first request latency."),
      tensorflow::Flag("num_request_iterations_for_warmup",
                       &options.num_request_iterations_for_warmup,
                       "Number of times a request is iterated during warmup "
                       "replay. This value is used only if > 0."),
      tensorflow::Flag("version", &display_version, "Display version"),
      tensorflow::Flag(
          "monitoring_config_file", &options.monitoring_config_file,
          "If non-empty, read an ascii MonitoringConfig protobuf from "
          "the supplied file name"),
      tensorflow::Flag(
          "remove_unused_fields_from_bundle_metagraph",
          &options.remove_unused_fields_from_bundle_metagraph,
          "Removes unused fields from MetaGraphDef proto message to save "
          "memory."),
      tensorflow::Flag("prefer_tflite_model", &options.prefer_tflite_model,
                       "EXPERIMENTAL; CAN BE REMOVED ANYTIME! "
                       "Prefer TensorFlow Lite model from `model.tflite` file "
                       "in SavedModel directory, instead of the TensorFlow "
                       "model from `saved_model.pb` file. "
                       "If no TensorFlow Lite model found, fallback to "
                       "TensorFlow model."),
      tensorflow::Flag(
          "num_tflite_pools", &options.num_tflite_pools,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! Number of TFLite interpreters "
          "in an interpreter pool of TfLiteSession. Typically there is one "
          "TfLiteSession for each TF Lite model that is loaded. If not "
          "set, will be auto set based on number of CPUs."),
      tensorflow::Flag(
          "num_tflite_interpreters_per_pool",
          &options.num_tflite_interpreters_per_pool,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! Number of TFLite interpreters "
          "in an interpreter pool of TfLiteSession. Typically there is one "
          "TfLiteSession for each TF Lite model that is loaded. If not "
          "set, will be 1."),
      tensorflow::Flag(
          "enable_signature_method_name_check",
          &options.enable_signature_method_name_check,
          "Enable method_name check for SignatureDef. Disable this if serving "
          "native TF2 regression/classification models."),
      tensorflow::Flag(
          "xla_cpu_compilation_enabled", &xla_cpu_compilation_enabled,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! "
          "Enable XLA:CPU JIT (default is disabled). With XLA:CPU JIT "
          "disabled, models utilizing this feature will return bad Status "
          "on first compilation request."),
      tensorflow::Flag("enable_profiler", &options.enable_profiler,
                       "Enable profiler service."),
      tensorflow::Flag("thread_pool_factory_config_file",
                       &options.thread_pool_factory_config_file,
                       "If non-empty, read an ascii ThreadPoolConfig protobuf "
                       "from the supplied file name.")};

  const auto& usage = tensorflow::Flags::Usage(argv[0], flag_list);
  if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) {
    std::cout << usage;
    return -1;
  }

  tensorflow::port::InitMain(argv[0], &argc, &argv);
#if defined(LIBTPU_ON_GCE) || defined(PLATFORM_CLOUD_TPU)
  InitializeTPU(options);
#endif

  if (display_version) {
    std::cout << "TensorFlow ModelServer: " << TF_Serving_Version() << "\n"
              << "TensorFlow Library: " << TF_Version() << "\n";
    return 0;
  }

  if (argc != 1) {
    std::cout << "unknown argument: " << argv[1] << "\n" << usage;
  }

  if (!xla_cpu_compilation_enabled) {
    tensorflow::DisableXlaCompilation();
  }

  tensorflow::serving::main::Server server;
  const auto& status = server.BuildAndStart(options);
  if (!status.ok()) {
    std::cout << "Failed to start server. Error: " << status << "\n";
    return -1;
  }
  server.WaitForTermination();
  return 0;
}
<commit_msg>Use pb.h for topology.proto.<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.

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.
==============================================================================*/

// gRPC server implementation of
// tensorflow_serving/apis/prediction_service.proto.
//
// It bring up a standard server to serve a single TensorFlow model using
// command line flags, or multiple models via config file.
//
// ModelServer prioritizes easy invocation over flexibility,
// and thus serves a statically configured set of models. New versions of these
// models will be loaded and managed over time using the
// AvailabilityPreservingPolicy at:
//     tensorflow_serving/core/availability_preserving_policy.h.
// by AspiredVersionsManager at:
//     tensorflow_serving/core/aspired_versions_manager.h
//
// ModelServer has inter-request batching support built-in, by using the
// BatchingSession at:
//     tensorflow_serving/batching/batching_session.h
//
// To serve a single model, run with:
//     $path_to_binary/tensorflow_model_server \
//     --model_base_path=[/tmp/my_model | gs://gcs_address]
// IMPORTANT: Be sure the base path excludes the version directory. For
// example for a model at /tmp/my_model/123, where 123 is the version, the base
// path is /tmp/my_model.
//
// To specify model name (default "default"): --model_name=my_name
// To specify port (default 8500): --port=my_port
// To enable batching (default disabled): --enable_batching
// To override the default batching parameters: --batching_parameters_file

#include <iostream>
#include <vector>

#include "tensorflow/c/c_api.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow_serving/model_servers/server.h"
#include "tensorflow_serving/model_servers/version.h"

#if defined(LIBTPU_ON_GCE) || defined(PLATFORM_CLOUD_TPU)
#include "tensorflow/core/protobuf/tpu/topology.pb.h"
#include "tensorflow/core/tpu/tpu_global_init.h"

void InitializeTPU(tensorflow::serving::main::Server::Options& server_options) {
  std::cout << "Initializing TPU system.";
  tensorflow::tpu::TopologyProto tpu_topology;
  TF_QCHECK_OK(tensorflow::InitializeTPUSystemGlobally(
      tensorflow::Env::Default(), &tpu_topology))
      << "Failed to initialize TPU system.";
  std::cout << "Initialized TPU topology: " << tpu_topology.DebugString();
  server_options.num_request_iterations_for_warmup =
      tpu_topology.num_tpu_devices_per_task();
  server_options.enforce_session_run_timeout = false;
  if (server_options.saved_model_tags.empty()) {
    server_options.saved_model_tags = "tpu,serve";
  }
}
#endif

int main(int argc, char** argv) {
  tensorflow::serving::main::Server::Options options;
  bool display_version = false;
  bool xla_cpu_compilation_enabled = false;
  std::vector<tensorflow::Flag> flag_list = {
      tensorflow::Flag("port", &options.grpc_port,
                       "TCP port to listen on for gRPC/HTTP API. Disabled if "
                       "port set to zero."),
      tensorflow::Flag("grpc_socket_path", &options.grpc_socket_path,
                       "If non-empty, listen to a UNIX socket for gRPC API "
                       "on the given path. Can be either relative or absolute "
                       "path."),
      tensorflow::Flag("rest_api_port", &options.http_port,
                       "Port to listen on for HTTP/REST API. If set to zero "
                       "HTTP/REST API will not be exported. This port must be "
                       "different than the one specified in --port."),
      tensorflow::Flag("rest_api_num_threads", &options.http_num_threads,
                       "Number of threads for HTTP/REST API processing. If not "
                       "set, will be auto set based on number of CPUs."),
      tensorflow::Flag("rest_api_timeout_in_ms", &options.http_timeout_in_ms,
                       "Timeout for HTTP/REST API calls."),
      tensorflow::Flag("rest_api_enable_cors_support",
                       &options.enable_cors_support,
                       "Enable CORS headers in response"),
      tensorflow::Flag("enable_batching", &options.enable_batching,
                       "enable batching"),
      tensorflow::Flag(
          "allow_version_labels_for_unavailable_models",
          &options.allow_version_labels_for_unavailable_models,
          "If true, allows assigning unused version labels to models that are "
          "not available yet."),
      tensorflow::Flag("batching_parameters_file",
                       &options.batching_parameters_file,
                       "If non-empty, read an ascii BatchingParameters "
                       "protobuf from the supplied file name and use the "
                       "contained values instead of the defaults."),
      tensorflow::Flag("model_config_file", &options.model_config_file,
                       "If non-empty, read an ascii ModelServerConfig "
                       "protobuf from the supplied file name, and serve the "
                       "models in that file. This config file can be used to "
                       "specify multiple models to serve and other advanced "
                       "parameters including non-default version policy. (If "
                       "used, --model_name, --model_base_path are ignored.)"),
      tensorflow::Flag("model_config_file_poll_wait_seconds",
                       &options.fs_model_config_poll_wait_seconds,
                       "Interval in seconds between each poll of the filesystem"
                       "for model_config_file. If unset or set to zero, "
                       "poll will be done exactly once and not periodically. "
                       "Setting this to negative is reserved for testing "
                       "purposes only."),
      tensorflow::Flag("model_name", &options.model_name,
                       "name of model (ignored "
                       "if --model_config_file flag is set)"),
      tensorflow::Flag("model_base_path", &options.model_base_path,
                       "path to export (ignored if --model_config_file flag "
                       "is set, otherwise required)"),
      tensorflow::Flag("num_load_threads", &options.num_load_threads,
                       "The number of threads in the thread-pool used to load "
                       "servables. If set as 0, we don't use a thread-pool, "
                       "and servable loads are performed serially in the "
                       "manager's main work loop, may casue the Serving "
                       "request to be delayed. Default: 0"),
      tensorflow::Flag("num_unload_threads", &options.num_unload_threads,
                       "The number of threads in the thread-pool used to "
                       "unload servables. If set as 0, we don't use a "
                       "thread-pool, and servable loads are performed serially "
                       "in the manager's main work loop, may casue the Serving "
                       "request to be delayed. Default: 0"),
      tensorflow::Flag("max_num_load_retries", &options.max_num_load_retries,
                       "maximum number of times it retries loading a model "
                       "after the first failure, before giving up. "
                       "If set to 0, a load is attempted only once. "
                       "Default: 5"),
      tensorflow::Flag("load_retry_interval_micros",
                       &options.load_retry_interval_micros,
                       "The interval, in microseconds, between each servable "
                       "load retry. If set negative, it doesn't wait. "
                       "Default: 1 minute"),
      tensorflow::Flag("file_system_poll_wait_seconds",
                       &options.file_system_poll_wait_seconds,
                       "Interval in seconds between each poll of the "
                       "filesystem for new model version. If set to zero "
                       "poll will be exactly done once and not periodically. "
                       "Setting this to negative value will disable polling "
                       "entirely causing ModelServer to indefinitely wait for "
                       "a new model at startup. Negative values are reserved "
                       "for testing purposes only."),
      tensorflow::Flag("flush_filesystem_caches",
                       &options.flush_filesystem_caches,
                       "If true (the default), filesystem caches will be "
                       "flushed after the initial load of all servables, and "
                       "after each subsequent individual servable reload (if "
                       "the number of load threads is 1). This reduces memory "
                       "consumption of the model server, at the potential cost "
                       "of cache misses if model files are accessed after "
                       "servables are loaded."),
      tensorflow::Flag("tensorflow_session_parallelism",
                       &options.tensorflow_session_parallelism,
                       "Number of threads to use for running a "
                       "Tensorflow session. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag(
          "tensorflow_session_config_file",
          &options.tensorflow_session_config_file,
          "If non-empty, read an ascii TensorFlow Session "
          "ConfigProto protobuf from the supplied file name. Note, "
          "parts of the session config (threads, parallelism etc.) "
          "can be overridden if needed, via corresponding command "
          "line flags."),
      tensorflow::Flag("tensorflow_intra_op_parallelism",
                       &options.tensorflow_intra_op_parallelism,
                       "Number of threads to use to parallelize the execution"
                       "of an individual op. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag("tensorflow_inter_op_parallelism",
                       &options.tensorflow_inter_op_parallelism,
                       "Controls the number of operators that can be executed "
                       "simultaneously. Auto-configured by default."
                       "Note that this option is ignored if "
                       "--platform_config_file is non-empty."),
      tensorflow::Flag("use_alts_credentials", &options.use_alts_credentials,
                       "Use Google ALTS credentials"),
      tensorflow::Flag(
          "ssl_config_file", &options.ssl_config_file,
          "If non-empty, read an ascii SSLConfig protobuf from "
          "the supplied file name and set up a secure gRPC channel"),
      tensorflow::Flag("platform_config_file", &options.platform_config_file,
                       "If non-empty, read an ascii PlatformConfigMap protobuf "
                       "from the supplied file name, and use that platform "
                       "config instead of the Tensorflow platform. (If used, "
                       "--enable_batching is ignored.)"),
      tensorflow::Flag(
          "per_process_gpu_memory_fraction",
          &options.per_process_gpu_memory_fraction,
          "Fraction that each process occupies of the GPU memory space "
          "the value is between 0.0 and 1.0 (with 0.0 as the default) "
          "If 1.0, the server will allocate all the memory when the server "
          "starts, If 0.0, Tensorflow will automatically select a value."),
      tensorflow::Flag("saved_model_tags", &options.saved_model_tags,
                       "Comma-separated set of tags corresponding to the meta "
                       "graph def to load from SavedModel."),
      tensorflow::Flag("grpc_channel_arguments",
                       &options.grpc_channel_arguments,
                       "A comma separated list of arguments to be passed to "
                       "the grpc server. (e.g. "
                       "grpc.max_connection_age_ms=2000)"),
      tensorflow::Flag("grpc_max_threads", &options.grpc_max_threads,
                       "Max grpc server threads to handle grpc messages."),
      tensorflow::Flag("enable_model_warmup", &options.enable_model_warmup,
                       "Enables model warmup, which triggers lazy "
                       "initializations (such as TF optimizations) at load "
                       "time, to reduce first request latency."),
      tensorflow::Flag("num_request_iterations_for_warmup",
                       &options.num_request_iterations_for_warmup,
                       "Number of times a request is iterated during warmup "
                       "replay. This value is used only if > 0."),
      tensorflow::Flag("version", &display_version, "Display version"),
      tensorflow::Flag(
          "monitoring_config_file", &options.monitoring_config_file,
          "If non-empty, read an ascii MonitoringConfig protobuf from "
          "the supplied file name"),
      tensorflow::Flag(
          "remove_unused_fields_from_bundle_metagraph",
          &options.remove_unused_fields_from_bundle_metagraph,
          "Removes unused fields from MetaGraphDef proto message to save "
          "memory."),
      tensorflow::Flag("prefer_tflite_model", &options.prefer_tflite_model,
                       "EXPERIMENTAL; CAN BE REMOVED ANYTIME! "
                       "Prefer TensorFlow Lite model from `model.tflite` file "
                       "in SavedModel directory, instead of the TensorFlow "
                       "model from `saved_model.pb` file. "
                       "If no TensorFlow Lite model found, fallback to "
                       "TensorFlow model."),
      tensorflow::Flag(
          "num_tflite_pools", &options.num_tflite_pools,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! Number of TFLite interpreters "
          "in an interpreter pool of TfLiteSession. Typically there is one "
          "TfLiteSession for each TF Lite model that is loaded. If not "
          "set, will be auto set based on number of CPUs."),
      tensorflow::Flag(
          "num_tflite_interpreters_per_pool",
          &options.num_tflite_interpreters_per_pool,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! Number of TFLite interpreters "
          "in an interpreter pool of TfLiteSession. Typically there is one "
          "TfLiteSession for each TF Lite model that is loaded. If not "
          "set, will be 1."),
      tensorflow::Flag(
          "enable_signature_method_name_check",
          &options.enable_signature_method_name_check,
          "Enable method_name check for SignatureDef. Disable this if serving "
          "native TF2 regression/classification models."),
      tensorflow::Flag(
          "xla_cpu_compilation_enabled", &xla_cpu_compilation_enabled,
          "EXPERIMENTAL; CAN BE REMOVED ANYTIME! "
          "Enable XLA:CPU JIT (default is disabled). With XLA:CPU JIT "
          "disabled, models utilizing this feature will return bad Status "
          "on first compilation request."),
      tensorflow::Flag("enable_profiler", &options.enable_profiler,
                       "Enable profiler service."),
      tensorflow::Flag("thread_pool_factory_config_file",
                       &options.thread_pool_factory_config_file,
                       "If non-empty, read an ascii ThreadPoolConfig protobuf "
                       "from the supplied file name.")};

  const auto& usage = tensorflow::Flags::Usage(argv[0], flag_list);
  if (!tensorflow::Flags::Parse(&argc, argv, flag_list)) {
    std::cout << usage;
    return -1;
  }

  tensorflow::port::InitMain(argv[0], &argc, &argv);
#if defined(LIBTPU_ON_GCE) || defined(PLATFORM_CLOUD_TPU)
  InitializeTPU(options);
#endif

  if (display_version) {
    std::cout << "TensorFlow ModelServer: " << TF_Serving_Version() << "\n"
              << "TensorFlow Library: " << TF_Version() << "\n";
    return 0;
  }

  if (argc != 1) {
    std::cout << "unknown argument: " << argv[1] << "\n" << usage;
  }

  if (!xla_cpu_compilation_enabled) {
    tensorflow::DisableXlaCompilation();
  }

  tensorflow::serving::main::Server server;
  const auto& status = server.BuildAndStart(options);
  if (!status.ok()) {
    std::cout << "Failed to start server. Error: " << status << "\n";
    return -1;
  }
  server.WaitForTermination();
  return 0;
}
<|endoftext|>


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

#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you have the Windows XP theme selected by
// inspecting a couple of metrics. It does not catch all cases, but it does
// pick up on classic vs xp, and normal vs large fonts. Something it misses
// is changes to the color scheme (which will infact cause pixel test
// failures).
//
// ** Expected dependencies **
// + Theme: Windows XP
// + Color scheme: Default (blue)
// + Font size: Normal
// + Font smoothing: off (minor impact).
//
static bool HasLayoutTestThemeDependenciesWin() {
  // This metric will be 17 when font size is "Normal". The size of drop-down
  // menus depends on it.
  if (::GetSystemMetrics(SM_CXVSCROLL) != 17)
    return false;

  // Check that the system fonts RenderThemeWin relies on are Tahoma 11 pt.
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != -11 ||
        0 != wcscmp(L"Tahoma", system_fonts[i]->lfFaceName))
      return false;
  }
  return true;
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  bool has_deps = HasLayoutTestThemeDependenciesWin();
  if (!has_deps) {
    fprintf(stderr,
            "\n"
            "###############################################################\n"
            "## Layout test system dependencies check failed.\n"
            "## Some layout tests may fail due to unexpected theme.\n"
            "##\n"
            "## To fix, go to Display Properties -> Appearance, and select:\n"
            "##  + Windows and buttons: Windows XP style\n"
            "##  + Color scheme: Default (blue)\n"
            "##  + Font size: Normal\n"
            "###############################################################\n");
  }
  return has_deps;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<commit_msg>redo CL 21368 - fix test shell on windows to accept vista sys deps<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  std::list<std::string> errors;

  OSVERSIONINFOEX osvi;
  ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  ::GetVersionEx((OSVERSIONINFO *)&osvi);

  // default to XP metrics, override if on Vista
  int requiredVScrollSize = 17;
  int requiredFontSize = -11; // 8 pt
  const WCHAR *requiredFont = L"Tahoma";
  bool isVista = false;
  if (osvi.dwMajorVersion == 6
      && osvi.dwMinorVersion == 0
      && osvi.wProductType == VER_NT_WORKSTATION) {
    requiredFont = L"Segoe UI";
    requiredFontSize = -12; // 9 pt
    isVista = true;
  } else if (osvi.dwMajorVersion == 5
             && osvi.dwMinorVersion == 1
             && osvi.wProductType == VER_NT_WORKSTATION) {
    // XP;
  } else {
    errors.push_back("Unsupported Operating System version "
                     "(must use XP or Vista)");
  }

  // on both XP and Vista, this metric will be 17 when font size is "Normal".
  // The size of drop-down menus depends on it.
  int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
  if (vScrollSize != requiredVScrollSize) {
    errors.push_back("Must use normal size fonts (96 dpi)");
  }

  // font smoothing (including ClearType) must be disabled
  BOOL bFontSmoothing;
  SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
                       (PVOID)&bFontSmoothing, (UINT)0);
  if (bFontSmoothing) {
    errors.push_back("Font smoothing (ClearType) must be disabled");
  }

  // Check that we're using the default system fonts
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != requiredFontSize ||
        wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
      if (isVista)
        errors.push_back("Must use either the Aero or Basic theme");
      else
        errors.push_back("Must use the default XP theme (Luna)");
      break;
    }
  }

  if (!errors.empty()) {
    fprintf(stderr, "%s",
      "##################################################################\n"
      "## Layout test system dependencies check failed.\n"
      "##\n");
    for (std::list<std::string>::iterator it = errors.begin();
         it != errors.end();
         ++it) {
      fprintf(stderr, "## %s\n", it->c_str());
    }
    fprintf(stderr, "%s",
      "##\n"
      "##################################################################\n");
  }
  return errors.empty();
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgUtil/RenderLeaf>
#include <osgUtil/RenderGraph>

using namespace osg;
using namespace osgUtil;

// comment if you are are working with vertex programs,
// but it does break osgreflect demo and perhaps others, so keep an eye
// out artifacts.
// #define APPLY_MATICES_BEFORE_STATE

void RenderLeaf::render(State& state,RenderLeaf* previous)
{

    if (previous)
    {

#ifdef APPLY_MATICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif
        // apply state if required.
        RenderGraph* prev_rg = previous->_parent;
        RenderGraph* prev_rg_parent = prev_rg->_parent;
        RenderGraph* rg = _parent;
        if (prev_rg_parent!=rg->_parent)
        {
            RenderGraph::moveRenderGraph(state,prev_rg_parent,rg->_parent);

            // send state changes and matrix changes to OpenGL.
            state.apply(rg->_stateset.get());

        }
        else if (rg!=prev_rg)
        {

            // send state changes and matrix changes to OpenGL.
            state.apply(rg->_stateset.get());

        }

#ifndef APPLY_MATICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // draw the drawable
        _drawable->draw(state);
    }
    else
    {
#ifdef APPLY_MATICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // apply state if required.
         RenderGraph::moveRenderGraph(state,NULL,_parent->_parent);

        state.apply(_parent->_stateset.get());

#ifndef APPLY_MATICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // draw the drawable
        _drawable->draw(state);
    }
}
<commit_msg>Fixed typo of APPLY_MATICES_BEFORE_STATE.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgUtil/RenderLeaf>
#include <osgUtil/RenderGraph>

using namespace osg;
using namespace osgUtil;

// comment if you are are working with vertex programs,
// but it does break osgreflect demo and perhaps others, so keep an eye
// out artifacts.
// #define APPLY_MATRICES_BEFORE_STATE

void RenderLeaf::render(State& state,RenderLeaf* previous)
{

    if (previous)
    {

#ifdef APPLY_MATRICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif
        // apply state if required.
        RenderGraph* prev_rg = previous->_parent;
        RenderGraph* prev_rg_parent = prev_rg->_parent;
        RenderGraph* rg = _parent;
        if (prev_rg_parent!=rg->_parent)
        {
            RenderGraph::moveRenderGraph(state,prev_rg_parent,rg->_parent);

            // send state changes and matrix changes to OpenGL.
            state.apply(rg->_stateset.get());

        }
        else if (rg!=prev_rg)
        {

            // send state changes and matrix changes to OpenGL.
            state.apply(rg->_stateset.get());

        }

#ifndef APPLY_MATRICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // draw the drawable
        _drawable->draw(state);
    }
    else
    {
#ifdef APPLY_MATRICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // apply state if required.
         RenderGraph::moveRenderGraph(state,NULL,_parent->_parent);

        state.apply(_parent->_stateset.get());

#ifndef APPLY_MATRICES_BEFORE_STATE
        // apply matrices if required.
        state.applyProjectionMatrix(_projection.get());
        state.applyModelViewMatrix(_modelview.get());
#endif

        // draw the drawable
        _drawable->draw(state);
    }
}
<|endoftext|>