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

#include "chrome/browser/android/signin/signin_manager_android.h"

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/browsing_data_remover.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/android_profile_oauth2_token_service.h"
#include "chrome/browser/signin/google_auto_login_helper.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profile_management_switches.h"
#include "jni/SigninManager_jni.h"

#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.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/user_cloud_policy_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
#endif

namespace {

// A BrowsingDataRemover::Observer that clears all Profile data and then
// invokes a callback and deletes itself.
class ProfileDataRemover : public BrowsingDataRemover::Observer {
 public:
  ProfileDataRemover(Profile* profile, const base::Closure& callback)
      : callback_(callback),
        origin_loop_(base::MessageLoopProxy::current()),
        remover_(BrowsingDataRemover::CreateForUnboundedRange(profile)) {
    remover_->AddObserver(this);
    remover_->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL);
  }

  virtual ~ProfileDataRemover() {}

  virtual void OnBrowsingDataRemoverDone() OVERRIDE {
    remover_->RemoveObserver(this);
    origin_loop_->PostTask(FROM_HERE, callback_);
    origin_loop_->DeleteSoon(FROM_HERE, this);
  }

 private:
  base::Closure callback_;
  scoped_refptr<base::MessageLoopProxy> origin_loop_;
  BrowsingDataRemover* remover_;

  DISALLOW_COPY_AND_ASSIGN(ProfileDataRemover);
};

}  // namespace

SigninManagerAndroid::SigninManagerAndroid(JNIEnv* env, jobject obj)
    : profile_(NULL),
      weak_factory_(this) {
  java_signin_manager_.Reset(env, obj);
  DCHECK(g_browser_process);
  DCHECK(g_browser_process->profile_manager());
  profile_ = g_browser_process->profile_manager()->GetDefaultProfile();
  DCHECK(profile_);
}

SigninManagerAndroid::~SigninManagerAndroid() {}

void SigninManagerAndroid::CheckPolicyBeforeSignIn(JNIEnv* env,
                                                   jobject obj,
                                                   jstring username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  username_ = base::android::ConvertJavaStringToUTF8(env, username);
  policy::UserPolicySigninService* service =
      policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
  service->RegisterForPolicy(
      base::android::ConvertJavaStringToUTF8(env, username),
      base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone,
                 weak_factory_.GetWeakPtr()));
#else
  // This shouldn't be called when ShouldLoadPolicyForUser() is false.
  NOTREACHED();
  base::android::ScopedJavaLocalRef<jstring> domain;
  Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
                                                 java_signin_manager_.obj(),
                                                 domain.obj());
#endif
}

void SigninManagerAndroid::FetchPolicyBeforeSignIn(JNIEnv* env, jobject obj) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  if (!dm_token_.empty()) {
    policy::UserPolicySigninService* service =
        policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
    service->FetchPolicyForSignedInUser(
        username_,
        dm_token_,
        client_id_,
        base::Bind(&SigninManagerAndroid::OnPolicyFetchDone,
                   weak_factory_.GetWeakPtr()));
    dm_token_.clear();
    client_id_.clear();
    return;
  }
#endif
  // This shouldn't be called when ShouldLoadPolicyForUser() is false, or when
  // CheckPolicyBeforeSignIn() failed.
  NOTREACHED();
  Java_SigninManager_onPolicyFetchedBeforeSignIn(env,
                                                 java_signin_manager_.obj());
}

void SigninManagerAndroid::OnSignInCompleted(JNIEnv* env,
                                             jobject obj,
                                             jstring username) {
  SigninManagerFactory::GetForProfile(profile_)->OnExternalSigninCompleted(
      base::android::ConvertJavaStringToUTF8(env, username));
}

void SigninManagerAndroid::SignOut(JNIEnv* env, jobject obj) {
  SigninManagerFactory::GetForProfile(profile_)->SignOut();
}

base::android::ScopedJavaLocalRef<jstring>
SigninManagerAndroid::GetManagementDomain(JNIEnv* env, jobject obj) {
  base::android::ScopedJavaLocalRef<jstring> domain;

#if defined(ENABLE_CONFIGURATION_POLICY)
  policy::UserCloudPolicyManager* manager =
      policy::UserCloudPolicyManagerFactory::GetForBrowserContext(profile_);
  policy::CloudPolicyStore* store = manager->core()->store();

  if (store && store->is_managed() && store->policy()->has_username()) {
    domain.Reset(
        base::android::ConvertUTF8ToJavaString(
            env, gaia::ExtractDomainName(store->policy()->username())));
  }
#endif

  return domain;
}

void SigninManagerAndroid::WipeProfileData(JNIEnv* env, jobject obj) {
  // The ProfileDataRemover deletes itself once done.
  new ProfileDataRemover(
      profile_,
      base::Bind(&SigninManagerAndroid::OnBrowsingDataRemoverDone,
                 weak_factory_.GetWeakPtr()));
}

#if defined(ENABLE_CONFIGURATION_POLICY)

void SigninManagerAndroid::OnPolicyRegisterDone(
    const std::string& dm_token,
    const std::string& client_id) {
  dm_token_ = dm_token;
  client_id_ = client_id_;

  JNIEnv* env = base::android::AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jstring> domain;
  if (!dm_token_.empty()) {
    DCHECK(!username_.empty());
    domain.Reset(
        base::android::ConvertUTF8ToJavaString(
            env, gaia::ExtractDomainName(username_)));
  } else {
    username_.clear();
  }

  Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
                                                 java_signin_manager_.obj(),
                                                 domain.obj());
}

void SigninManagerAndroid::OnPolicyFetchDone(bool success) {
  Java_SigninManager_onPolicyFetchedBeforeSignIn(
      base::android::AttachCurrentThread(),
      java_signin_manager_.obj());
}

#endif

void SigninManagerAndroid::OnBrowsingDataRemoverDone() {
  BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
  model->RemoveAll();

  // All the Profile data has been wiped. Clear the last signed in username as
  // well, so that the next signin doesn't trigger the acount change dialog.
  profile_->GetPrefs()->ClearPref(prefs::kGoogleServicesLastUsername);

  Java_SigninManager_onProfileDataWiped(base::android::AttachCurrentThread(),
                                        java_signin_manager_.obj());
}

void SigninManagerAndroid::LogInSignedInUser(JNIEnv* env, jobject obj) {
  if (switches::IsNewProfileManagement()) {
    // New Mirror code path that just fires the events and let the
    // Account Reconcilor handles everything.
    AndroidProfileOAuth2TokenService* token_service =
        ProfileOAuth2TokenServiceFactory::GetPlatformSpecificForProfile(
            profile_);
    const std::string& primary_acct = token_service->GetPrimaryAccountId();
    const std::vector<std::string>& ids = token_service->GetAccounts();
    token_service->ValidateAccounts(primary_acct, ids);

  } else {
    DVLOG(1) << "SigninManagerAndroid::LogInSignedInUser "
        " Manually calling GoogleAutoLoginHelper";
    // Old code path that doesn't depend on the new Account Reconcilor.
    // We manually login.

    // AutoLogin deletes itself.
    GoogleAutoLoginHelper* autoLogin = new GoogleAutoLoginHelper(profile_);
    autoLogin->LogIn();
  }
}

static jlong Init(JNIEnv* env, jobject obj) {
  SigninManagerAndroid* signin_manager_android =
      new SigninManagerAndroid(env, obj);
  return reinterpret_cast<intptr_t>(signin_manager_android);
}

static jboolean ShouldLoadPolicyForUser(JNIEnv* env,
                                        jobject obj,
                                        jstring j_username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  std::string username =
      base::android::ConvertJavaStringToUTF8(env, j_username);
  return !policy::BrowserPolicyConnector::IsNonEnterpriseUser(username);
#else
  return false;
#endif
}

// static
bool SigninManagerAndroid::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}
<commit_msg>Fix typo in SigninManagerAndroid that left client_id unset<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/signin/signin_manager_android.h"

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/browsing_data_helper.h"
#include "chrome/browser/browsing_data/browsing_data_remover.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/android_profile_oauth2_token_service.h"
#include "chrome/browser/signin/google_auto_login_helper.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profile_management_switches.h"
#include "jni/SigninManager_jni.h"

#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_android.h"
#include "chrome/browser/policy/cloud/user_policy_signin_service_factory.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/user_cloud_policy_manager.h"
#include "google_apis/gaia/gaia_auth_util.h"
#endif

namespace {

// A BrowsingDataRemover::Observer that clears all Profile data and then
// invokes a callback and deletes itself.
class ProfileDataRemover : public BrowsingDataRemover::Observer {
 public:
  ProfileDataRemover(Profile* profile, const base::Closure& callback)
      : callback_(callback),
        origin_loop_(base::MessageLoopProxy::current()),
        remover_(BrowsingDataRemover::CreateForUnboundedRange(profile)) {
    remover_->AddObserver(this);
    remover_->Remove(BrowsingDataRemover::REMOVE_ALL, BrowsingDataHelper::ALL);
  }

  virtual ~ProfileDataRemover() {}

  virtual void OnBrowsingDataRemoverDone() OVERRIDE {
    remover_->RemoveObserver(this);
    origin_loop_->PostTask(FROM_HERE, callback_);
    origin_loop_->DeleteSoon(FROM_HERE, this);
  }

 private:
  base::Closure callback_;
  scoped_refptr<base::MessageLoopProxy> origin_loop_;
  BrowsingDataRemover* remover_;

  DISALLOW_COPY_AND_ASSIGN(ProfileDataRemover);
};

}  // namespace

SigninManagerAndroid::SigninManagerAndroid(JNIEnv* env, jobject obj)
    : profile_(NULL),
      weak_factory_(this) {
  java_signin_manager_.Reset(env, obj);
  DCHECK(g_browser_process);
  DCHECK(g_browser_process->profile_manager());
  profile_ = g_browser_process->profile_manager()->GetDefaultProfile();
  DCHECK(profile_);
}

SigninManagerAndroid::~SigninManagerAndroid() {}

void SigninManagerAndroid::CheckPolicyBeforeSignIn(JNIEnv* env,
                                                   jobject obj,
                                                   jstring username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  username_ = base::android::ConvertJavaStringToUTF8(env, username);
  policy::UserPolicySigninService* service =
      policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
  service->RegisterForPolicy(
      base::android::ConvertJavaStringToUTF8(env, username),
      base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone,
                 weak_factory_.GetWeakPtr()));
#else
  // This shouldn't be called when ShouldLoadPolicyForUser() is false.
  NOTREACHED();
  base::android::ScopedJavaLocalRef<jstring> domain;
  Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
                                                 java_signin_manager_.obj(),
                                                 domain.obj());
#endif
}

void SigninManagerAndroid::FetchPolicyBeforeSignIn(JNIEnv* env, jobject obj) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  if (!dm_token_.empty()) {
    policy::UserPolicySigninService* service =
        policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
    service->FetchPolicyForSignedInUser(
        username_,
        dm_token_,
        client_id_,
        base::Bind(&SigninManagerAndroid::OnPolicyFetchDone,
                   weak_factory_.GetWeakPtr()));
    dm_token_.clear();
    client_id_.clear();
    return;
  }
#endif
  // This shouldn't be called when ShouldLoadPolicyForUser() is false, or when
  // CheckPolicyBeforeSignIn() failed.
  NOTREACHED();
  Java_SigninManager_onPolicyFetchedBeforeSignIn(env,
                                                 java_signin_manager_.obj());
}

void SigninManagerAndroid::OnSignInCompleted(JNIEnv* env,
                                             jobject obj,
                                             jstring username) {
  SigninManagerFactory::GetForProfile(profile_)->OnExternalSigninCompleted(
      base::android::ConvertJavaStringToUTF8(env, username));
}

void SigninManagerAndroid::SignOut(JNIEnv* env, jobject obj) {
  SigninManagerFactory::GetForProfile(profile_)->SignOut();
}

base::android::ScopedJavaLocalRef<jstring>
SigninManagerAndroid::GetManagementDomain(JNIEnv* env, jobject obj) {
  base::android::ScopedJavaLocalRef<jstring> domain;

#if defined(ENABLE_CONFIGURATION_POLICY)
  policy::UserCloudPolicyManager* manager =
      policy::UserCloudPolicyManagerFactory::GetForBrowserContext(profile_);
  policy::CloudPolicyStore* store = manager->core()->store();

  if (store && store->is_managed() && store->policy()->has_username()) {
    domain.Reset(
        base::android::ConvertUTF8ToJavaString(
            env, gaia::ExtractDomainName(store->policy()->username())));
  }
#endif

  return domain;
}

void SigninManagerAndroid::WipeProfileData(JNIEnv* env, jobject obj) {
  // The ProfileDataRemover deletes itself once done.
  new ProfileDataRemover(
      profile_,
      base::Bind(&SigninManagerAndroid::OnBrowsingDataRemoverDone,
                 weak_factory_.GetWeakPtr()));
}

#if defined(ENABLE_CONFIGURATION_POLICY)

void SigninManagerAndroid::OnPolicyRegisterDone(
    const std::string& dm_token,
    const std::string& client_id) {
  dm_token_ = dm_token;
  client_id_ = client_id;

  JNIEnv* env = base::android::AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jstring> domain;
  if (!dm_token_.empty()) {
    DCHECK(!username_.empty());
    domain.Reset(
        base::android::ConvertUTF8ToJavaString(
            env, gaia::ExtractDomainName(username_)));
  } else {
    username_.clear();
  }

  Java_SigninManager_onPolicyCheckedBeforeSignIn(env,
                                                 java_signin_manager_.obj(),
                                                 domain.obj());
}

void SigninManagerAndroid::OnPolicyFetchDone(bool success) {
  Java_SigninManager_onPolicyFetchedBeforeSignIn(
      base::android::AttachCurrentThread(),
      java_signin_manager_.obj());
}

#endif

void SigninManagerAndroid::OnBrowsingDataRemoverDone() {
  BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile_);
  model->RemoveAll();

  // All the Profile data has been wiped. Clear the last signed in username as
  // well, so that the next signin doesn't trigger the acount change dialog.
  profile_->GetPrefs()->ClearPref(prefs::kGoogleServicesLastUsername);

  Java_SigninManager_onProfileDataWiped(base::android::AttachCurrentThread(),
                                        java_signin_manager_.obj());
}

void SigninManagerAndroid::LogInSignedInUser(JNIEnv* env, jobject obj) {
  if (switches::IsNewProfileManagement()) {
    // New Mirror code path that just fires the events and let the
    // Account Reconcilor handles everything.
    AndroidProfileOAuth2TokenService* token_service =
        ProfileOAuth2TokenServiceFactory::GetPlatformSpecificForProfile(
            profile_);
    const std::string& primary_acct = token_service->GetPrimaryAccountId();
    const std::vector<std::string>& ids = token_service->GetAccounts();
    token_service->ValidateAccounts(primary_acct, ids);

  } else {
    DVLOG(1) << "SigninManagerAndroid::LogInSignedInUser "
        " Manually calling GoogleAutoLoginHelper";
    // Old code path that doesn't depend on the new Account Reconcilor.
    // We manually login.

    // AutoLogin deletes itself.
    GoogleAutoLoginHelper* autoLogin = new GoogleAutoLoginHelper(profile_);
    autoLogin->LogIn();
  }
}

static jlong Init(JNIEnv* env, jobject obj) {
  SigninManagerAndroid* signin_manager_android =
      new SigninManagerAndroid(env, obj);
  return reinterpret_cast<intptr_t>(signin_manager_android);
}

static jboolean ShouldLoadPolicyForUser(JNIEnv* env,
                                        jobject obj,
                                        jstring j_username) {
#if defined(ENABLE_CONFIGURATION_POLICY)
  std::string username =
      base::android::ConvertJavaStringToUTF8(env, j_username);
  return !policy::BrowserPolicyConnector::IsNonEnterpriseUser(username);
#else
  return false;
#endif
}

// static
bool SigninManagerAndroid::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}
<|endoftext|>


<commit_before>#include <net/tcp/connection.hpp>
#include <net/stream.hpp>

// TCP stream

namespace net::tcp
{
  /**
   * @brief      Exposes a TCP Connection as a Stream with only the most necessary features.
   *             May be overrided by extensions like TLS etc for additional functionality.
   */
  class Stream final : public net::Stream {
  public:
    static const uint16_t SUBID = 1;
    /**
     * @brief      Construct a Stream for a Connection ptr
     *
     * @param[in]  conn  The connection
     */
    Stream(Connection_ptr conn)
      : m_tcp{std::move(conn)}
    {
      // stream for a nullptr makes no sense
      Expects(m_tcp != nullptr);
      m_tcp->on_close({this, &Stream::close});
    }
    ~Stream()
    {
      this->reset_callbacks();
      m_tcp->close();
    }

    /**
     * @brief      Event when the stream is connected/established/ready to use.
     *
     * @param[in]  cb    The connect callback
     */
    void on_connect(ConnectCallback cb) override
    {
      m_tcp->on_connect(Connection::ConnectCallback::make_packed(
          [this, cb] (Connection_ptr conn)
          { if(conn) cb(*this); }));
    }

    /**
     * @brief      Event when data is received.
     *
     * @param[in]  n     The size of the receive buffer
     * @param[in]  cb    The read callback
     */
    void on_read(size_t n, ReadCallback cb) override
    { m_tcp->on_read(n, cb); }

    /**
     * @brief      Event for when the Stream is being closed.
     *
     * @param[in]  cb    The close callback
     */
    void on_close(CloseCallback cb) override
    {
      m_on_close = std::move(cb);
    }

    /**
     * @brief      Event for when data has been written.
     *
     * @param[in]  cb    The write callback
     */
    void on_write(WriteCallback cb) override
    { m_tcp->on_write(cb); }

    /**
     * @brief      Async write of a data with a length.
     *
     * @param[in]  buf   data
     * @param[in]  n     length
     */
    void write(const void* buf, size_t n) override
    { m_tcp->write(buf, n); }

    /**
     * @brief      Async write of a shared buffer with a length.
     *
     * @param[in]  buffer  shared buffer
     * @param[in]  n       length
     */
    void write(buffer_t buffer) override
    { m_tcp->write(buffer); }

    /**
     * @brief      Async write of a string.
     *             Calls write(const void* buf, size_t n)
     *
     * @param[in]  str   The string
     */
    void write(const std::string& str) override
    { write(str.data(), str.size()); }

    /**
     * @brief      Closes the stream.
     */
    void close() override
    {
      auto onclose = std::move(this->m_on_close);
      m_tcp->reset_callbacks();
      m_tcp->close();
      if (onclose) onclose();
    }

    /**
     * @brief      Resets all callbacks.
     */
    void reset_callbacks() override
    { m_tcp->reset_callbacks(); }

    /**
     * @brief      Returns the streams local socket.
     *
     * @return     A TCP Socket
     */
    Socket local() const override
    { return m_tcp->local(); }

    /**
     * @brief      Returns the streams remote socket.
     *
     * @return     A TCP Socket
     */
    Socket remote() const override
    { return m_tcp->remote(); }

    /**
     * @brief      Returns a string representation of the stream.
     *
     * @return     String representation of the stream.
     */
    std::string to_string() const override
    { return m_tcp->to_string(); }

    /**
     * @brief      Determines if connected (established).
     *
     * @return     True if connected, False otherwise.
     */
    bool is_connected() const noexcept override
    { return m_tcp->is_connected(); }

    /**
     * @brief      Determines if writable. (write is allowed)
     *
     * @return     True if writable, False otherwise.
     */
    bool is_writable() const noexcept override
    { return m_tcp->is_writable(); }

    /**
     * @brief      Determines if readable. (data can be received)
     *
     * @return     True if readable, False otherwise.
     */
    bool is_readable() const noexcept override
    { return m_tcp->is_readable(); }

    /**
     * @brief      Determines if closing.
     *
     * @return     True if closing, False otherwise.
     */
    bool is_closing() const noexcept override
    { return m_tcp->is_closing(); }

    /**
     * @brief      Determines if closed.
     *
     * @return     True if closed, False otherwise.
     */
    bool is_closed() const noexcept override
    { return m_tcp->is_closed(); };

    int get_cpuid() const noexcept override;

    size_t serialize_to(void* p, const size_t) const override {
      return m_tcp->serialize_to(p);
    }
    uint16_t serialization_subid() const override {
      return SUBID;
    }

    Stream* transport() noexcept override {
      return nullptr;
    }

    Connection_ptr tcp() {
      return this->m_tcp;
    }

  protected:
    Connection_ptr m_tcp;
    CloseCallback  m_on_close = nullptr;

  }; // < class Connection::Stream

}
<commit_msg>tcp: At least call close when Stream connect fails<commit_after>#include <net/tcp/connection.hpp>
#include <net/stream.hpp>

// TCP stream

namespace net::tcp
{
  /**
   * @brief      Exposes a TCP Connection as a Stream with only the most necessary features.
   *             May be overrided by extensions like TLS etc for additional functionality.
   */
  class Stream final : public net::Stream {
  public:
    static const uint16_t SUBID = 1;
    /**
     * @brief      Construct a Stream for a Connection ptr
     *
     * @param[in]  conn  The connection
     */
    Stream(Connection_ptr conn)
      : m_tcp{std::move(conn)}
    {
      // stream for a nullptr makes no sense
      Expects(m_tcp != nullptr);
      m_tcp->on_close({this, &Stream::close});
    }
    ~Stream()
    {
      this->reset_callbacks();
      m_tcp->close();
    }

    /**
     * @brief      Event when the stream is connected/established/ready to use.
     *
     * @param[in]  cb    The connect callback
     */
    void on_connect(ConnectCallback cb) override
    {
      m_tcp->on_connect(Connection::ConnectCallback::make_packed(
          [this, cb] (Connection_ptr conn)
          {
            // this will ensure at least close is called if the connect fails
            if (conn != nullptr) {
              cb(*this);
            }
            else {
              if (this->m_on_close) this->m_on_close();
            }
          }));
    }

    /**
     * @brief      Event when data is received.
     *
     * @param[in]  n     The size of the receive buffer
     * @param[in]  cb    The read callback
     */
    void on_read(size_t n, ReadCallback cb) override
    { m_tcp->on_read(n, cb); }

    /**
     * @brief      Event for when the Stream is being closed.
     *
     * @param[in]  cb    The close callback
     */
    void on_close(CloseCallback cb) override
    {
      m_on_close = std::move(cb);
    }

    /**
     * @brief      Event for when data has been written.
     *
     * @param[in]  cb    The write callback
     */
    void on_write(WriteCallback cb) override
    { m_tcp->on_write(cb); }

    /**
     * @brief      Async write of a data with a length.
     *
     * @param[in]  buf   data
     * @param[in]  n     length
     */
    void write(const void* buf, size_t n) override
    { m_tcp->write(buf, n); }

    /**
     * @brief      Async write of a shared buffer with a length.
     *
     * @param[in]  buffer  shared buffer
     * @param[in]  n       length
     */
    void write(buffer_t buffer) override
    { m_tcp->write(buffer); }

    /**
     * @brief      Async write of a string.
     *             Calls write(const void* buf, size_t n)
     *
     * @param[in]  str   The string
     */
    void write(const std::string& str) override
    { write(str.data(), str.size()); }

    /**
     * @brief      Closes the stream.
     */
    void close() override
    {
      auto onclose = std::move(this->m_on_close);
      m_tcp->reset_callbacks();
      m_tcp->close();
      if (onclose) onclose();
    }

    /**
     * @brief      Resets all callbacks.
     */
    void reset_callbacks() override
    { m_tcp->reset_callbacks(); }

    /**
     * @brief      Returns the streams local socket.
     *
     * @return     A TCP Socket
     */
    Socket local() const override
    { return m_tcp->local(); }

    /**
     * @brief      Returns the streams remote socket.
     *
     * @return     A TCP Socket
     */
    Socket remote() const override
    { return m_tcp->remote(); }

    /**
     * @brief      Returns a string representation of the stream.
     *
     * @return     String representation of the stream.
     */
    std::string to_string() const override
    { return m_tcp->to_string(); }

    /**
     * @brief      Determines if connected (established).
     *
     * @return     True if connected, False otherwise.
     */
    bool is_connected() const noexcept override
    { return m_tcp->is_connected(); }

    /**
     * @brief      Determines if writable. (write is allowed)
     *
     * @return     True if writable, False otherwise.
     */
    bool is_writable() const noexcept override
    { return m_tcp->is_writable(); }

    /**
     * @brief      Determines if readable. (data can be received)
     *
     * @return     True if readable, False otherwise.
     */
    bool is_readable() const noexcept override
    { return m_tcp->is_readable(); }

    /**
     * @brief      Determines if closing.
     *
     * @return     True if closing, False otherwise.
     */
    bool is_closing() const noexcept override
    { return m_tcp->is_closing(); }

    /**
     * @brief      Determines if closed.
     *
     * @return     True if closed, False otherwise.
     */
    bool is_closed() const noexcept override
    { return m_tcp->is_closed(); };

    int get_cpuid() const noexcept override;

    size_t serialize_to(void* p, const size_t) const override {
      return m_tcp->serialize_to(p);
    }
    uint16_t serialization_subid() const override {
      return SUBID;
    }

    Stream* transport() noexcept override {
      return nullptr;
    }

    Connection_ptr tcp() {
      return this->m_tcp;
    }

  protected:
    Connection_ptr m_tcp;
    CloseCallback  m_on_close = nullptr;

  }; // < class Connection::Stream

}
<|endoftext|>


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

#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
                                                     AutoFillManager* host)
    : ConfirmInfoBarDelegate(tab_contents),
      browser_(NULL),
      host_(host) {
  if (tab_contents) {
    // This is NULL for TestTabContents.
    if (tab_contents->delegate())
      browser_ = tab_contents->delegate()->GetBrowser();

    tab_contents->AddInfoBar(this);
  }
}

AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}

bool AutoFillCCInfoBarDelegate::ShouldExpire(
    const NavigationController::LoadCommittedDetails& details) const {
  // The user has submitted a form, causing the page to navigate elsewhere. We
  // don't want the infobar to be expired at this point, because the user won't
  // get a chance to answer the question.
  return false;
}

void AutoFillCCInfoBarDelegate::InfoBarClosed() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }

  // This will delete us.
  ConfirmInfoBarDelegate::InfoBarClosed();
}

std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}

SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_AUTOFILL);
}

int AutoFillCCInfoBarDelegate::GetButtons() const {
  return BUTTON_OK | BUTTON_CANCEL;
}

std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  if (button == BUTTON_OK)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
  else if (button == BUTTON_CANCEL)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
  else
    NOTREACHED();

  return std::wstring();
}

bool AutoFillCCInfoBarDelegate::Accept() {
  if (host_) {
    host_->OnInfoBarClosed(true);
    host_ = NULL;
  }
  return true;
}

bool AutoFillCCInfoBarDelegate::Cancel() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }
  return true;
}

std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
  return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}

bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
  browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
                    PageTransition::TYPED);
  return false;
}

#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
  return CreateAutofillCcInfoBar(this);
}
#endif  // defined(OS_WIN)

<commit_msg>AutoFill: Collect UMA stats for AutoFill CC InfoBar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/histogram.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
                                                     AutoFillManager* host)
    : ConfirmInfoBarDelegate(tab_contents),
      browser_(NULL),
      host_(host) {
  if (tab_contents) {
    // This is NULL for TestTabContents.
    if (tab_contents->delegate())
      browser_ = tab_contents->delegate()->GetBrowser();

    tab_contents->AddInfoBar(this);
  }
}

AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}

bool AutoFillCCInfoBarDelegate::ShouldExpire(
    const NavigationController::LoadCommittedDetails& details) const {
  // The user has submitted a form, causing the page to navigate elsewhere. We
  // don't want the infobar to be expired at this point, because the user won't
  // get a chance to answer the question.
  return false;
}

void AutoFillCCInfoBarDelegate::InfoBarClosed() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }

  // This will delete us.
  ConfirmInfoBarDelegate::InfoBarClosed();
}

std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}

SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_AUTOFILL);
}

int AutoFillCCInfoBarDelegate::GetButtons() const {
  return BUTTON_OK | BUTTON_CANCEL;
}

std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  if (button == BUTTON_OK)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
  else if (button == BUTTON_CANCEL)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
  else
    NOTREACHED();

  return std::wstring();
}

bool AutoFillCCInfoBarDelegate::Accept() {
  UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarAccepted", 1);
  if (host_) {
    host_->OnInfoBarClosed(true);
    host_ = NULL;
  }
  return true;
}

bool AutoFillCCInfoBarDelegate::Cancel() {
  UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarDenied", 1);
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }
  return true;
}

std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
  return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}

bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
  browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
                    PageTransition::TYPED);
  return false;
}

#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
  return CreateAutofillCcInfoBar(this);
}
#endif  // defined(OS_WIN)

<|endoftext|>


<commit_before>/*
   webpresenceplugin.cpp

   Kopete Web Presence plugin

   Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>

   Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

 *************************************************************************
 *                                                                    	*
 * This program is free software; you can redistribute it and/or modify  *
 * it under the terms of the GNU General Public License as published by  *
 * the Free Software Foundation; either version 2 of the License, or     *
 * (at your option) any later version.                                   *
 *                                                                       *
 *************************************************************************
 */

#include <qtimer.h>
#include <qptrlist.h>
#include <qfile.h>

#include <kdebug.h>
#include <kgenericfactory.h>
#include <ktempfile.h>
#include <kio/job.h>
#include <knotifyclient.h>
#include <kaction.h>
#include <kstdguiitem.h>
#include <kstandarddirs.h>

#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/DOCBparser.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>

#include "kopetecontactlist.h"
#include "pluginloader.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"

#include "webpresenceplugin.h"
#include "webpresencepreferences.h"

K_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );

	WebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& /*args*/ )
: KopetePlugin( parent, name )
{
	m_prefs = new WebPresencePreferences( "", this );
	connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
	m_timer = new QTimer();
	connect ( m_timer, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );
	m_timer->start( m_prefs->frequency() * 1000 * 60);
}

WebPresencePlugin::~WebPresencePlugin()
{}

void WebPresencePlugin::slotWriteFile()
{
	bool error = false;
	// generate the (temporary) XML file representing the current contactlist
	KTempFile* xml = generateFile();
	xml->setAutoDelete( true );

	kdDebug() << "WebPresencePlugin::slotWriteFile() : " << xml->name()
		<< endl;

	if ( m_prefs->justXml() )
	{
	    m_output = xml;
		xml = 0L;
	}
	else
	{
		// transform XML to the final format
		m_output = new KTempFile();
		m_output->setAutoDelete( true );
		if ( !transform( xml, m_output ) )
		{
			error = true;
			delete m_output;
		}
		delete xml; // might make debugging harder!
	}
	if ( !error )
	{
		// upload it to the specified URL
		KURL src( m_output->name() );
		KURL dest( m_prefs->url() );
		KIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );
		connect( job, SIGNAL( result( KIO::Job * ) ),
				SLOT(  slotUploadJobResult( KIO::Job * ) ) );
	}
}

void WebPresencePlugin::slotUploadJobResult( KIO::Job *job )
{
	if (  job->error() ) {
		kdDebug() << "Error uploading presence info." << endl;
		job->showErrorDialog( 0 );
	}
	delete m_output;
	return;
}

KTempFile* WebPresencePlugin::generateFile()
{
	kdDebug() << "WebPresencePlugin::generateFile()" << endl;
	// generate the (temporary) file representing the current contactlist
	KTempFile* theFile = new KTempFile();
	QTextStream* qout =  theFile->textStream() ;
	QPtrList<KopeteProtocol> protocols = allProtocols();

	int depth = 0;
	QString shift;
	*qout << "<?xml version=\"1.0\"?>\n"
		<< shift.fill( '\t', ++depth ) << "<contacts>\n";

	*qout << shift.fill( '\t', ++depth ) << "<contact type=\"self\">\n";

	*qout << shift.fill( '\t', ++depth ) << "<name>";
	if ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )
		*qout << m_prefs->userName();
	else
		*qout << protocols.first()->myself()->displayName();
	*qout << "</name>\n";

	*qout << shift.fill( '\t', depth++ ) << "<protocols>\n";
	for ( KopeteProtocol *p = protocols.first();
			p; p = protocols.next() )
	{
		Q_ASSERT( p );
		kdDebug() << p->pluginId() << endl;
		kdDebug() << statusAsString(  p->myself()->status() ) << endl;
		kdDebug() << p->myself()->contactId().latin1() << endl;

		*qout << shift.fill( '\t', depth++ ) << "<protocol>\n";
		*qout << shift.fill( '\t', depth ) << "<protoname>"
			<< p->pluginId() << "</protoname>\n";
		*qout << shift.fill( '\t', depth ) << "<protostatus>"
			<< statusAsString( p->myself()->status() )
			<< "</protostatus>\n";
		if ( m_prefs->showAddresses() )
		{
			*qout << shift.fill( '\t', depth ) << "<protoaddress>"
				<< p->myself()->contactId().latin1()
				<< "</protoaddress>\n";
		}
		*qout << shift.fill( '\t', --depth ) << "</protocol>\n";
	}
	*qout << shift.fill( '\t', --depth ) << "</protocols>\n";
	*qout << shift.fill( '\t', --depth ) << "</contact>\n";

	*qout << shift.fill( '\t', --depth ) << "</contacts>\n" << endl;

	theFile->close();
	return theFile;
}

bool WebPresencePlugin::transform( KTempFile* src, KTempFile* dest )
{
	xmlSubstituteEntitiesDefault( 1 );
	xmlLoadExtDtdDefaultValue = 1;
	// test if the stylesheet exists
	QFile sheet;
	if ( m_prefs->useDefaultStyleSheet() )
		sheet.setName( locateLocal( "appdata", "webpresencedefault.xsl" ) );
	else
		sheet.setName( m_prefs->userStyleSheet() );

	QString error = "";
	if ( sheet.exists() )
	{
		// and if it is a valid stylesheet
		xsltStylesheetPtr cur = NULL;
		if ( ( cur = xsltParseStylesheetFile(
					( const xmlChar *) sheet.name().latin1() ) ) )
		{
			// and if we can parse the input XML
			xmlDocPtr doc = NULL;
			if ( ( doc = xmlParseFile( src->name() ) ) )
			{
				// and if we can apply the stylesheet
				xmlDocPtr res = NULL;
				if ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )
				{
					// and if we can save the result
					if ( xsltSaveResultToFile(dest->fstream() , res, cur)
							!= -1 )
					{
						// then it all worked!
						dest->close();
					}
					else
						error = "write result!";
				}
				else
				{
					error = "apply stylesheet!";
					error += " Check the stylesheet works using xsltproc";
				}
				xmlFreeDoc(res);
			}
			else
				error = "parse input XML!";
			xmlFreeDoc(doc);
		}
		else
			error = "parse stylesheet!";
		xsltFreeStylesheet(cur);
	}
	else
		error = "find stylesheet!";

	xsltCleanupGlobals();
	xmlCleanupParser();

	if ( error.isEmpty() )
		return true;
	else
	{
		kdDebug() << "WebPresencePlugin::transform() - couldn't "
			<< error << endl;
		return false;
	}
}

QPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()
{
	kdDebug() << "WebPresencePlugin::allProtocols()" << endl;
	QPtrList<KopeteProtocol> protos;
	QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();

	for( KopetePlugin *p = plugins.first(); p; p = plugins.next() )
	{
		KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
		if( !proto )
			continue;
		protos.append( proto );
	}
	return protos;
}

QString WebPresencePlugin::statusAsString( KopeteContact::ContactStatus c )
{
	QString status;
	switch ( c )
	{
		case KopeteContact::Online:
			status = "ONLINE";
			break;
		case KopeteContact::Away:
			status = "AWAY";
			break;
		case KopeteContact::Offline:
			status = "OFFLINE";
			break;
		default:
			status = "UNKNOWN";
	}
	return status;
}

void WebPresencePlugin::slotSettingsChanged()
{
	m_timer->start( m_prefs->frequency() * 1000 * 60);
}

// vim: set noet ts=4 sts=4 sw=4:
#include "webpresenceplugin.moc"
<commit_msg>Now looking for the default stylesheet where it gets installed.<commit_after>/*
   webpresenceplugin.cpp

   Kopete Web Presence plugin

   Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>

   Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

 *************************************************************************
 *                                                                    	*
 * This program is free software; you can redistribute it and/or modify  *
 * it under the terms of the GNU General Public License as published by  *
 * the Free Software Foundation; either version 2 of the License, or     *
 * (at your option) any later version.                                   *
 *                                                                       *
 *************************************************************************
 */

#include <qtimer.h>
#include <qptrlist.h>
#include <qfile.h>

#include <kdebug.h>
#include <kgenericfactory.h>
#include <ktempfile.h>
#include <kio/job.h>
#include <knotifyclient.h>
#include <kaction.h>
#include <kstdguiitem.h>
#include <kstandarddirs.h>

#include <libxml/xmlmemory.h>
#include <libxml/debugXML.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlIO.h>
#include <libxml/DOCBparser.h>
#include <libxml/xinclude.h>
#include <libxml/catalog.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>

#include "kopetecontactlist.h"
#include "pluginloader.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"

#include "webpresenceplugin.h"
#include "webpresencepreferences.h"

K_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );

	WebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& /*args*/ )
: KopetePlugin( parent, name )
{
	m_prefs = new WebPresencePreferences( "", this );
	connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
	m_timer = new QTimer();
	connect ( m_timer, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );
	m_timer->start( m_prefs->frequency() * 1000 * 60);
}

WebPresencePlugin::~WebPresencePlugin()
{}

void WebPresencePlugin::slotWriteFile()
{
	bool error = false;
	// generate the (temporary) XML file representing the current contactlist
	KTempFile* xml = generateFile();
	xml->setAutoDelete( true );

	kdDebug() << "WebPresencePlugin::slotWriteFile() : " << xml->name()
		<< endl;

	if ( m_prefs->justXml() )
	{
	    m_output = xml;
		xml = 0L;
	}
	else
	{
		// transform XML to the final format
		m_output = new KTempFile();
		m_output->setAutoDelete( true );
		if ( !transform( xml, m_output ) )
		{
			error = true;
			delete m_output;
		}
		delete xml; // might make debugging harder!
	}
	if ( !error )
	{
		// upload it to the specified URL
		KURL src( m_output->name() );
		KURL dest( m_prefs->url() );
		KIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );
		connect( job, SIGNAL( result( KIO::Job * ) ),
				SLOT(  slotUploadJobResult( KIO::Job * ) ) );
	}
}

void WebPresencePlugin::slotUploadJobResult( KIO::Job *job )
{
	if (  job->error() ) {
		kdDebug() << "Error uploading presence info." << endl;
		job->showErrorDialog( 0 );
	}
	delete m_output;
	return;
}

KTempFile* WebPresencePlugin::generateFile()
{
	kdDebug() << "WebPresencePlugin::generateFile()" << endl;
	// generate the (temporary) file representing the current contactlist
	KTempFile* theFile = new KTempFile();
	QTextStream* qout =  theFile->textStream() ;
	QPtrList<KopeteProtocol> protocols = allProtocols();

	int depth = 0;
	QString shift;
	*qout << "<?xml version=\"1.0\"?>\n"
		<< shift.fill( '\t', ++depth ) << "<contacts>\n";

	*qout << shift.fill( '\t', ++depth ) << "<contact type=\"self\">\n";

	*qout << shift.fill( '\t', ++depth ) << "<name>";
	if ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )
		*qout << m_prefs->userName();
	else
		*qout << protocols.first()->myself()->displayName();
	*qout << "</name>\n";

	*qout << shift.fill( '\t', depth++ ) << "<protocols>\n";
	for ( KopeteProtocol *p = protocols.first();
			p; p = protocols.next() )
	{
		Q_ASSERT( p );
		kdDebug() << p->pluginId() << endl;
		kdDebug() << statusAsString(  p->myself()->status() ) << endl;
		kdDebug() << p->myself()->contactId().latin1() << endl;

		*qout << shift.fill( '\t', depth++ ) << "<protocol>\n";
		*qout << shift.fill( '\t', depth ) << "<protoname>"
			<< p->pluginId() << "</protoname>\n";
		*qout << shift.fill( '\t', depth ) << "<protostatus>"
			<< statusAsString( p->myself()->status() )
			<< "</protostatus>\n";
		if ( m_prefs->showAddresses() )
		{
			*qout << shift.fill( '\t', depth ) << "<protoaddress>"
				<< p->myself()->contactId().latin1()
				<< "</protoaddress>\n";
		}
		*qout << shift.fill( '\t', --depth ) << "</protocol>\n";
	}
	*qout << shift.fill( '\t', --depth ) << "</protocols>\n";
	*qout << shift.fill( '\t', --depth ) << "</contact>\n";

	*qout << shift.fill( '\t', --depth ) << "</contacts>\n" << endl;

	theFile->close();
	return theFile;
}

bool WebPresencePlugin::transform( KTempFile* src, KTempFile* dest )
{
	xmlSubstituteEntitiesDefault( 1 );
	xmlLoadExtDtdDefaultValue = 1;
	// test if the stylesheet exists
	QFile sheet;
	if ( m_prefs->useDefaultStyleSheet() )
		sheet.setName( locate( "appdata", "webpresencedefault.xsl" ) );
	else
		sheet.setName( m_prefs->userStyleSheet() );

	QString error = "";
	if ( sheet.exists() )
	{
		// and if it is a valid stylesheet
		xsltStylesheetPtr cur = NULL;
		if ( ( cur = xsltParseStylesheetFile(
					( const xmlChar *) sheet.name().latin1() ) ) )
		{
			// and if we can parse the input XML
			xmlDocPtr doc = NULL;
			if ( ( doc = xmlParseFile( src->name() ) ) )
			{
				// and if we can apply the stylesheet
				xmlDocPtr res = NULL;
				if ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )
				{
					// and if we can save the result
					if ( xsltSaveResultToFile(dest->fstream() , res, cur)
							!= -1 )
					{
						// then it all worked!
						dest->close();
					}
					else
						error = "write result!";
				}
				else
				{
					error = "apply stylesheet!";
					error += " Check the stylesheet works using xsltproc";
				}
				xmlFreeDoc(res);
			}
			else
				error = "parse input XML!";
			xmlFreeDoc(doc);
		}
		else
			error = "parse stylesheet!";
		xsltFreeStylesheet(cur);
	}
	else
		error = "find stylesheet!";

	xsltCleanupGlobals();
	xmlCleanupParser();

	if ( error.isEmpty() )
		return true;
	else
	{
		kdDebug() << "WebPresencePlugin::transform() - couldn't "
			<< error << endl;
		return false;
	}
}

QPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()
{
	kdDebug() << "WebPresencePlugin::allProtocols()" << endl;
	QPtrList<KopeteProtocol> protos;
	QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();

	for( KopetePlugin *p = plugins.first(); p; p = plugins.next() )
	{
		KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );
		if( !proto )
			continue;
		protos.append( proto );
	}
	return protos;
}

QString WebPresencePlugin::statusAsString( KopeteContact::ContactStatus c )
{
	QString status;
	switch ( c )
	{
		case KopeteContact::Online:
			status = "ONLINE";
			break;
		case KopeteContact::Away:
			status = "AWAY";
			break;
		case KopeteContact::Offline:
			status = "OFFLINE";
			break;
		default:
			status = "UNKNOWN";
	}
	return status;
}

void WebPresencePlugin::slotSettingsChanged()
{
	m_timer->start( m_prefs->frequency() * 1000 * 60);
}

// vim: set noet ts=4 sts=4 sw=4:
#include "webpresenceplugin.moc"
<|endoftext|>


<commit_before>#ifndef AL_PARAMETERMIDI_H
#define AL_PARAMETERMIDI_H

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012-2015. The Regents of the University of California.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

		Redistributions of source code must retain the above copyright notice,
		this list of conditions and the following disclaimer.

		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in the
		documentation and/or other materials provided with the distribution.

		Neither the name of the University of California nor the names of its
		contributors may be used to endorse or promote products derived from
		this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.

	File description:
	Class to connect MIDI Input to Parameter objects
	File author(s):
	Andrés Cabrera mantaraya36@gmail.com
*/

#include "allocore/io/al_MIDI.hpp"
#include "allocore/ui/al_Parameter.hpp"

namespace al
{

/**
 * @brief The ParameterMIDI class connects Parameter objects to MIDI messages
 *
 *
@code
    Parameter Size("Size", "", 1.0, "", 0, 1.0);
    Parameter Speed("Speed", "", 0.05, "", 0.01, 0.3);

    ParameterMIDI parameterMIDI;

    parameterMIDI.connectControl(Size, 1, 1);
    parameterMIDI.connectControl(Speed, 10, 1);
@endcode
 *
 */
class ParameterMIDI : public MIDIMessageHandler {
public:
	ParameterMIDI(int deviceIndex = 0, bool verbose = false) {
		MIDIMessageHandler::bindTo(mMidiIn);
		mVerbose = verbose;
		try {
			mMidiIn.openPort(deviceIndex);
			printf("Opened port to %s\n", mMidiIn.getPortName(deviceIndex).c_str());
		}
		catch (al::MIDIError error) {
			std::cout << "ParameterMIDI Warning: Could not open MIDI port " << deviceIndex << std::endl;
		}
	}

	void connectControl(Parameter &param, int controlNumber, int channel)
	{
		connectControl(param, controlNumber, channel, (float) param.min(), (float) param.max());
	}

	void connectControl(Parameter &param, int controlNumber, int channel,
	                    float min, float max) {
		ControlBinding newBinding;
		newBinding.controlNumber = controlNumber;
		newBinding.channel = channel - 1;
		newBinding.param = &param;
		newBinding.min = min;
		newBinding.max = max;
		mBindings.push_back(newBinding);
	}

	/**
	 * @brief connectNoteToValue
	 * @param param the parameter to bind
	 * @param channel MIDI channel (1-16)
	 * @param min The parameter value to map the lowest note
	 * @param low The MIDI note number for the lowest (or only) note to map
	 * @param max The value unto which the highest note is mapped
	 * @param high The highest MIDI note number to map
	 */
	void connectNoteToValue(Parameter &param, int channel,
	                        float min, int low,
	                        float max = -1, int high = -1) {
		if (high == -1) {
			max = min;
			high = low;
		}
		for (int num = low; num <= high; ++num) {
			NoteBinding newBinding;
			newBinding.noteNumber = num;
			if (num != high) {
				newBinding.value = min + (max - min) * (num - low)/(high - low);
			} else {
				newBinding.value = max;
			}
			newBinding.channel = channel - 1;
			newBinding.param = &param;
			mNoteBindings.push_back(newBinding);
		}
	}

	void connectNoteToIncrement(Parameter &param, int channel, int note,
	                            float increment) {
		IncrementBinding newBinding;
		newBinding.channel = channel - 1;
		newBinding.noteNumber = note;
		newBinding.increment = increment;
		newBinding.param = &param;
		mIncrementBindings.push_back(newBinding);
	}

	virtual void onMIDIMessage(const MIDIMessage& m) override {
		if (m.type() & MIDIByte::CONTROL_CHANGE ) {
			for(ControlBinding binding: mBindings) {
				if (m.channel() == binding.channel
				        && m.controlNumber() == binding.controlNumber) {
					float newValue = binding.min + (m.controlValue() * (binding.max - binding.min));
					binding.param->set(newValue);
				}
			}
		}
		if (m.type() & MIDIByte::NOTE_ON && m.velocity() > 0) {
			for(NoteBinding binding: mNoteBindings) {
				if (m.channel() == binding.channel
				        && m.noteNumber() == binding.noteNumber) {
					binding.param->set(binding.value);
				}
			}
			for(IncrementBinding binding: mIncrementBindings) {
				if (m.channel() == binding.channel
				        && m.noteNumber() == binding.noteNumber) {
					binding.param->set(binding.param->get() + binding.increment);
				}
			}
		}
		if (mVerbose) {
			m.print();
		}
	}

private:

	struct ControlBinding {
		int controlNumber;
		int channel;
		Parameter *param;
		float min, max;
	};

	struct NoteBinding {
		int noteNumber;
		int channel;
		float value;
		Parameter *param;
	};

	struct IncrementBinding {
		int noteNumber;
		int channel;
		float increment;
		Parameter *param;
	};

	MIDIIn mMidiIn;
	bool mVerbose;
	std::vector<ControlBinding> mBindings;
	std::vector<NoteBinding> mNoteBindings;
	std::vector<IncrementBinding> mIncrementBindings;
};

}

#endif // AL_PARAMETERMIDI_H
<commit_msg>Added connectNoteToToggle function to ParameterMIDI<commit_after>#ifndef AL_PARAMETERMIDI_H
#define AL_PARAMETERMIDI_H

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012-2015. The Regents of the University of California.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

		Redistributions of source code must retain the above copyright notice,
		this list of conditions and the following disclaimer.

		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in the
		documentation and/or other materials provided with the distribution.

		Neither the name of the University of California nor the names of its
		contributors may be used to endorse or promote products derived from
		this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.

	File description:
	Class to connect MIDI Input to Parameter objects
	File author(s):
	Andrés Cabrera mantaraya36@gmail.com
*/

#include "allocore/io/al_MIDI.hpp"
#include "allocore/ui/al_Parameter.hpp"

namespace al
{

/**
 * @brief The ParameterMIDI class connects Parameter objects to MIDI messages
 *
 *
@code
    Parameter Size("Size", "", 1.0, "", 0, 1.0);
    Parameter Speed("Speed", "", 0.05, "", 0.01, 0.3);

    ParameterMIDI parameterMIDI;

    parameterMIDI.connectControl(Size, 1, 1);
    parameterMIDI.connectControl(Speed, 10, 1);
@endcode
 *
 */
class ParameterMIDI : public MIDIMessageHandler {
public:
	ParameterMIDI(int deviceIndex = 0, bool verbose = false) {
		MIDIMessageHandler::bindTo(mMidiIn);
		mVerbose = verbose;
		try {
			mMidiIn.openPort(deviceIndex);
			printf("Opened port to %s\n", mMidiIn.getPortName(deviceIndex).c_str());
		}
		catch (al::MIDIError error) {
			std::cout << "ParameterMIDI Warning: Could not open MIDI port " << deviceIndex << std::endl;
		}
	}

	void connectControl(Parameter &param, int controlNumber, int channel)
	{
		connectControl(param, controlNumber, channel, (float) param.min(), (float) param.max());
	}

	void connectControl(Parameter &param, int controlNumber, int channel,
	                    float min, float max) {
		ControlBinding newBinding;
		newBinding.controlNumber = controlNumber;
		newBinding.channel = channel - 1;
		newBinding.param = &param;
		newBinding.min = min;
		newBinding.max = max;
		mBindings.push_back(newBinding);
	}

	/**
	 * @brief connectNoteToValue
	 * @param param the parameter to bind
	 * @param channel MIDI channel (1-16)
	 * @param min The parameter value to map the lowest note
	 * @param low The MIDI note number for the lowest (or only) note to map
	 * @param max The value unto which the highest note is mapped
	 * @param high The highest MIDI note number to map
	 */
	void connectNoteToValue(Parameter &param, int channel,
	                        float min, int low,
	                        float max = -1, int high = -1) {
		if (high == -1) {
			max = min;
			high = low;
		}
		for (int num = low; num <= high; ++num) {
			NoteBinding newBinding;
			newBinding.noteNumber = num;
			if (num != high) {
				newBinding.value = min + (max - min) * (num - low)/(high - low);
			} else {
				newBinding.value = max;
			}
			newBinding.channel = channel - 1;
			newBinding.param = &param;
			mNoteBindings.push_back(newBinding);
		}
	}

	void connectNoteToToggle(ParameterBool &param, int channel, int note) {
		ToggleBinding newBinding;
		newBinding.noteNumber = note;
		newBinding.toggle = true;
		newBinding.channel = channel - 1;
		newBinding.param = &param;
		mToggleBindings.push_back(newBinding);
	}

	void connectNoteToIncrement(Parameter &param, int channel, int note,
	                            float increment) {
		IncrementBinding newBinding;
		newBinding.channel = channel - 1;
		newBinding.noteNumber = note;
		newBinding.increment = increment;
		newBinding.param = &param;
		mIncrementBindings.push_back(newBinding);
	}

	virtual void onMIDIMessage(const MIDIMessage& m) override {
		if (m.type() & MIDIByte::CONTROL_CHANGE ) {
			for(ControlBinding binding: mBindings) {
				if (m.channel() == binding.channel
				        && m.controlNumber() == binding.controlNumber) {
					float newValue = binding.min + (m.controlValue() * (binding.max - binding.min));
					binding.param->set(newValue);
				}
			}
		}
		if (m.type() & MIDIByte::NOTE_ON && m.velocity() > 0) {
			for(NoteBinding binding: mNoteBindings) {
				if (m.channel() == binding.channel
				        && m.noteNumber() == binding.noteNumber) {
					binding.param->set(binding.value);
				}
			}
			for(IncrementBinding binding: mIncrementBindings) {
				if (m.channel() == binding.channel
				        && m.noteNumber() == binding.noteNumber) {
					binding.param->set(binding.param->get() + binding.increment);
				}
			}
			for(ToggleBinding binding: mToggleBindings) {
				if (m.channel() == binding.channel
						&& m.noteNumber() == binding.noteNumber) {
					if (binding.toggle == true) {
						binding.param->set(
									binding.param->get() == binding.param->max() ?
										binding.param->min() : binding.param->max() );
					} else {
						binding.param->set(binding.param->max());
					}
				}
			}
		} else if (m.type() & MIDIByte::NOTE_OFF
				   || (m.type() & MIDIByte::NOTE_ON && m.velocity() == 0)) {

			for(ToggleBinding binding: mToggleBindings) {
				if (m.channel() == binding.channel
						&& m.noteNumber() == binding.noteNumber) {
					if (binding.toggle != true) {
						binding.param->set( binding.param->min() );
					}
				}
			}
		}
		if (mVerbose) {
			m.print();
		}
	}

private:

	struct ControlBinding {
		int controlNumber;
		int channel;
		Parameter *param;
		float min, max;
	};

	struct NoteBinding {
		int noteNumber;
		int channel;
		float value;
		Parameter *param;
	};

	struct ToggleBinding {
		int noteNumber;
		int channel;
		bool toggle;
		ParameterBool *param;
	};

	struct IncrementBinding {
		int noteNumber;
		int channel;
		float increment;
		Parameter *param;
	};

	MIDIIn mMidiIn;
	bool mVerbose;
	std::vector<ControlBinding> mBindings;
	std::vector<NoteBinding> mNoteBindings;
	std::vector<ToggleBinding> mToggleBindings;
	std::vector<IncrementBinding> mIncrementBindings;
};

}

#endif // AL_PARAMETERMIDI_H
<|endoftext|>


<commit_before>/* Copyright 2017 R. Thomas
 * Copyright 2017 Quarkslab
 *
 * 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.
 */
#include "LIEF/PE/utils.hpp"
#include "LIEF/MachO/utils.hpp"
#include "LIEF/ELF/utils.hpp"

#include "LIEF/OAT.hpp"
#include "LIEF/DEX.hpp"
#include "LIEF/VDEX.hpp"
#include "LIEF/ART.hpp"

#include "pyLIEF.hpp"

void init_utils_functions(py::module& m) {

  m.def("shell",
    [] (void) {
      auto&& InteractiveShellEmbed = py::module::import("IPython").attr("terminal").attr("embed").attr("InteractiveShellEmbed");
      auto&& ipshell = InteractiveShellEmbed("banner1"_a = "Dropping into IPython", "exit_msg"_a = "Leaving Interpreter, back to program.");
      return ipshell();
    },
    "Drop into an IPython Interpreter");

  m.def("demangle", [] (const std::string& name) -> py::object {
  #if defined(__unix__)
    int status;
    char* demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
    if (status == 0) {
      std::string realname = demangled_name;
      free(demangled_name);
      return py::str(realname);
    } else {
      return py::none();
    }
  #else
      return nullptr;
  #endif
  });

  m.def("breakp",
      [] (void) {
        py::object set_trace = py::module::import("pdb").attr("set_trace");
        return set_trace();
      },
      "Trigger 'pdb.set_trace()'");

#if defined(LIEF_PE_SUPPORT)
    m.def("is_pe",
        static_cast<bool (*)(const std::string&)>(&LIEF::PE::is_pe),
        "Check if the given file is a ``PE`` (from filename)",
        "filename"_a);

    m.def("is_pe",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::PE::is_pe),
        "Check if the given raw data is a ``PE``",
        "raw"_a);
#endif

#if defined(LIEF_ELF_SUPPORT)
    m.def("is_elf",
        static_cast<bool (*)(const std::string&)>(&LIEF::ELF::is_elf),
        "Check if the given file is an ``ELF``",
        "filename"_a);

    m.def("is_elf",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ELF::is_elf),
        "Check if the given raw data is an ``ELF``",
        "raw"_a);
#endif

#if defined(LIEF_MACHO_SUPPORT)
    m.def("is_macho",
        static_cast<bool (*)(const std::string&)>(&LIEF::MachO::is_macho),
        "Check if the given file is a ``MachO`` (from filename)",
        "filename"_a);

    m.def("is_macho",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::MachO::is_macho),
        "Check if the given raw data is a ``MachO``",
        "raw"_a);

#endif

#if defined(LIEF_OAT_SUPPORT)
    m.def("is_oat",
        static_cast<bool (*)(const std::string&)>(&LIEF::OAT::is_oat),
        "Check if the given file is an ``OAT`` (from filename)",
        "filename"_a);

    m.def("is_oat",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::is_oat),
        "Check if the given raw data is an ``OAT``",
        "raw"_a);

    m.def("is_oat",
        static_cast<bool (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::is_oat),
        "Check if the given " RST_CLASS_REF(lief.ELF.Binary) " is an ``OAT``",
        "elf"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const std::string&)>(&LIEF::OAT::version),
        "Return the OAT version of the given file",
        "filename"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::version),
        "Return the OAT version of the raw data",
        "raw"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::version),
        "Return the OAT version of the given " RST_CLASS_REF(lief.ELF.Binary) "",
        "elf"_a);

#endif

#if defined(LIEF_DEX_SUPPORT)
    m.def("is_dex",
        static_cast<bool (*)(const std::string&)>(&LIEF::DEX::is_dex),
        "Check if the given file is a ``DEX`` (from filename)",
        "filename"_a);

    m.def("is_dex",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::is_dex),
        "Check if the given raw data is a ``DEX``",
        "raw"_a);

    m.def("dex_version",
        static_cast<LIEF::DEX::dex_version_t (*)(const std::string&)>(&LIEF::DEX::version),
        "Return the OAT version of the given file",
        "filename"_a);

    m.def("dex_version",
        static_cast<LIEF::DEX::dex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::version),
        "Return the DEX version of the raw data",
        "raw"_a);

#endif

#if defined(LIEF_VDEX_SUPPORT)
    m.def("is_vdex",
        static_cast<bool (*)(const std::string&)>(&LIEF::VDEX::is_vdex),
        "Check if the given file is a ``VDEX`` (from filename)",
        "filename"_a);

    m.def("is_vdex",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::is_vdex),
        "Check if the given raw data is a ``VDEX``",
        "raw"_a);

    m.def("vdex_version",
        static_cast<LIEF::VDEX::vdex_version_t (*)(const std::string&)>(&LIEF::VDEX::version),
        "Return the VDEX version of the given file",
        "filename"_a);

    m.def("vdex_version",
        static_cast<LIEF::VDEX::vdex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::version),
        "Return the VDEX version of the raw data",
        "raw"_a);

#endif

#if defined(LIEF_ART_SUPPORT)
    m.def("is_art",
        static_cast<bool (*)(const std::string&)>(&LIEF::ART::is_art),
        "Check if the given file is an ``ART`` (from filename)",
        "filename"_a);

    m.def("is_art",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ART::is_art),
        "Check if the given raw data is an ``ART``",
        "raw"_a);

    m.def("art_version",
        static_cast<LIEF::ART::art_version_t (*)(const std::string&)>(&LIEF::ART::version),
        "Return the ART version of the given file",
        "filename"_a);

    m.def("art_version",
        static_cast<LIEF::ART::art_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::ART::version),
        "Return the ART version of the raw data",
        "raw"_a);

#endif

}
<commit_msg>Fix typo<commit_after>/* Copyright 2017 R. Thomas
 * Copyright 2017 Quarkslab
 *
 * 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.
 */
#include "LIEF/PE/utils.hpp"
#include "LIEF/MachO/utils.hpp"
#include "LIEF/ELF/utils.hpp"

#include "LIEF/OAT.hpp"
#include "LIEF/DEX.hpp"
#include "LIEF/VDEX.hpp"
#include "LIEF/ART.hpp"

#include "pyLIEF.hpp"

void init_utils_functions(py::module& m) {

  m.def("shell",
    [] (void) {
      auto&& InteractiveShellEmbed = py::module::import("IPython").attr("terminal").attr("embed").attr("InteractiveShellEmbed");
      auto&& ipshell = InteractiveShellEmbed("banner1"_a = "Dropping into IPython", "exit_msg"_a = "Leaving Interpreter, back to program.");
      return ipshell();
    },
    "Drop into an IPython Interpreter");

  m.def("demangle", [] (const std::string& name) -> py::object {
  #if defined(__unix__)
    int status;
    char* demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
    if (status == 0) {
      std::string realname = demangled_name;
      free(demangled_name);
      return py::str(realname);
    } else {
      return py::none();
    }
  #else
      return py::none();
  #endif
  });

  m.def("breakp",
      [] (void) {
        py::object set_trace = py::module::import("pdb").attr("set_trace");
        return set_trace();
      },
      "Trigger 'pdb.set_trace()'");

#if defined(LIEF_PE_SUPPORT)
    m.def("is_pe",
        static_cast<bool (*)(const std::string&)>(&LIEF::PE::is_pe),
        "Check if the given file is a ``PE`` (from filename)",
        "filename"_a);

    m.def("is_pe",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::PE::is_pe),
        "Check if the given raw data is a ``PE``",
        "raw"_a);
#endif

#if defined(LIEF_ELF_SUPPORT)
    m.def("is_elf",
        static_cast<bool (*)(const std::string&)>(&LIEF::ELF::is_elf),
        "Check if the given file is an ``ELF``",
        "filename"_a);

    m.def("is_elf",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ELF::is_elf),
        "Check if the given raw data is an ``ELF``",
        "raw"_a);
#endif

#if defined(LIEF_MACHO_SUPPORT)
    m.def("is_macho",
        static_cast<bool (*)(const std::string&)>(&LIEF::MachO::is_macho),
        "Check if the given file is a ``MachO`` (from filename)",
        "filename"_a);

    m.def("is_macho",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::MachO::is_macho),
        "Check if the given raw data is a ``MachO``",
        "raw"_a);

#endif

#if defined(LIEF_OAT_SUPPORT)
    m.def("is_oat",
        static_cast<bool (*)(const std::string&)>(&LIEF::OAT::is_oat),
        "Check if the given file is an ``OAT`` (from filename)",
        "filename"_a);

    m.def("is_oat",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::is_oat),
        "Check if the given raw data is an ``OAT``",
        "raw"_a);

    m.def("is_oat",
        static_cast<bool (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::is_oat),
        "Check if the given " RST_CLASS_REF(lief.ELF.Binary) " is an ``OAT``",
        "elf"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const std::string&)>(&LIEF::OAT::version),
        "Return the OAT version of the given file",
        "filename"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::OAT::version),
        "Return the OAT version of the raw data",
        "raw"_a);

    m.def("oat_version",
        static_cast<LIEF::OAT::oat_version_t (*)(const LIEF::ELF::Binary&)>(&LIEF::OAT::version),
        "Return the OAT version of the given " RST_CLASS_REF(lief.ELF.Binary) "",
        "elf"_a);

#endif

#if defined(LIEF_DEX_SUPPORT)
    m.def("is_dex",
        static_cast<bool (*)(const std::string&)>(&LIEF::DEX::is_dex),
        "Check if the given file is a ``DEX`` (from filename)",
        "filename"_a);

    m.def("is_dex",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::is_dex),
        "Check if the given raw data is a ``DEX``",
        "raw"_a);

    m.def("dex_version",
        static_cast<LIEF::DEX::dex_version_t (*)(const std::string&)>(&LIEF::DEX::version),
        "Return the OAT version of the given file",
        "filename"_a);

    m.def("dex_version",
        static_cast<LIEF::DEX::dex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::DEX::version),
        "Return the DEX version of the raw data",
        "raw"_a);

#endif

#if defined(LIEF_VDEX_SUPPORT)
    m.def("is_vdex",
        static_cast<bool (*)(const std::string&)>(&LIEF::VDEX::is_vdex),
        "Check if the given file is a ``VDEX`` (from filename)",
        "filename"_a);

    m.def("is_vdex",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::is_vdex),
        "Check if the given raw data is a ``VDEX``",
        "raw"_a);

    m.def("vdex_version",
        static_cast<LIEF::VDEX::vdex_version_t (*)(const std::string&)>(&LIEF::VDEX::version),
        "Return the VDEX version of the given file",
        "filename"_a);

    m.def("vdex_version",
        static_cast<LIEF::VDEX::vdex_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::VDEX::version),
        "Return the VDEX version of the raw data",
        "raw"_a);

#endif

#if defined(LIEF_ART_SUPPORT)
    m.def("is_art",
        static_cast<bool (*)(const std::string&)>(&LIEF::ART::is_art),
        "Check if the given file is an ``ART`` (from filename)",
        "filename"_a);

    m.def("is_art",
        static_cast<bool (*)(const std::vector<uint8_t>&)>(&LIEF::ART::is_art),
        "Check if the given raw data is an ``ART``",
        "raw"_a);

    m.def("art_version",
        static_cast<LIEF::ART::art_version_t (*)(const std::string&)>(&LIEF::ART::version),
        "Return the ART version of the given file",
        "filename"_a);

    m.def("art_version",
        static_cast<LIEF::ART::art_version_t (*)(const std::vector<uint8_t>&)>(&LIEF::ART::version),
        "Return the ART version of the raw data",
        "raw"_a);

#endif

}
<|endoftext|>


<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/autofill/risk/fingerprint.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "base/port.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "chrome/browser/autofill/risk/proto/fingerprint.pb.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebScreenInfo.h"
#include "ui/gfx/rect.h"

namespace autofill {
namespace risk {

const int64 kGaiaId = GG_INT64_C(99194853094755497);
const char kCharset[] = "UTF-8";
const char kAcceptLanguages[] = "en-US,en";
const int kScreenColorDepth = 53;

class AutofillRiskFingerprintTest : public InProcessBrowserTest {
 public:
  AutofillRiskFingerprintTest()
      : kWindowBounds(2, 3, 5, 7),
        kContentBounds(11, 13, 17, 37),
        kScreenBounds(0, 0, 101, 71),
        kAvailableScreenBounds(0, 11, 101, 60),
        kUnavailableScreenBounds(0, 0, 101, 11),
        message_loop_(MessageLoop::TYPE_UI) {}

  void GetFingerprintTestCallback(scoped_ptr<Fingerprint> fingerprint) {
    // TODO(isherman): Investigating http://crbug.com/174296
    LOG(WARNING) << "Callback called.";

    // Verify that all fields Chrome can fill have been filled.
    ASSERT_TRUE(fingerprint->has_machine_characteristics());
    const Fingerprint_MachineCharacteristics& machine =
        fingerprint->machine_characteristics();
    ASSERT_TRUE(machine.has_operating_system_build());
    ASSERT_TRUE(machine.has_browser_install_time_hours());
    ASSERT_GT(machine.font_size(), 0);
    ASSERT_GT(machine.plugin_size(), 0);
    ASSERT_TRUE(machine.has_utc_offset_ms());
    ASSERT_TRUE(machine.has_browser_language());
    ASSERT_GT(machine.requested_language_size(), 0);
    ASSERT_TRUE(machine.has_charset());
    ASSERT_TRUE(machine.has_screen_count());
    ASSERT_TRUE(machine.has_screen_size());
    ASSERT_TRUE(machine.screen_size().has_width());
    ASSERT_TRUE(machine.screen_size().has_height());
    ASSERT_TRUE(machine.has_screen_color_depth());
    ASSERT_TRUE(machine.has_unavailable_screen_size());
    ASSERT_TRUE(machine.unavailable_screen_size().has_width());
    ASSERT_TRUE(machine.unavailable_screen_size().has_height());
    ASSERT_TRUE(machine.has_user_agent());
    ASSERT_TRUE(machine.has_cpu());
    ASSERT_TRUE(machine.cpu().has_vendor_name());
    ASSERT_TRUE(machine.cpu().has_brand());
    ASSERT_TRUE(machine.has_ram());
    ASSERT_TRUE(machine.has_graphics_card());
    ASSERT_TRUE(machine.graphics_card().has_vendor_id());
    ASSERT_TRUE(machine.graphics_card().has_device_id());
    ASSERT_TRUE(machine.has_browser_build());

    ASSERT_TRUE(fingerprint->has_transient_state());
    const Fingerprint_TransientState& transient_state =
        fingerprint->transient_state();
    ASSERT_TRUE(transient_state.has_inner_window_size());
    ASSERT_TRUE(transient_state.has_outer_window_size());
    ASSERT_TRUE(transient_state.inner_window_size().has_width());
    ASSERT_TRUE(transient_state.inner_window_size().has_height());
    ASSERT_TRUE(transient_state.outer_window_size().has_width());
    ASSERT_TRUE(transient_state.outer_window_size().has_height());

    ASSERT_TRUE(fingerprint->has_metadata());
    ASSERT_TRUE(fingerprint->metadata().has_timestamp_ms());
    ASSERT_TRUE(fingerprint->metadata().has_gaia_id());
    ASSERT_TRUE(fingerprint->metadata().has_fingerprinter_version());

    // Some values have exact known (mocked out) values:
    ASSERT_EQ(2, machine.requested_language_size());
    EXPECT_EQ("en-US", machine.requested_language(0));
    EXPECT_EQ("en", machine.requested_language(1));
    EXPECT_EQ(kCharset, machine.charset());
    EXPECT_EQ(kScreenColorDepth, machine.screen_color_depth());
    EXPECT_EQ(kUnavailableScreenBounds.width(),
              machine.unavailable_screen_size().width());
    EXPECT_EQ(kUnavailableScreenBounds.height(),
              machine.unavailable_screen_size().height());
    EXPECT_EQ(kContentBounds.width(),
              transient_state.inner_window_size().width());
    EXPECT_EQ(kContentBounds.height(),
              transient_state.inner_window_size().height());
    EXPECT_EQ(kWindowBounds.width(),
              transient_state.outer_window_size().width());
    EXPECT_EQ(kWindowBounds.height(),
              transient_state.outer_window_size().height());
    EXPECT_EQ(kGaiaId, fingerprint->metadata().gaia_id());

    // TODO(isherman): Investigating http://crbug.com/174296
    LOG(WARNING) << "Stopping the message loop.";
    message_loop_.Quit();
  }

 protected:
  const gfx::Rect kWindowBounds;
  const gfx::Rect kContentBounds;
  const gfx::Rect kScreenBounds;
  const gfx::Rect kAvailableScreenBounds;
  const gfx::Rect kUnavailableScreenBounds;
  MessageLoop message_loop_;
};

// Test that getting a fingerprint works on some basic level.
IN_PROC_BROWSER_TEST_F(AutofillRiskFingerprintTest, GetFingerprint) {
  TestingPrefServiceSimple prefs;
  prefs.registry()->RegisterStringPref(prefs::kDefaultCharset, kCharset);
  prefs.registry()->RegisterStringPref(prefs::kAcceptLanguages,
                                       kAcceptLanguages);

  WebKit::WebScreenInfo screen_info;
  screen_info.depth = kScreenColorDepth;
  screen_info.rect = WebKit::WebRect(kScreenBounds);
  screen_info.availableRect = WebKit::WebRect(kAvailableScreenBounds);

  // TODO(isherman): Investigating http://crbug.com/174296
  LOG(WARNING) << "Loading fingerprint.";
  internal::GetFingerprintInternal(
      kGaiaId, kWindowBounds, kContentBounds, screen_info, prefs,
      base::Bind(&AutofillRiskFingerprintTest::GetFingerprintTestCallback,
                 base::Unretained(this)));

  // Wait for the callback to be called.
  // TODO(isherman): Investigating http://crbug.com/174296
  LOG(WARNING) << "Waiting for the callback to be called.";
  message_loop_.Run();
}

}  // namespace risk
}  // namespace autofill
<commit_msg>Disable AutofillRiskFingerprintTest.GetFingerprint on Windows<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/autofill/risk/fingerprint.h"

#include "base/bind.h"
#include "base/message_loop.h"
#include "base/port.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/testing_pref_service.h"
#include "chrome/browser/autofill/risk/proto/fingerprint.pb.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRect.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebScreenInfo.h"
#include "ui/gfx/rect.h"

namespace autofill {
namespace risk {

const int64 kGaiaId = GG_INT64_C(99194853094755497);
const char kCharset[] = "UTF-8";
const char kAcceptLanguages[] = "en-US,en";
const int kScreenColorDepth = 53;

class AutofillRiskFingerprintTest : public InProcessBrowserTest {
 public:
  AutofillRiskFingerprintTest()
      : kWindowBounds(2, 3, 5, 7),
        kContentBounds(11, 13, 17, 37),
        kScreenBounds(0, 0, 101, 71),
        kAvailableScreenBounds(0, 11, 101, 60),
        kUnavailableScreenBounds(0, 0, 101, 11),
        message_loop_(MessageLoop::TYPE_UI) {}

  void GetFingerprintTestCallback(scoped_ptr<Fingerprint> fingerprint) {
    // TODO(isherman): Investigating http://crbug.com/174296
    LOG(WARNING) << "Callback called.";

    // Verify that all fields Chrome can fill have been filled.
    ASSERT_TRUE(fingerprint->has_machine_characteristics());
    const Fingerprint_MachineCharacteristics& machine =
        fingerprint->machine_characteristics();
    ASSERT_TRUE(machine.has_operating_system_build());
    ASSERT_TRUE(machine.has_browser_install_time_hours());
    ASSERT_GT(machine.font_size(), 0);
    ASSERT_GT(machine.plugin_size(), 0);
    ASSERT_TRUE(machine.has_utc_offset_ms());
    ASSERT_TRUE(machine.has_browser_language());
    ASSERT_GT(machine.requested_language_size(), 0);
    ASSERT_TRUE(machine.has_charset());
    ASSERT_TRUE(machine.has_screen_count());
    ASSERT_TRUE(machine.has_screen_size());
    ASSERT_TRUE(machine.screen_size().has_width());
    ASSERT_TRUE(machine.screen_size().has_height());
    ASSERT_TRUE(machine.has_screen_color_depth());
    ASSERT_TRUE(machine.has_unavailable_screen_size());
    ASSERT_TRUE(machine.unavailable_screen_size().has_width());
    ASSERT_TRUE(machine.unavailable_screen_size().has_height());
    ASSERT_TRUE(machine.has_user_agent());
    ASSERT_TRUE(machine.has_cpu());
    ASSERT_TRUE(machine.cpu().has_vendor_name());
    ASSERT_TRUE(machine.cpu().has_brand());
    ASSERT_TRUE(machine.has_ram());
    ASSERT_TRUE(machine.has_graphics_card());
    ASSERT_TRUE(machine.graphics_card().has_vendor_id());
    ASSERT_TRUE(machine.graphics_card().has_device_id());
    ASSERT_TRUE(machine.has_browser_build());

    ASSERT_TRUE(fingerprint->has_transient_state());
    const Fingerprint_TransientState& transient_state =
        fingerprint->transient_state();
    ASSERT_TRUE(transient_state.has_inner_window_size());
    ASSERT_TRUE(transient_state.has_outer_window_size());
    ASSERT_TRUE(transient_state.inner_window_size().has_width());
    ASSERT_TRUE(transient_state.inner_window_size().has_height());
    ASSERT_TRUE(transient_state.outer_window_size().has_width());
    ASSERT_TRUE(transient_state.outer_window_size().has_height());

    ASSERT_TRUE(fingerprint->has_metadata());
    ASSERT_TRUE(fingerprint->metadata().has_timestamp_ms());
    ASSERT_TRUE(fingerprint->metadata().has_gaia_id());
    ASSERT_TRUE(fingerprint->metadata().has_fingerprinter_version());

    // Some values have exact known (mocked out) values:
    ASSERT_EQ(2, machine.requested_language_size());
    EXPECT_EQ("en-US", machine.requested_language(0));
    EXPECT_EQ("en", machine.requested_language(1));
    EXPECT_EQ(kCharset, machine.charset());
    EXPECT_EQ(kScreenColorDepth, machine.screen_color_depth());
    EXPECT_EQ(kUnavailableScreenBounds.width(),
              machine.unavailable_screen_size().width());
    EXPECT_EQ(kUnavailableScreenBounds.height(),
              machine.unavailable_screen_size().height());
    EXPECT_EQ(kContentBounds.width(),
              transient_state.inner_window_size().width());
    EXPECT_EQ(kContentBounds.height(),
              transient_state.inner_window_size().height());
    EXPECT_EQ(kWindowBounds.width(),
              transient_state.outer_window_size().width());
    EXPECT_EQ(kWindowBounds.height(),
              transient_state.outer_window_size().height());
    EXPECT_EQ(kGaiaId, fingerprint->metadata().gaia_id());

    // TODO(isherman): Investigating http://crbug.com/174296
    LOG(WARNING) << "Stopping the message loop.";
    message_loop_.Quit();
  }

 protected:
  const gfx::Rect kWindowBounds;
  const gfx::Rect kContentBounds;
  const gfx::Rect kScreenBounds;
  const gfx::Rect kAvailableScreenBounds;
  const gfx::Rect kUnavailableScreenBounds;
  MessageLoop message_loop_;
};

// This test is flaky on Windows. See http://crbug.com/178356.
#if defined(OS_WIN)
#define MAYBE_GetFingerprint DISABLE_GetFingerprint
#else
#define MAYBE_GetFingerprint GetFingerprint
#endif
// Test that getting a fingerprint works on some basic level.
IN_PROC_BROWSER_TEST_F(AutofillRiskFingerprintTest, MAYBE_GetFingerprint) {
  TestingPrefServiceSimple prefs;
  prefs.registry()->RegisterStringPref(prefs::kDefaultCharset, kCharset);
  prefs.registry()->RegisterStringPref(prefs::kAcceptLanguages,
                                       kAcceptLanguages);

  WebKit::WebScreenInfo screen_info;
  screen_info.depth = kScreenColorDepth;
  screen_info.rect = WebKit::WebRect(kScreenBounds);
  screen_info.availableRect = WebKit::WebRect(kAvailableScreenBounds);

  // TODO(isherman): Investigating http://crbug.com/174296
  LOG(WARNING) << "Loading fingerprint.";
  internal::GetFingerprintInternal(
      kGaiaId, kWindowBounds, kContentBounds, screen_info, prefs,
      base::Bind(&AutofillRiskFingerprintTest::GetFingerprintTestCallback,
                 base::Unretained(this)));

  // Wait for the callback to be called.
  // TODO(isherman): Investigating http://crbug.com/174296
  LOG(WARNING) << "Waiting for the callback to be called.";
  message_loop_.Run();
}

}  // namespace risk
}  // namespace autofill
<|endoftext|>


<commit_before>#ifndef CK_CONFIG_AMD_HPP
#define CK_CONFIG_AMD_HPP

#include "hip/hip_runtime.h"
#include "hip/hip_fp16.h"
#include "bfloat16_dev.hpp"

// index type: unsigned or signed
#define CK_UNSIGNED_INDEX_TYPE 0

// device backend
#define CK_DEVICE_BACKEND_AMD 1

// AMD inline asm
#ifndef CK_USE_AMD_INLINE_ASM
#define CK_USE_AMD_INLINE_ASM 0
#endif

#ifndef CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM
#define CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM 0
#endif

// AMD buffer addressing
#ifndef CK_USE_AMD_BUFFER_ADDRESSING
#define CK_USE_AMD_BUFFER_ADDRESSING 1
#endif

#ifndef CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC
#define CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC 1
#endif

// AMD XDLOPS
#ifndef CK_USE_AMD_XDLOPS
#define CK_USE_AMD_XDLOPS 1
#endif

#ifndef CK_USE_AMD_XDLOPS_INLINE_ASM
#define CK_USE_AMD_XDLOPS_INLINE_ASM 1
#endif

// experimental implementation
#define CK_EXPERIMENTAL_BLOCKWISE_GEMM_USE_PIPELINE 1
#define CK_EXPERIMENTAL_TENSOR_COORDINATE_USE_CALCULATE_OFFSET_DIFF 0
#define CK_EXPERIMENTAL_THREADWISE_COPY_V4R2_USE_OPTIMIZED_ADDRESS_CACLULATION 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_BLOCKWISE_GENERIC_SLICE_COPY_V1 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V1R2 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V2R1 0

// workaround
#define CK_WORKAROUND_SWDEV_202749 1

namespace ck {

enum AddressSpace
{
    generic,
    global
};

#if CK_UNSIGNED_INDEX_TYPE
using index_t = uint32_t;
#else
using index_t = int32_t;
#endif

// int32x4_t use by buffer_load and buffer_store llvm intrinsic
typedef int32_t int32x4_t __attribute__((ext_vector_type(4)));

} // namespace ck
#endif
<commit_msg>Avoid xdlops header files on non-xdlops GPUs (#2161)<commit_after>#ifndef CK_CONFIG_AMD_HPP
#define CK_CONFIG_AMD_HPP

#include "hip/hip_runtime.h"
#include "hip/hip_fp16.h"
#include "bfloat16_dev.hpp"

// index type: unsigned or signed
#define CK_UNSIGNED_INDEX_TYPE 0

// device backend
#define CK_DEVICE_BACKEND_AMD 1

// AMD inline asm
#ifndef CK_USE_AMD_INLINE_ASM
#define CK_USE_AMD_INLINE_ASM 1
#endif

#ifndef CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM
#define CK_THREADWISE_GEMM_USE_AMD_INLINE_ASM 1
#endif

// AMD buffer addressing
#ifndef CK_USE_AMD_BUFFER_ADDRESSING
#define CK_USE_AMD_BUFFER_ADDRESSING 1
#endif

#ifndef CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC
#define CK_USE_AMD_BUFFER_ADDRESSING_INTRINSIC 1
#endif

// AMD XDLOPS
#ifndef CK_USE_AMD_XDLOPS
#define CK_USE_AMD_XDLOPS 0
#endif

#ifndef CK_USE_AMD_XDLOPS_INLINE_ASM
#define CK_USE_AMD_XDLOPS_INLINE_ASM 0
#endif

// experimental implementation
#define CK_EXPERIMENTAL_BLOCKWISE_GEMM_USE_PIPELINE 1
#define CK_EXPERIMENTAL_TENSOR_COORDINATE_USE_CALCULATE_OFFSET_DIFF 0
#define CK_EXPERIMENTAL_THREADWISE_COPY_V4R2_USE_OPTIMIZED_ADDRESS_CACLULATION 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_BLOCKWISE_GENERIC_SLICE_COPY_V1 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V1R2 0
#define CK_EXPERIMENTAL_USE_MORE_COMPILE_STATIC_THREADWISE_GENERIC_TENSOR_SLICE_COPY_V2R1 0

// workaround
#define CK_WORKAROUND_SWDEV_202749 1

namespace ck {

enum AddressSpace
{
    generic,
    global
};

#if CK_UNSIGNED_INDEX_TYPE
using index_t = uint32_t;
#else
using index_t = int32_t;
#endif

// int32x4_t use by buffer_load and buffer_store llvm intrinsic
typedef int32_t int32x4_t __attribute__((ext_vector_type(4)));

} // namespace ck
#endif
<|endoftext|>