<commit_before>// Copyright (c) 2006-2008 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 "webkit/glue/plugins/mozilla_extensions.h"

#include <algorithm>

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_resolver_winhttp.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/plugins/plugin_instance.h"

#define QI_SUPPORTS_IID(iid, iface)                                           \
  QI_SUPPORTS_IID_(iid, iface::GetIID(), iface)

#define QI_SUPPORTS_IID_(src_iid, iface_iid, iface)                           \
  if (iid.Equals(iface_iid)) {                                                \
    AddRef();                                                                 \
    *result = static_cast<iface*>(this);                                      \
    return NS_OK;                                                             \
  }

namespace NPAPI
{

void MozillaExtensionApi::DetachFromInstance() {
  plugin_instance_ = NULL;
}

bool MozillaExtensionApi::FindProxyForUrl(const char* url,
                                          std::string* proxy) {
  bool result = false;

  if ((!url) || (!proxy)) {
    NOTREACHED();
    return result;
  }

  net::ProxyResolverWinHttp proxy_resolver;
  net::ProxyService proxy_service(&proxy_resolver);
  net::ProxyInfo proxy_info;

  if (proxy_service.ResolveProxy(GURL(std::string(url)),
                                 &proxy_info,
                                 NULL,
                                 NULL) == net::OK) {
    if (!proxy_info.is_direct()) {
      std::string winhttp_proxy = proxy_info.proxy_server();

      // Winhttp returns proxy in the the following format:
      // - HTTP proxy: "111.111.111.111:11"
      // -.SOCKS proxy: "socks=111.111.111.111:11"
      // - Mixed proxy: "http=111.111.111.111:11; socks=222.222.222.222:22"
      //
      // We need to translate this into the following format:
      // i)   "DIRECT"  -- no proxy
      // ii)  "PROXY xxx.xxx.xxx.xxx"   -- use proxy
      // iii) "SOCKS xxx.xxx.xxx.xxx"  -- use SOCKS
      // iv)  Mixed. e.g. "PROXY 111.111.111.111;PROXY 112.112.112.112",
      //                  "PROXY 111.111.111.111;SOCKS 112.112.112.112"....
      StringToLowerASCII(winhttp_proxy);
      if (std::string::npos == winhttp_proxy.find('=')) {
        // Proxy is in the form: "111.111.111.111:11"
        winhttp_proxy.insert(0, "http ");
      } else {
        // Proxy is in the following form.
        // -.SOCKS proxy: "socks=111.111.111.111:11"
        // - Mixed proxy: "http=111.111.111.111:11; socks=222.222.222.222:22"
        // in this case just replace the '=' with a space
        std::replace_if(winhttp_proxy.begin(),
                        winhttp_proxy.end(),
                        std::bind2nd(std::equal_to<char>(), '='), ' ');
      }

      *proxy = winhttp_proxy;
      result = true;
    }
  }

  return result;
}

// nsISupports implementation
NS_IMETHODIMP MozillaExtensionApi::QueryInterface(REFNSIID iid,
                                                  void** result) {
  static const nsIID knsISupportsIID = NS_ISUPPORTS_IID;
  QI_SUPPORTS_IID_(iid, knsISupportsIID, nsIServiceManager)
  QI_SUPPORTS_IID(iid, nsIServiceManager)
  QI_SUPPORTS_IID(iid, nsIPluginManager)
  QI_SUPPORTS_IID(iid, nsIPluginManager2)
  QI_SUPPORTS_IID(iid, nsICookieStorage)

  NOTREACHED();
  return NS_ERROR_NO_INTERFACE;
}

NS_IMETHODIMP_(nsrefcnt) MozillaExtensionApi::AddRef(void) {
  return InterlockedIncrement(reinterpret_cast<LONG*>(&ref_count_));
}

NS_IMETHODIMP_(nsrefcnt) MozillaExtensionApi::Release(void) {
  DCHECK(static_cast<int>(ref_count_) > 0);
  if (InterlockedDecrement(reinterpret_cast<LONG*>(&ref_count_)) == 0) {
    delete this;
    return 0;
  }

  return ref_count_;
}

NS_IMETHODIMP MozillaExtensionApi::GetService(REFNSIID class_guid,
                                              REFNSIID iid,
                                              void** result) {

  static const nsIID kPluginManagerCID = NS_PLUGINMANAGER_CID;
  static const nsIID kCookieStorageCID = NS_COOKIESTORAGE_CID;

  nsresult rv = NS_ERROR_FAILURE;

  if ((class_guid.Equals(kPluginManagerCID)) ||
      (class_guid.Equals(kCookieStorageCID))) {
    rv = QueryInterface(iid, result);
  }

  DCHECK(rv == NS_OK);
  return rv;
}

NS_IMETHODIMP MozillaExtensionApi::GetServiceByContractID(
    const char* contract_id,
    REFNSIID iid,
    void** result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::IsServiceInstantiated(REFNSIID class_guid,
                                                         REFNSIID iid,
                                                         PRBool* result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::IsServiceInstantiatedByContractID(
    const char* contract_id,
    REFNSIID iid,
    PRBool* result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetValue(nsPluginManagerVariable variable,
                                            void * value) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::ReloadPlugins(PRBool reloadPages) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UserAgent(
    const char** resultingAgentString) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetURL(
    nsISupports* pluginInst,
    const char* url,
    const char* target,
    nsIPluginStreamListener* streamListener,
    const char* altHost,
    const char* referrer,
    PRBool forceJSEnabled) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::PostURL(
    nsISupports* pluginInst,
    const char* url,
    unsigned int postDataLen,
    const char* postData,
    PRBool isFile,
    const char* target,
    nsIPluginStreamListener* streamListener,
    const char* altHost,
    const char* referrer,
    PRBool forceJSEnabled ,
    unsigned int postHeadersLength,
    const char* postHeaders) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::RegisterPlugin(
    REFNSIID aCID,
    const char *aPluginName,
    const char *aDescription,
    const char * * aMimeTypes,
    const char * * aMimeDescriptions,
    const char * * aFileExtensions,
    PRInt32 aCount) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UnregisterPlugin(REFNSIID aCID) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetURLWithHeaders(
    nsISupports* pluginInst,
    const char* url,
    const char* target /* = NULL */,
    nsIPluginStreamListener* streamListener /* = NULL */,
    const char* altHost /* = NULL */,
    const char* referrer /* = NULL */,
    PRBool forceJSEnabled /* = PR_FALSE */,
    PRUint32 getHeadersLength /* = 0 */,
    const char* getHeaders /* = NULL */){
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

// nsIPluginManager2
NS_IMETHODIMP MozillaExtensionApi::BeginWaitCursor() {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::EndWaitCursor() {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::SupportsURLProtocol(const char* aProtocol,
                                                       PRBool* aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::NotifyStatusChange(nsIPlugin* aPlugin,
                                                      nsresult aStatus) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::FindProxyForURL(
    const char* aURL,
    char** aResult) {
  std::string proxy = "DIRECT";
  FindProxyForUrl(aURL, &proxy);

  // Allocate this using the NPAPI allocator. The plugin will call
  // NPN_Free to free this.
  char* result = static_cast<char*>(NPN_MemAlloc(proxy.length() + 1));
  strncpy(result, proxy.c_str(), proxy.length() + 1);

  *aResult = result;
  return NS_OK;
}

NS_IMETHODIMP MozillaExtensionApi::RegisterWindow(
    nsIEventHandler* handler,
    nsPluginPlatformWindowRef window) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UnregisterWindow(
    nsIEventHandler* handler,
    nsPluginPlatformWindowRef win) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::AllocateMenuID(nsIEventHandler* aHandler,
                                                  PRBool aIsSubmenu,
                                                  PRInt16 *aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::DeallocateMenuID(nsIEventHandler* aHandler,
                                                    PRInt16 aMenuID) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::HasAllocatedMenuID(nsIEventHandler* aHandler,
                                                      PRInt16 aMenuID,
                                                      PRBool* aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

// nsICookieStorage
NS_IMETHODIMP MozillaExtensionApi::GetCookie(
    const char* url,
    void* cookie_buffer,
    PRUint32& buffer_size) {
  if ((!url) || (!cookie_buffer)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (!plugin_instance_)
    return NS_ERROR_FAILURE;

  WebPlugin* webplugin = plugin_instance_->webplugin();
  if (!webplugin)
    return NS_ERROR_FAILURE;

  // Bypass third-party cookie blocking by using the url as the policy_url.
  GURL cookies_url((std::string(url)));
  std::string cookies = webplugin->GetCookies(cookies_url, cookies_url);

  if (cookies.empty())
    return NS_ERROR_FAILURE;

  if(cookies.length() >= buffer_size)
    return NS_ERROR_FAILURE;

  strncpy(static_cast<char*>(cookie_buffer),
          cookies.c_str(),
          cookies.length() + 1);

  buffer_size = cookies.length();
  return NS_OK;
}

NS_IMETHODIMP MozillaExtensionApi::SetCookie(
    const char* url,
    const void* cookie_buffer,
    PRUint32 buffer_size){
  if ((!url) || (!cookie_buffer) || (!buffer_size)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (!plugin_instance_)
    return NS_ERROR_FAILURE;

  WebPlugin* webplugin = plugin_instance_->webplugin();
  if (!webplugin)
    return NS_ERROR_FAILURE;

  std::string cookie(static_cast<const char*>(cookie_buffer),
                     buffer_size);
  GURL cookies_url((std::string(url)));
  webplugin->SetCookie(cookies_url,
                       cookies_url,
                       cookie);
  return NS_OK;
}

} // namespace NPAPI

<commit_msg>Fix ProxyService usage in Java plugin proxy interface<commit_after>// Copyright (c) 2006-2008 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 "webkit/glue/plugins/mozilla_extensions.h"

#include <algorithm>

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_resolver_winhttp.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/plugins/plugin_instance.h"

#define QI_SUPPORTS_IID(iid, iface)                                           \
  QI_SUPPORTS_IID_(iid, iface::GetIID(), iface)

#define QI_SUPPORTS_IID_(src_iid, iface_iid, iface)                           \
  if (iid.Equals(iface_iid)) {                                                \
    AddRef();                                                                 \
    *result = static_cast<iface*>(this);                                      \
    return NS_OK;                                                             \
  }

namespace NPAPI
{

void MozillaExtensionApi::DetachFromInstance() {
  plugin_instance_ = NULL;
}

bool MozillaExtensionApi::FindProxyForUrl(const char* url,
                                          std::string* proxy) {
  bool result = false;

  if ((!url) || (!proxy)) {
    NOTREACHED();
    return result;
  }

  scoped_ptr<net::ProxyService> proxy_service(net::ProxyService::Create(NULL));
  if (!proxy_service.get()) {
    NOTREACHED();
    return result;
  }

  net::ProxyInfo proxy_info;
  if (proxy_service->ResolveProxy(GURL(std::string(url)),
                                 &proxy_info,
                                 NULL,
                                 NULL) == net::OK) {
    if (!proxy_info.is_direct()) {
      std::string winhttp_proxy = proxy_info.proxy_server();

      // Winhttp returns proxy in the the following format:
      // - HTTP proxy: "111.111.111.111:11"
      // -.SOCKS proxy: "socks=111.111.111.111:11"
      // - Mixed proxy: "http=111.111.111.111:11; socks=222.222.222.222:22"
      //
      // We need to translate this into the following format:
      // i)   "DIRECT"  -- no proxy
      // ii)  "PROXY xxx.xxx.xxx.xxx"   -- use proxy
      // iii) "SOCKS xxx.xxx.xxx.xxx"  -- use SOCKS
      // iv)  Mixed. e.g. "PROXY 111.111.111.111;PROXY 112.112.112.112",
      //                  "PROXY 111.111.111.111;SOCKS 112.112.112.112"....
      StringToLowerASCII(winhttp_proxy);
      if (std::string::npos == winhttp_proxy.find('=')) {
        // Proxy is in the form: "111.111.111.111:11"
        winhttp_proxy.insert(0, "http ");
      } else {
        // Proxy is in the following form.
        // -.SOCKS proxy: "socks=111.111.111.111:11"
        // - Mixed proxy: "http=111.111.111.111:11; socks=222.222.222.222:22"
        // in this case just replace the '=' with a space
        std::replace_if(winhttp_proxy.begin(),
                        winhttp_proxy.end(),
                        std::bind2nd(std::equal_to<char>(), '='), ' ');
      }

      *proxy = winhttp_proxy;
      result = true;
    }
  }

  return result;
}

// nsISupports implementation
NS_IMETHODIMP MozillaExtensionApi::QueryInterface(REFNSIID iid,
                                                  void** result) {
  static const nsIID knsISupportsIID = NS_ISUPPORTS_IID;
  QI_SUPPORTS_IID_(iid, knsISupportsIID, nsIServiceManager)
  QI_SUPPORTS_IID(iid, nsIServiceManager)
  QI_SUPPORTS_IID(iid, nsIPluginManager)
  QI_SUPPORTS_IID(iid, nsIPluginManager2)
  QI_SUPPORTS_IID(iid, nsICookieStorage)

  NOTREACHED();
  return NS_ERROR_NO_INTERFACE;
}

NS_IMETHODIMP_(nsrefcnt) MozillaExtensionApi::AddRef(void) {
  return InterlockedIncrement(reinterpret_cast<LONG*>(&ref_count_));
}

NS_IMETHODIMP_(nsrefcnt) MozillaExtensionApi::Release(void) {
  DCHECK(static_cast<int>(ref_count_) > 0);
  if (InterlockedDecrement(reinterpret_cast<LONG*>(&ref_count_)) == 0) {
    delete this;
    return 0;
  }

  return ref_count_;
}

NS_IMETHODIMP MozillaExtensionApi::GetService(REFNSIID class_guid,
                                              REFNSIID iid,
                                              void** result) {

  static const nsIID kPluginManagerCID = NS_PLUGINMANAGER_CID;
  static const nsIID kCookieStorageCID = NS_COOKIESTORAGE_CID;

  nsresult rv = NS_ERROR_FAILURE;

  if ((class_guid.Equals(kPluginManagerCID)) ||
      (class_guid.Equals(kCookieStorageCID))) {
    rv = QueryInterface(iid, result);
  }

  DCHECK(rv == NS_OK);
  return rv;
}

NS_IMETHODIMP MozillaExtensionApi::GetServiceByContractID(
    const char* contract_id,
    REFNSIID iid,
    void** result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::IsServiceInstantiated(REFNSIID class_guid,
                                                         REFNSIID iid,
                                                         PRBool* result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::IsServiceInstantiatedByContractID(
    const char* contract_id,
    REFNSIID iid,
    PRBool* result) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetValue(nsPluginManagerVariable variable,
                                            void * value) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::ReloadPlugins(PRBool reloadPages) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UserAgent(
    const char** resultingAgentString) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetURL(
    nsISupports* pluginInst,
    const char* url,
    const char* target,
    nsIPluginStreamListener* streamListener,
    const char* altHost,
    const char* referrer,
    PRBool forceJSEnabled) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::PostURL(
    nsISupports* pluginInst,
    const char* url,
    unsigned int postDataLen,
    const char* postData,
    PRBool isFile,
    const char* target,
    nsIPluginStreamListener* streamListener,
    const char* altHost,
    const char* referrer,
    PRBool forceJSEnabled ,
    unsigned int postHeadersLength,
    const char* postHeaders) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::RegisterPlugin(
    REFNSIID aCID,
    const char *aPluginName,
    const char *aDescription,
    const char * * aMimeTypes,
    const char * * aMimeDescriptions,
    const char * * aFileExtensions,
    PRInt32 aCount) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UnregisterPlugin(REFNSIID aCID) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::GetURLWithHeaders(
    nsISupports* pluginInst,
    const char* url,
    const char* target /* = NULL */,
    nsIPluginStreamListener* streamListener /* = NULL */,
    const char* altHost /* = NULL */,
    const char* referrer /* = NULL */,
    PRBool forceJSEnabled /* = PR_FALSE */,
    PRUint32 getHeadersLength /* = 0 */,
    const char* getHeaders /* = NULL */){
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

// nsIPluginManager2
NS_IMETHODIMP MozillaExtensionApi::BeginWaitCursor() {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::EndWaitCursor() {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::SupportsURLProtocol(const char* aProtocol,
                                                       PRBool* aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::NotifyStatusChange(nsIPlugin* aPlugin,
                                                      nsresult aStatus) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::FindProxyForURL(
    const char* aURL,
    char** aResult) {
  std::string proxy = "DIRECT";
  FindProxyForUrl(aURL, &proxy);

  // Allocate this using the NPAPI allocator. The plugin will call
  // NPN_Free to free this.
  char* result = static_cast<char*>(NPN_MemAlloc(proxy.length() + 1));
  strncpy(result, proxy.c_str(), proxy.length() + 1);

  *aResult = result;
  return NS_OK;
}

NS_IMETHODIMP MozillaExtensionApi::RegisterWindow(
    nsIEventHandler* handler,
    nsPluginPlatformWindowRef window) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::UnregisterWindow(
    nsIEventHandler* handler,
    nsPluginPlatformWindowRef win) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::AllocateMenuID(nsIEventHandler* aHandler,
                                                  PRBool aIsSubmenu,
                                                  PRInt16 *aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::DeallocateMenuID(nsIEventHandler* aHandler,
                                                    PRInt16 aMenuID) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP MozillaExtensionApi::HasAllocatedMenuID(nsIEventHandler* aHandler,
                                                      PRInt16 aMenuID,
                                                      PRBool* aResult) {
  NOTREACHED();
  return NS_ERROR_FAILURE;
}

// nsICookieStorage
NS_IMETHODIMP MozillaExtensionApi::GetCookie(
    const char* url,
    void* cookie_buffer,
    PRUint32& buffer_size) {
  if ((!url) || (!cookie_buffer)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (!plugin_instance_)
    return NS_ERROR_FAILURE;

  WebPlugin* webplugin = plugin_instance_->webplugin();
  if (!webplugin)
    return NS_ERROR_FAILURE;

  // Bypass third-party cookie blocking by using the url as the policy_url.
  GURL cookies_url((std::string(url)));
  std::string cookies = webplugin->GetCookies(cookies_url, cookies_url);

  if (cookies.empty())
    return NS_ERROR_FAILURE;

  if(cookies.length() >= buffer_size)
    return NS_ERROR_FAILURE;

  strncpy(static_cast<char*>(cookie_buffer),
          cookies.c_str(),
          cookies.length() + 1);

  buffer_size = cookies.length();
  return NS_OK;
}

NS_IMETHODIMP MozillaExtensionApi::SetCookie(
    const char* url,
    const void* cookie_buffer,
    PRUint32 buffer_size){
  if ((!url) || (!cookie_buffer) || (!buffer_size)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (!plugin_instance_)
    return NS_ERROR_FAILURE;

  WebPlugin* webplugin = plugin_instance_->webplugin();
  if (!webplugin)
    return NS_ERROR_FAILURE;

  std::string cookie(static_cast<const char*>(cookie_buffer),
                     buffer_size);
  GURL cookies_url((std::string(url)));
  webplugin->SetCookie(cookies_url,
                       cookies_url,
                       cookie);
  return NS_OK;
}

} // namespace NPAPI

<|endoftext|>


<commit_before>//===--- OperatorPrecedence.cpp ---------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines and computes precedence levels for binary/ternary operators.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/OperatorPrecedence.h"

namespace clang {

prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator,
                               bool CPlusPlus11) {
  switch (Kind) {
  case tok::greater:
    // C++ [temp.names]p3:
    //   [...] When parsing a template-argument-list, the first
    //   non-nested > is taken as the ending delimiter rather than a
    //   greater-than operator. [...]
    if (GreaterThanIsOperator)
      return prec::Relational;
    return prec::Unknown;

  case tok::greatergreater:
    // C++0x [temp.names]p3:
    //
    //   [...] Similarly, the first non-nested >> is treated as two
    //   consecutive but distinct > tokens, the first of which is
    //   taken as the end of the template-argument-list and completes
    //   the template-id. [...]
    if (GreaterThanIsOperator || !CPlusPlus11)
      return prec::Shift;
    return prec::Unknown;

  default:                        return prec::Unknown;
  case tok::comma:                return prec::Comma;
  case tok::equal:
  case tok::starequal:
  case tok::slashequal:
  case tok::percentequal:
  case tok::plusequal:
  case tok::minusequal:
  case tok::lesslessequal:
  case tok::greatergreaterequal:
  case tok::ampequal:
  case tok::caretequal:
  case tok::pipeequal:            return prec::Assignment;
  case tok::question:             return prec::Conditional;
  case tok::pipepipe:             return prec::LogicalOr;
  case tok::ampamp:               return prec::LogicalAnd;
  case tok::pipe:                 return prec::InclusiveOr;
  case tok::caret:                return prec::ExclusiveOr;
  case tok::amp:                  return prec::And;
  case tok::exclaimequal:
  case tok::equalequal:           return prec::Equality;
  case tok::lessequal:
  case tok::less:
  case tok::greaterequal:         return prec::Relational;
  case tok::lessless:             return prec::Shift;
  case tok::plus:
  case tok::minus:                return prec::Additive;
  case tok::percent:
  case tok::slash:
  case tok::star:                 return prec::Multiplicative;
  case tok::periodstar:
  case tok::arrowstar:            return prec::PointerToMember;
  }
}

}  // namespace clang
<commit_msg>Replace C++0x in a comment with C++11<commit_after>//===--- OperatorPrecedence.cpp ---------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines and computes precedence levels for binary/ternary operators.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/OperatorPrecedence.h"

namespace clang {

prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator,
                               bool CPlusPlus11) {
  switch (Kind) {
  case tok::greater:
    // C++ [temp.names]p3:
    //   [...] When parsing a template-argument-list, the first
    //   non-nested > is taken as the ending delimiter rather than a
    //   greater-than operator. [...]
    if (GreaterThanIsOperator)
      return prec::Relational;
    return prec::Unknown;

  case tok::greatergreater:
    // C++11 [temp.names]p3:
    //
    //   [...] Similarly, the first non-nested >> is treated as two
    //   consecutive but distinct > tokens, the first of which is
    //   taken as the end of the template-argument-list and completes
    //   the template-id. [...]
    if (GreaterThanIsOperator || !CPlusPlus11)
      return prec::Shift;
    return prec::Unknown;

  default:                        return prec::Unknown;
  case tok::comma:                return prec::Comma;
  case tok::equal:
  case tok::starequal:
  case tok::slashequal:
  case tok::percentequal:
  case tok::plusequal:
  case tok::minusequal:
  case tok::lesslessequal:
  case tok::greatergreaterequal:
  case tok::ampequal:
  case tok::caretequal:
  case tok::pipeequal:            return prec::Assignment;
  case tok::question:             return prec::Conditional;
  case tok::pipepipe:             return prec::LogicalOr;
  case tok::ampamp:               return prec::LogicalAnd;
  case tok::pipe:                 return prec::InclusiveOr;
  case tok::caret:                return prec::ExclusiveOr;
  case tok::amp:                  return prec::And;
  case tok::exclaimequal:
  case tok::equalequal:           return prec::Equality;
  case tok::lessequal:
  case tok::less:
  case tok::greaterequal:         return prec::Relational;
  case tok::lessless:             return prec::Shift;
  case tok::plus:
  case tok::minus:                return prec::Additive;
  case tok::percent:
  case tok::slash:
  case tok::star:                 return prec::Multiplicative;
  case tok::periodstar:
  case tok::arrowstar:            return prec::PointerToMember;
  }
}

}  // namespace clang
<|endoftext|>


<commit_before>#include <stingraykit/VariantMultidispatch.h>
#include <stingraykit/variant.h>

#include <gmock/gmock-matchers.h>

using namespace stingray;

using testing::Pair;

namespace
{

	struct Visitor : static_visitor<std::pair<std::string, std::string>>
	{
		template < typename T1, typename T2 >
		std::pair<std::string, std::string> operator () (const T1& p1, const T2& p2) const
		{ return std::make_pair(ToString(p1), ToString(p2)); }
	};

	struct SVisitor : public static_visitor<int>
	{
		int operator () (const std::string&) const { return 0; }
		int operator () (int) const { return 1; }
	};

	template < size_t Index >
	class StringHolder
	{
	private:
		std::string	_str;

	public:
		StringHolder() : _str(ToString(Index)) { }

		const std::string& GetStr() const { return _str; }
	};

	struct StringHolderVisitor : public static_visitor<const std::string&>
	{
		template < typename StringHolder_ >
		const std::string& operator () (const StringHolder_& holder) const { return holder.GetStr(); }
	};

}

TEST(VariantTest, Variant)
{
	using VType = variant<TypeList<int, std::string>>;
	VType v_default;
	VType v_int((int)42);
	VType v_string(std::string("1234"));

	ASSERT_TRUE(v_int.get_ptr<int>());
	ASSERT_TRUE(!v_int.get_ptr<std::string>());
	ASSERT_EQ(v_int.get<int>(), 42);
	ASSERT_EQ(v_int.which(), 0U);
	ASSERT_ANY_THROW(v_int.get<std::string>());

	ASSERT_TRUE(v_string.get_ptr<std::string>());
	ASSERT_TRUE(!v_string.get_ptr<int>());
	ASSERT_EQ(v_string.get<std::string>(), "1234");
	ASSERT_EQ(v_string.which(), 1U);
	ASSERT_ANY_THROW(v_string.get<int>());

	VType v_int_copy(v_int);
	ASSERT_TRUE(v_int_copy.get_ptr<int>());
	ASSERT_TRUE(!v_int_copy.get_ptr<std::string>());
	ASSERT_EQ(v_int_copy.get<int>(), 42);
	ASSERT_EQ(v_int_copy.which(), 0U);
	ASSERT_ANY_THROW(v_int_copy.get<std::string>());

	VType v_string_move(std::move(v_string));
	ASSERT_TRUE(v_string.get_ptr<std::string>());
	ASSERT_TRUE(v_string.get<std::string>().empty());
	ASSERT_TRUE(v_string_move.get_ptr<std::string>());
	ASSERT_EQ(v_string_move.get<std::string>(), "1234");

	VType v_emplace;
	ASSERT_TRUE(v_emplace.get_ptr<int>());
	v_emplace.emplace<std::string>("xxx", 1);
	ASSERT_TRUE(v_emplace.get_ptr<std::string>());
	ASSERT_EQ(v_emplace.get<std::string>(), "x");

	using VEmpty = variant<TypeList<EmptyType, int, std::string>>;
	VEmpty v_empty;
	ASSERT_TRUE(v_empty.empty());
	v_empty.emplace<int>(42);
	ASSERT_TRUE(v_empty.get_ptr<int>());
	ASSERT_EQ(v_empty.get<int>(), 42);
}

TEST(VariantTest, VisitorApplier)
{
	using VType = variant<TypeList<int, std::string>>;

	std::vector<VType> v;
	v.push_back(VType(std::string("1234")));
	v.push_back(VType(42));
	v.push_back(VType(0));

	std::vector<int> r;
	std::transform(v.begin(), v.end(), std::back_inserter(r), make_visitor_applier(SVisitor()));

	int seq[] = { 0, 1, 1 };
	ASSERT_TRUE(std::equal(r.begin(), r.end(), std::begin(seq), std::end(seq)));
}

TEST(VariantTest, VisitorApplierReturnRef)
{
	variant<TypeList<StringHolder<0>, StringHolder<3>, StringHolder<2>, StringHolder<5>>> var;

	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<0>>().GetStr());
	var = StringHolder<2>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<2>>().GetStr());
	var = StringHolder<5>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<5>>().GetStr());
	var = StringHolder<3>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<3>>().GetStr());

}

TEST(VariantTest, Multidispatch)
{
	using Variant1Type = variant<TypeList<int, std::string>>;
	using Variant2Type = variant<TypeList<char, double>>;

	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(1), Variant2Type('z')), Pair("1", "z"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(std::string("test")), Variant2Type(3.14)), Pair("test", "3.14"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(1), Variant2Type(3.14)), Pair("1", "3.14"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(std::string("test")), Variant2Type('z')), Pair("test", "z"));
}
<commit_msg>VariantTest: use MatchRange<commit_after>#include <stingraykit/VariantMultidispatch.h>
#include <stingraykit/variant.h>

#include <unittests/RangeMatcher.h>

using namespace stingray;

using testing::ElementsAre;
using testing::Pair;

namespace
{

	struct Visitor : static_visitor<std::pair<std::string, std::string>>
	{
		template < typename T1, typename T2 >
		std::pair<std::string, std::string> operator () (const T1& p1, const T2& p2) const
		{ return std::make_pair(ToString(p1), ToString(p2)); }
	};

	struct SVisitor : public static_visitor<int>
	{
		int operator () (const std::string&) const { return 0; }
		int operator () (int) const { return 1; }
	};

	template < size_t Index >
	class StringHolder
	{
	private:
		std::string	_str;

	public:
		StringHolder() : _str(ToString(Index)) { }

		const std::string& GetStr() const { return _str; }
	};

	struct StringHolderVisitor : public static_visitor<const std::string&>
	{
		template < typename StringHolder_ >
		const std::string& operator () (const StringHolder_& holder) const { return holder.GetStr(); }
	};

}

TEST(VariantTest, Variant)
{
	using VType = variant<TypeList<int, std::string>>;
	VType v_default;
	VType v_int((int)42);
	VType v_string(std::string("1234"));

	ASSERT_TRUE(v_int.get_ptr<int>());
	ASSERT_TRUE(!v_int.get_ptr<std::string>());
	ASSERT_EQ(v_int.get<int>(), 42);
	ASSERT_EQ(v_int.which(), 0U);
	ASSERT_ANY_THROW(v_int.get<std::string>());

	ASSERT_TRUE(v_string.get_ptr<std::string>());
	ASSERT_TRUE(!v_string.get_ptr<int>());
	ASSERT_EQ(v_string.get<std::string>(), "1234");
	ASSERT_EQ(v_string.which(), 1U);
	ASSERT_ANY_THROW(v_string.get<int>());

	VType v_int_copy(v_int);
	ASSERT_TRUE(v_int_copy.get_ptr<int>());
	ASSERT_TRUE(!v_int_copy.get_ptr<std::string>());
	ASSERT_EQ(v_int_copy.get<int>(), 42);
	ASSERT_EQ(v_int_copy.which(), 0U);
	ASSERT_ANY_THROW(v_int_copy.get<std::string>());

	VType v_string_move(std::move(v_string));
	ASSERT_TRUE(v_string.get_ptr<std::string>());
	ASSERT_TRUE(v_string.get<std::string>().empty());
	ASSERT_TRUE(v_string_move.get_ptr<std::string>());
	ASSERT_EQ(v_string_move.get<std::string>(), "1234");

	VType v_emplace;
	ASSERT_TRUE(v_emplace.get_ptr<int>());
	v_emplace.emplace<std::string>("xxx", 1);
	ASSERT_TRUE(v_emplace.get_ptr<std::string>());
	ASSERT_EQ(v_emplace.get<std::string>(), "x");

	using VEmpty = variant<TypeList<EmptyType, int, std::string>>;
	VEmpty v_empty;
	ASSERT_TRUE(v_empty.empty());
	v_empty.emplace<int>(42);
	ASSERT_TRUE(v_empty.get_ptr<int>());
	ASSERT_EQ(v_empty.get<int>(), 42);
}

TEST(VariantTest, VisitorApplier)
{
	using VType = variant<TypeList<int, std::string>>;
	const std::vector<VType> v{ std::string("1234"), 42, 0 };

	ASSERT_THAT(ToRange(v) | Transform(make_visitor_applier(SVisitor())), MatchRange(ElementsAre(0, 1, 1)));
}

TEST(VariantTest, VisitorApplierReturnRef)
{
	variant<TypeList<StringHolder<0>, StringHolder<3>, StringHolder<2>, StringHolder<5>>> var;

	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<0>>().GetStr());
	var = StringHolder<2>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<2>>().GetStr());
	var = StringHolder<5>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<5>>().GetStr());
	var = StringHolder<3>();
	ASSERT_EQ(&apply_visitor(StringHolderVisitor(), var), &var.get<StringHolder<3>>().GetStr());

}

TEST(VariantTest, Multidispatch)
{
	using Variant1Type = variant<TypeList<int, std::string>>;
	using Variant2Type = variant<TypeList<char, double>>;

	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(1), Variant2Type('z')), Pair("1", "z"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(std::string("test")), Variant2Type(3.14)), Pair("test", "3.14"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(1), Variant2Type(3.14)), Pair("1", "3.14"));
	ASSERT_THAT(Multidispatch(Visitor(), Variant1Type(std::string("test")), Variant2Type('z')), Pair("test", "z"));
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "NonlinearEigenSystem.h"

// MOOSE includes
#include "DirichletBC.h"
#include "EigenProblem.h"
#include "IntegratedBC.h"
#include "KernelBase.h"
#include "NodalBC.h"
#include "TimeIntegrator.h"

// libmesh includes
#include "libmesh/eigen_system.h"
#include "libmesh/libmesh_config.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/sparse_matrix.h"

#if LIBMESH_HAVE_SLEPC

namespace Moose
{

void
assemble_matrix(EquationSystems & es, const std::string & system_name)
{
  EigenProblem * p = es.parameters.get<EigenProblem *>("_eigen_problem");
  EigenSystem & eigen_system = es.get_system<EigenSystem>(system_name);

  p->computeJacobian(
      *eigen_system.current_local_solution.get(), *eigen_system.matrix_A, Moose::KT_NONEIGEN);

  if (eigen_system.generalized())
  {
    if (eigen_system.matrix_B)
      p->computeJacobian(
          *eigen_system.current_local_solution.get(), *eigen_system.matrix_B, Moose::KT_EIGEN);
    else
      mooseError("It is a generalized eigenvalue problem but matrix B is empty\n");
  }
}
}

NonlinearEigenSystem::NonlinearEigenSystem(EigenProblem & eigen_problem, const std::string & name)
  : NonlinearSystemBase(
        eigen_problem, eigen_problem.es().add_system<TransientEigenSystem>(name), name),
    _transient_sys(eigen_problem.es().get_system<TransientEigenSystem>(name)),
    _n_eigen_pairs_required(eigen_problem.getNEigenPairsRequired())
{
  sys().attach_assemble_function(Moose::assemble_matrix);
}

void
NonlinearEigenSystem::solve()
{
  // Clear the iteration counters
  _current_l_its.clear();
  _current_nl_its = 0;
  // Initialize the solution vector using a predictor and known values from nodal bcs
  setInitialSolution();
  _time_integrator->solve();
  _time_integrator->postSolve();

  // store eigenvalues
  unsigned int n_converged_eigenvalues = getNumConvergedEigenvalues();

  if (_n_eigen_pairs_required < n_converged_eigenvalues)
    n_converged_eigenvalues = _n_eigen_pairs_required;

  _eigen_values.resize(n_converged_eigenvalues);
  for (unsigned int n = 0; n < n_converged_eigenvalues; n++)
    _eigen_values[n] = getNthConvergedEigenvalue(n);
}

void
NonlinearEigenSystem::stopSolve()
{
  mooseError("did not implement yet \n");
}

void
NonlinearEigenSystem::setupFiniteDifferencedPreconditioner()
{
  mooseError("did not implement yet \n");
}

bool
NonlinearEigenSystem::converged()
{
  return _transient_sys.get_n_converged();
}

unsigned int
NonlinearEigenSystem::getCurrentNonlinearIterationNumber()
{
  mooseError("did not implement yet \n");
  return 0;
}

NumericVector<Number> &
NonlinearEigenSystem::RHS()
{
  mooseError("did not implement yet \n");
  // return NULL;
}

NonlinearSolver<Number> *
NonlinearEigenSystem::nonlinearSolver()
{
  mooseError("did not implement yet \n");
  return NULL;
}

void
NonlinearEigenSystem::addEigenKernels(std::shared_ptr<KernelBase> kernel, THREAD_ID tid)
{
  if (kernel->isEigenKernel())
    _eigen_kernels.addObject(kernel, tid);
  else
    _non_eigen_kernels.addObject(kernel, tid);
}

void
NonlinearEigenSystem::checkIntegrity()
{
  if (_integrated_bcs.hasActiveObjects())
    mooseError("Can't set an inhomogeneous integrated boundary condition for eigenvalue problems.");

  if (_nodal_bcs.hasActiveObjects())
  {
    const auto & nodal_bcs = _nodal_bcs.getActiveObjects();
    for (const auto & nodal_bc : nodal_bcs)
    {
      std::shared_ptr<DirichletBC> nbc = std::dynamic_pointer_cast<DirichletBC>(nodal_bc);
      if (nbc && nbc->getParam<Real>("value"))
        mooseError(
            "Can't set an inhomogeneous Dirichlet boundary condition for eigenvalue problems.");
      else if (!nbc)
        mooseError("Invalid NodalBC for eigenvalue problems, please use homogeneous Dirichlet.");
    }
  }
}

const std::pair<Real, Real>
NonlinearEigenSystem::getNthConvergedEigenvalue(dof_id_type n)
{
  unsigned int n_converged_eigenvalues = getNumConvergedEigenvalues();
  if (n >= n_converged_eigenvalues)
    mooseError(n, " not in [0, ", n_converged_eigenvalues, ")");
  return _transient_sys.get_eigenpair(n);
}

#else

NonlinearEigenSystem::NonlinearEigenSystem(EigenProblem & eigen_problem,
                                           const std::string & /*name*/)
  : libMesh::ParallelObject(eigen_problem)
{
  mooseError("Need to install SLEPc to solve eigenvalue problems, please reconfigure libMesh\n");
}

#endif /* LIBMESH_HAVE_SLEPC */
<commit_msg>Fix NonlinearEigenSystem for steady problems<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "NonlinearEigenSystem.h"

// MOOSE includes
#include "DirichletBC.h"
#include "EigenProblem.h"
#include "IntegratedBC.h"
#include "KernelBase.h"
#include "NodalBC.h"
#include "TimeIntegrator.h"

// libmesh includes
#include "libmesh/eigen_system.h"
#include "libmesh/libmesh_config.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/sparse_matrix.h"

#if LIBMESH_HAVE_SLEPC

namespace Moose
{

void
assemble_matrix(EquationSystems & es, const std::string & system_name)
{
  EigenProblem * p = es.parameters.get<EigenProblem *>("_eigen_problem");
  EigenSystem & eigen_system = es.get_system<EigenSystem>(system_name);

  p->computeJacobian(
      *eigen_system.current_local_solution.get(), *eigen_system.matrix_A, Moose::KT_NONEIGEN);

  if (eigen_system.generalized())
  {
    if (eigen_system.matrix_B)
      p->computeJacobian(
          *eigen_system.current_local_solution.get(), *eigen_system.matrix_B, Moose::KT_EIGEN);
    else
      mooseError("It is a generalized eigenvalue problem but matrix B is empty\n");
  }
}
}

NonlinearEigenSystem::NonlinearEigenSystem(EigenProblem & eigen_problem, const std::string & name)
  : NonlinearSystemBase(
        eigen_problem, eigen_problem.es().add_system<TransientEigenSystem>(name), name),
    _transient_sys(eigen_problem.es().get_system<TransientEigenSystem>(name)),
    _n_eigen_pairs_required(eigen_problem.getNEigenPairsRequired())
{
  sys().attach_assemble_function(Moose::assemble_matrix);
}

void
NonlinearEigenSystem::solve()
{
  // Clear the iteration counters
  _current_l_its.clear();
  _current_nl_its = 0;
  // Initialize the solution vector using a predictor and known values from nodal bcs
  setInitialSolution();

  // Solve the transient problem if we have a time integrator; the
  // steady problem if not.
  if (_time_integrator)
  {
    _time_integrator->solve();
    _time_integrator->postSolve();
  }
  else
    system().solve();

  // store eigenvalues
  unsigned int n_converged_eigenvalues = getNumConvergedEigenvalues();

  if (_n_eigen_pairs_required < n_converged_eigenvalues)
    n_converged_eigenvalues = _n_eigen_pairs_required;

  _eigen_values.resize(n_converged_eigenvalues);
  for (unsigned int n = 0; n < n_converged_eigenvalues; n++)
    _eigen_values[n] = getNthConvergedEigenvalue(n);
}

void
NonlinearEigenSystem::stopSolve()
{
  mooseError("did not implement yet \n");
}

void
NonlinearEigenSystem::setupFiniteDifferencedPreconditioner()
{
  mooseError("did not implement yet \n");
}

bool
NonlinearEigenSystem::converged()
{
  return _transient_sys.get_n_converged();
}

unsigned int
NonlinearEigenSystem::getCurrentNonlinearIterationNumber()
{
  mooseError("did not implement yet \n");
  return 0;
}

NumericVector<Number> &
NonlinearEigenSystem::RHS()
{
  mooseError("did not implement yet \n");
  // return NULL;
}

NonlinearSolver<Number> *
NonlinearEigenSystem::nonlinearSolver()
{
  mooseError("did not implement yet \n");
  return NULL;
}

void
NonlinearEigenSystem::addEigenKernels(std::shared_ptr<KernelBase> kernel, THREAD_ID tid)
{
  if (kernel->isEigenKernel())
    _eigen_kernels.addObject(kernel, tid);
  else
    _non_eigen_kernels.addObject(kernel, tid);
}

void
NonlinearEigenSystem::checkIntegrity()
{
  if (_integrated_bcs.hasActiveObjects())
    mooseError("Can't set an inhomogeneous integrated boundary condition for eigenvalue problems.");

  if (_nodal_bcs.hasActiveObjects())
  {
    const auto & nodal_bcs = _nodal_bcs.getActiveObjects();
    for (const auto & nodal_bc : nodal_bcs)
    {
      std::shared_ptr<DirichletBC> nbc = std::dynamic_pointer_cast<DirichletBC>(nodal_bc);
      if (nbc && nbc->getParam<Real>("value"))
        mooseError(
            "Can't set an inhomogeneous Dirichlet boundary condition for eigenvalue problems.");
      else if (!nbc)
        mooseError("Invalid NodalBC for eigenvalue problems, please use homogeneous Dirichlet.");
    }
  }
}

const std::pair<Real, Real>
NonlinearEigenSystem::getNthConvergedEigenvalue(dof_id_type n)
{
  unsigned int n_converged_eigenvalues = getNumConvergedEigenvalues();
  if (n >= n_converged_eigenvalues)
    mooseError(n, " not in [0, ", n_converged_eigenvalues, ")");
  return _transient_sys.get_eigenpair(n);
}

#else

NonlinearEigenSystem::NonlinearEigenSystem(EigenProblem & eigen_problem,
                                           const std::string & /*name*/)
  : libMesh::ParallelObject(eigen_problem)
{
  mooseError("Need to install SLEPc to solve eigenvalue problems, please reconfigure libMesh\n");
}

#endif /* LIBMESH_HAVE_SLEPC */
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = L_cuserid;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	std::string username(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}
<commit_msg>Use test fixture in GetUserName unit tests<commit_after>#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

class GetUserNameTest : public ::testing::Test {
protected:
	DWORD lpnSize;
	std::vector<WCHAR_T> lpBuffer;
	BOOL result;
	std::string userName;

	GetUserNameTest(): userName(std::string(getlogin())) {}

	void GetUserNameWithSize(DWORD size) {
		lpnSize = size;
		// allocate a WCHAR_T buffer to receive username
		lpBuffer.assign(lpnSize, '\0');
		result = GetUserName(&lpBuffer[0], &lpnSize);
	}
};

TEST_F(GetUserNameTest, NormalUse) {
	GetUserNameWithSize(L_cuserid);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(userName.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(userName, output);
}
<|endoftext|>


<commit_before>#define CURL_STATICLIB 1
#include <URL.h>
#include <curl/curl.h>
#include <Utils.h>
#include <map>
#include <string>

#ifdef HX_WINDOWS
#include <stdio.h>
#define snprintf _snprintf
#endif

/**
 * TODO:
 * HTTP redirects
 * HTTP POST method.
 */

namespace nme
{

static std::string sCACertFile("");
static CURLM *sCurlM = 0;
static int sRunning = 0;
static int sLoaders = 0;

typedef std::map<CURL *,class CURLLoader *> CurlMap;
typedef std::vector<class CURLLoader *> CurlList;
void processMultiMessages();

CurlMap *sCurlMap = 0;
CurlList *sCurlList = 0;

enum { MAX_ACTIVE = 64 };

class CURLLoader : public URLLoader
{
public:
	CURL *mHandle;
	int mBytesLoaded;
	int mBytesTotal;
	URLState mState;
	int mHttpCode;
	char mErrorBuf[CURL_ERROR_SIZE];
	QuickVec<unsigned char> mBytes;

   size_t         mBufferRemaining;
   unsigned char *mBufferPos;
   unsigned char *mPutBuffer;

  struct curl_slist *headerlist;

	CURLLoader(URLRequest &r)
	{
		mState = urlInit;
		if (!sCurlM)
			sCurlM = curl_multi_init();
		mBytesTotal = -1;
		mBytesLoaded = 0;
		mHttpCode = 0;
		sLoaders++;
		mHandle = curl_easy_init();
		if (!sCurlMap)
			sCurlMap = new CurlMap;

      mBufferRemaining = 0;
      mPutBuffer = 0;
      mBufferPos = 0;
    headerlist = NULL;

		curl_easy_setopt(mHandle, CURLOPT_URL, r.url);

      /* send all data to this function  */
      curl_easy_setopt(mHandle, CURLOPT_WRITEFUNCTION, staticOnData);
      curl_easy_setopt(mHandle, CURLOPT_WRITEDATA, (void *)this);
		curl_easy_setopt(mHandle, CURLOPT_NOPROGRESS, 0);
      if (r.authType!=0)
      {
         curl_easy_setopt(mHandle, CURLOPT_HTTPAUTH, r.authType);
         if (r.passwd && r.passwd[0])
            curl_easy_setopt(mHandle, CURLOPT_USERPWD, r.passwd);
      }
      curl_easy_setopt(mHandle, CURLOPT_PROGRESSFUNCTION, staticOnProgress);
      curl_easy_setopt(mHandle, CURLOPT_PROGRESSDATA, (void *)this);
      curl_easy_setopt(mHandle, CURLOPT_ERRORBUFFER, mErrorBuf );
      if (r.debug)
         curl_easy_setopt(mHandle, CURLOPT_VERBOSE, 1);
      curl_easy_setopt( mHandle, CURLOPT_COOKIEFILE, "" );
      if (r.cookies && r.cookies[0])
         curl_easy_setopt( mHandle, CURLOPT_COOKIE, r.cookies );
      if (sCACertFile.empty())
         curl_easy_setopt(mHandle, CURLOPT_SSL_VERIFYPEER, false);
      else
         curl_easy_setopt(mHandle, CURLOPT_CAINFO, sCACertFile.c_str());

      if (r.method)
      {
        if (!strcmp(r.method,"POST"))
        {
          curl_easy_setopt(mHandle, CURLOPT_POST, true);

          if (r.postData.Ok())
          {
            curl_easy_setopt(mHandle, CURLOPT_POSTFIELDSIZE, r.postData.Size());
            curl_easy_setopt(mHandle, CURLOPT_COPYPOSTFIELDS, r.postData.Bytes());
          }
        }
        else if (!strcmp(r.method,"PUT"))
        {
          // The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
          curl_easy_setopt(mHandle, CURLOPT_PUT, true);

          curl_easy_setopt(mHandle, CURLOPT_UPLOAD, 1);
          if (r.postData.Ok())
            SetPutBuffer(r.postData.Bytes(),r.postData.Size());
        }
        else if (!strcmp(r.method,"GET"))
        {
          // GET is the default, so this is not necessary but here for completeness.
          curl_easy_setopt(mHandle, CURLOPT_HTTPGET, true);
        }
        else if (!strcmp(r.method,"DELETE"))
        {
          curl_easy_setopt(mHandle, CURLOPT_CUSTOMREQUEST, r.method);
        }
        else
        {
          // unsupported method !!
        }
      }

      if (r.contentType)
      {
        std::vector<char> buffer;
        buffer.resize(512);
        snprintf(&buffer[0], buffer.size(), "Content-Type: %s", r.contentType);
        headerlist = curl_slist_append(headerlist, &buffer[0]);

      }
      headerlist = curl_slist_append(headerlist, "Expect:");
      curl_easy_setopt(mHandle, CURLOPT_HTTPHEADER, headerlist);

      mErrorBuf[0] = '\0';

      /* some servers don't like requests that are made without a user-agent
         field, so we provide one */
      curl_easy_setopt(mHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

		  mState = urlLoading;

      if (sCurlMap->size()<MAX_ACTIVE)
      {
         StartProcessing();
      }
      else
      {
         if (sCurlList==0)
           sCurlList = new CurlList;
         sCurlList->push_back(this);
      }
   }

   size_t ReadFunc( void *ptr, size_t size, size_t nmemb)
   {
      size_t bytes = size * nmemb;
      if (mBufferRemaining<=bytes)
         bytes = mBufferRemaining;

      memcpy(ptr,mBufferPos,bytes);
      mBufferPos += bytes;
      mBufferRemaining -= bytes;

      return bytes;
   }

   static size_t SReadFunc( void *ptr, size_t size, size_t nmemb, void *userdata)
   {
      return ((CURLLoader *)userdata)->ReadFunc(ptr,size,nmemb);
   }

   void SetPutBuffer(const unsigned char *inBuffer, size_t inLen)
   {
      mPutBuffer = new unsigned char[inLen];
      mBufferRemaining = 0;
      mBufferPos = mPutBuffer;
      memcpy(mPutBuffer,inBuffer,inLen);
      curl_easy_setopt(mHandle, CURLOPT_READFUNCTION, SReadFunc);
      curl_easy_setopt(mHandle, CURLOPT_INFILESIZE, inLen);
   }

   void StartProcessing()
   {
		(*sCurlMap)[mHandle] = this;
		int c1 = curl_multi_add_handle(sCurlM,mHandle);
		int result = curl_multi_perform(sCurlM, &sRunning);
      processMultiMessages();
	}

	~CURLLoader()
	{
      delete [] mPutBuffer;
		curl_easy_cleanup(mHandle);
		sLoaders--;
		if (sLoaders==0)
		{
			curl_multi_cleanup(sCurlM);
			sCurlM = 0;
		}
	}

	size_t onData( void *inBuffer, size_t inItemSize, size_t inItems)
	{
		size_t size = inItemSize*inItems;
		if (size>0)
		{
			int s = mBytes.size();
			mBytes.resize(s+size);
			memcpy(&mBytes[s],inBuffer,size);
		}
		return inItems;
	}

	int onProgress( double inBytesTotal, double inBytesDownloaded,
                    double inUploadTotal, double inBytesUploaded )
	{
		mBytesTotal = inBytesTotal;
		mBytesLoaded = inBytesDownloaded;
		return 0;
	}

	void setResult(CURLcode inResult)
	{
		sCurlMap->erase(mHandle);
		curl_multi_remove_handle(sCurlM,mHandle);
		mState = inResult==0 ? urlComplete : urlError;
	}

	static size_t staticOnData( void *inBuffer, size_t size, size_t inItems, void *userdata)
	{
		return ((CURLLoader *)userdata)->onData(inBuffer,size,inItems);
	}

	static size_t staticOnProgress(void* inCookie, double inBytesTotal, double inBytesDownloaded,
                    double inUploadTotal, double inBytesUploaded)

	{
		return ((CURLLoader *)inCookie)->onProgress(
			inBytesTotal,inBytesDownloaded,inUploadTotal,inBytesUploaded);
	}

   void getCookies( std::vector<std::string> &outCookies )
   {
      curl_slist *list = 0;
		if (CURLE_OK == curl_easy_getinfo(mHandle,CURLINFO_COOKIELIST,&list) && list)
      {
         curl_slist *item = list;
         while(item)
         {
            outCookies.push_back(item->data);
            item = item->next;
         }
         curl_slist_free_all(list);
      }
	}

	URLState getState()
	{
		long http_code = 0;
		int curl_code = curl_easy_getinfo(mHandle,CURLINFO_RESPONSE_CODE,&http_code);
		if (curl_code!=CURLE_OK)
			mState = urlError;
		else if (http_code>0)
		{
			// XXX : A HTTP code >= 400 should be an error. Handle this in URLLoader.hx for now.
			mHttpCode = http_code;
		}
		return mState;
	}

	int bytesLoaded() { return mBytesLoaded; }
	int bytesTotal() { return mBytesTotal; }

	virtual int getHttpCode() { return mHttpCode; }

	virtual const char *getErrorMessage() { return mErrorBuf; }
	virtual ByteArray releaseData()
	{
		if (mBytes.size())
		{
         return ByteArray(mBytes);
		}
		return ByteArray();
	}

};

void processMultiMessages()
{
		int remaining;
		CURLMsg *msg;
		while( (msg=curl_multi_info_read(sCurlM,&remaining) ) )
		{
			if (msg->msg==CURLMSG_DONE)
			{
				CurlMap::iterator i = sCurlMap->find(msg->easy_handle);
				if (i!=sCurlMap->end())
					i->second->setResult( msg->data.result );
			}
		}
}

bool URLLoader::processAll()
{
   bool added = false;
   do {
      added = false;
	   bool check = sRunning;
	   for(int go=0; go<10 && sRunning; go++)
	   {
		   int code = curl_multi_perform(sCurlM,&sRunning);
		   if (code!= CURLM_CALL_MULTI_PERFORM)
			   break;
	   }
	   if (check)
         processMultiMessages();

      while(sCurlMap && sCurlList && !sCurlList->empty() && sCurlMap->size()<MAX_ACTIVE )
      {
         CURLLoader *curl = (*sCurlList)[0];
         sCurlList->erase(sCurlList->begin());
         added = true;
         curl->StartProcessing();
      }

   } while(added);

   return sRunning || (sCurlList && sCurlList->size());
}

URLLoader *URLLoader::create(URLRequest &r)
{
	return new CURLLoader(r);
}

typedef int (*get_file_callback_func)(const char *filename, unsigned char **buf);
extern "C"
{
extern get_file_callback_func get_file_callback;
}

#if (defined(HX_MACOS) || defined(ANDROID) ) && defined(NME_CURL_SSL)
#define TRY_GET_FILE
#endif

#ifdef TRY_GET_FILE
static int sGetFile(const char *inFilename, unsigned char **outBuf)
{
   #ifdef ANDROID
   ByteArray bytes = AndroidGetAssetBytes(inFilename);
   #else
   ByteArray bytes = ByteArray::FromFile(inFilename);
   #endif

   ELOG("Loaded cert %s %d bytes.", inFilename, bytes.Size());
   if (bytes.Size()>0)
   {
      *outBuf = (unsigned char *)malloc(bytes.Size());
      memcpy(*outBuf,bytes.Bytes(),bytes.Size());
      return bytes.Size();
   }

   return -1;
}
#endif

void URLLoader::initialize(const char *inCACertFilePath)
{
  #ifdef HX_WINDOWS
  unsigned int flags = CURL_GLOBAL_WIN32;
  #else
  unsigned int flags = 0;
  #endif
  curl_global_init(flags | CURL_GLOBAL_SSL);
  sCACertFile = std::string(inCACertFilePath);

  #ifdef TRY_GET_FILE
  get_file_callback = sGetFile;
  #endif

  /* Set to 1 to print version information for libcurl. */
  if (!sCACertFile.empty())
  {
     FILE *f = fopen(sCACertFile.c_str(),"rb");
     bool loaded = f;
     if (f)
        fclose(f);
     ELOG("Open cert file: %s %s\n", sCACertFile.c_str(), loaded ? "Yes" : "NO!!" );
     #ifdef IPHONE
     if (!loaded)
     {
        sCACertFile = GetResourcePath() + gAssetBase + inCACertFilePath;
        FILE *f = fopen(sCACertFile.c_str(),"rb");
        loaded = f;
        if (f)
          fclose(f);
        ELOG("Open cert file: %s %s\n", sCACertFile.c_str(), loaded ? "Yes" : "NO!!" );
     }
     #endif
  }

  #if 0
  curl_version_info_data * info = curl_version_info(CURLVERSION_NOW);
  ELOG("SSL cert: %s\n", inCACertFilePath);
  ELOG("libcurl version: %s\n", info->version);
  ELOG("Support for SSL in libcurl: %d\n", (info->features) & CURL_VERSION_SSL);
  ELOG("Supported libcurl protocols: ");
  for (int i=0; info->protocols[i] != 0; i++) {
    ELOG(" protocol %d: %s",i,  info->protocols[i]);
  }
  #endif
}

}
<commit_msg>HTTP POST method<commit_after>#define CURL_STATICLIB 1
#include <URL.h>
#include <curl/curl.h>
#include <Utils.h>
#include <map>
#include <string>

#ifdef HX_WINDOWS
#include <stdio.h>
#define snprintf _snprintf
#endif

/**
 * TODO:
 * HTTP redirects
 */

namespace nme
{

static std::string sCACertFile("");
static CURLM *sCurlM = 0;
static int sRunning = 0;
static int sLoaders = 0;

typedef std::map<CURL *,class CURLLoader *> CurlMap;
typedef std::vector<class CURLLoader *> CurlList;
void processMultiMessages();

CurlMap *sCurlMap = 0;
CurlList *sCurlList = 0;

enum { MAX_ACTIVE = 64 };

class CURLLoader : public URLLoader
{
public:
	CURL *mHandle;
	int mBytesLoaded;
	int mBytesTotal;
	URLState mState;
	int mHttpCode;
	char mErrorBuf[CURL_ERROR_SIZE];
	QuickVec<unsigned char> mBytes;

  size_t         mBufferRemaining;
  unsigned char *mBufferPos;
  unsigned char *mPutBuffer;

  struct curl_slist *headerlist;

	CURLLoader(URLRequest &r)
	{
		mState = urlInit;
		if (!sCurlM)
			sCurlM = curl_multi_init();
		mBytesTotal = -1;
		mBytesLoaded = 0;
		mHttpCode = 0;
		sLoaders++;
		mHandle = curl_easy_init();
		if (!sCurlMap)
			sCurlMap = new CurlMap;

    mBufferRemaining = 0;
    mPutBuffer = 0;
    mBufferPos = 0;
    headerlist = NULL;

		curl_easy_setopt(mHandle, CURLOPT_URL, r.url);

    /* send all data to this function  */
    curl_easy_setopt(mHandle, CURLOPT_WRITEFUNCTION, staticOnData);
    curl_easy_setopt(mHandle, CURLOPT_WRITEDATA, (void *)this);
		curl_easy_setopt(mHandle, CURLOPT_NOPROGRESS, 0);
    if (r.authType!=0)
    {
      curl_easy_setopt(mHandle, CURLOPT_HTTPAUTH, r.authType);
      if (r.passwd && r.passwd[0])
        curl_easy_setopt(mHandle, CURLOPT_USERPWD, r.passwd);
    }
    curl_easy_setopt(mHandle, CURLOPT_PROGRESSFUNCTION, staticOnProgress);
    curl_easy_setopt(mHandle, CURLOPT_PROGRESSDATA, (void *)this);
    curl_easy_setopt(mHandle, CURLOPT_ERRORBUFFER, mErrorBuf );
    if (r.debug)
      curl_easy_setopt(mHandle, CURLOPT_VERBOSE, 1);
    curl_easy_setopt( mHandle, CURLOPT_COOKIEFILE, "" );
    if (r.cookies && r.cookies[0])
      curl_easy_setopt( mHandle, CURLOPT_COOKIE, r.cookies );
    if (sCACertFile.empty())
      curl_easy_setopt(mHandle, CURLOPT_SSL_VERIFYPEER, false);
    else
      curl_easy_setopt(mHandle, CURLOPT_CAINFO, sCACertFile.c_str());

    if (r.method)
    {
      if (!strcmp(r.method,"POST"))
      {
        curl_easy_setopt(mHandle, CURLOPT_POST, true);

        if (r.postData.Ok())
        {
          curl_easy_setopt(mHandle, CURLOPT_POSTFIELDSIZE, r.postData.Size());
          curl_easy_setopt(mHandle, CURLOPT_COPYPOSTFIELDS, r.postData.Bytes());
        }
      }
      else if (!strcmp(r.method,"PUT"))
      {
        // The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
        curl_easy_setopt(mHandle, CURLOPT_PUT, true);

        curl_easy_setopt(mHandle, CURLOPT_UPLOAD, 1);
        if (r.postData.Ok())
          SetPutBuffer(r.postData.Bytes(),r.postData.Size());
      }
      else if (!strcmp(r.method,"GET"))
      {
        // GET is the default, so this is not necessary but here for completeness.
        curl_easy_setopt(mHandle, CURLOPT_HTTPGET, true);
      }
      else if (!strcmp(r.method,"DELETE"))
      {
        curl_easy_setopt(mHandle, CURLOPT_CUSTOMREQUEST, r.method);
      }
      else
      {
        // unsupported method !!
      }
    }

    if (r.contentType)
    {
      std::vector<char> buffer;
      buffer.resize(512);
      snprintf(&buffer[0], buffer.size(), "Content-Type: %s", r.contentType);
      headerlist = curl_slist_append(headerlist, &buffer[0]);
    }
    headerlist = curl_slist_append(headerlist, "Expect:");
    curl_easy_setopt(mHandle, CURLOPT_HTTPHEADER, headerlist);

    mErrorBuf[0] = '\0';

    /* some servers don't like requests that are made without a user-agent
      field, so we provide one */
    curl_easy_setopt(mHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

		mState = urlLoading;

    if (sCurlMap->size()<MAX_ACTIVE)
    {
      StartProcessing();
    }
    else
    {
      if (sCurlList==0)
        sCurlList = new CurlList;
      sCurlList->push_back(this);
    }
  }

  size_t ReadFunc( void *ptr, size_t size, size_t nmemb)
  {
    size_t bytes = size * nmemb;
    if (mBufferRemaining<=bytes)
      bytes = mBufferRemaining;

    memcpy(ptr,mBufferPos,bytes);
    mBufferPos += bytes;
    mBufferRemaining -= bytes;

    return bytes;
  }

  static size_t SReadFunc( void *ptr, size_t size, size_t nmemb, void *userdata)
  {
    return ((CURLLoader *)userdata)->ReadFunc(ptr,size,nmemb);
  }

  void SetPutBuffer(const unsigned char *inBuffer, size_t inLen)
  {
    mPutBuffer = new unsigned char[inLen];
    mBufferRemaining = 0;
    mBufferPos = mPutBuffer;
    memcpy(mPutBuffer,inBuffer,inLen);
    curl_easy_setopt(mHandle, CURLOPT_READFUNCTION, SReadFunc);
    curl_easy_setopt(mHandle, CURLOPT_INFILESIZE, inLen);
  }

  void StartProcessing()
  {
		(*sCurlMap)[mHandle] = this;
    //int c1 = curl_multi_add_handle(sCurlM,mHandle);
    curl_multi_add_handle(sCurlM,mHandle);
    //int result = curl_multi_perform(sCurlM, &sRunning);
    curl_multi_perform(sCurlM, &sRunning);
    processMultiMessages();
	}

	~CURLLoader()
	{
    delete [] mPutBuffer;
		curl_easy_cleanup(mHandle);
		sLoaders--;
		if (sLoaders==0)
		{
			curl_multi_cleanup(sCurlM);
			sCurlM = 0;
		}
	}

	size_t onData( void *inBuffer, size_t inItemSize, size_t inItems)
	{
		size_t size = inItemSize*inItems;
		if (size>0)
		{
			int s = mBytes.size();
			mBytes.resize(s+size);
			memcpy(&mBytes[s],inBuffer,size);
		}
		return inItems;
	}

	int onProgress( double inBytesTotal, double inBytesDownloaded,
                    double inUploadTotal, double inBytesUploaded )
	{
		mBytesTotal = inBytesTotal;
		mBytesLoaded = inBytesDownloaded;
		return 0;
	}

	void setResult(CURLcode inResult)
	{
		sCurlMap->erase(mHandle);
		curl_multi_remove_handle(sCurlM,mHandle);
		mState = inResult==0 ? urlComplete : urlError;
	}

	static size_t staticOnData( void *inBuffer, size_t size, size_t inItems, void *userdata)
	{
		return ((CURLLoader *)userdata)->onData(inBuffer,size,inItems);
	}

	static size_t staticOnProgress(void* inCookie, double inBytesTotal, double inBytesDownloaded,
                    double inUploadTotal, double inBytesUploaded)

	{
		return ((CURLLoader *)inCookie)->onProgress(
			inBytesTotal,inBytesDownloaded,inUploadTotal,inBytesUploaded);
	}

   void getCookies( std::vector<std::string> &outCookies )
   {
      curl_slist *list = 0;
		if (CURLE_OK == curl_easy_getinfo(mHandle,CURLINFO_COOKIELIST,&list) && list)
      {
         curl_slist *item = list;
         while(item)
         {
            outCookies.push_back(item->data);
            item = item->next;
         }
         curl_slist_free_all(list);
      }
	}

	URLState getState()
	{
		long http_code = 0;
		int curl_code = curl_easy_getinfo(mHandle,CURLINFO_RESPONSE_CODE,&http_code);
		if (curl_code != CURLE_OK)
			mState = urlError;
		else if (http_code>0)
		{
			// XXX : A HTTP code >= 400 should be an error. Handle this in URLLoader.hx for now.
			mHttpCode = http_code;
		}
		return mState;
	}

	int bytesLoaded() { return mBytesLoaded; }
	int bytesTotal() { return mBytesTotal; }

	virtual int getHttpCode() { return mHttpCode; }

	virtual const char *getErrorMessage() { return mErrorBuf; }
	virtual ByteArray releaseData()
	{
		if (mBytes.size())
		{
         return ByteArray(mBytes);
		}
		return ByteArray();
	}

};

void processMultiMessages()
{
		int remaining;
		CURLMsg *msg;
		while( (msg=curl_multi_info_read(sCurlM,&remaining) ) )
		{
			if (msg->msg==CURLMSG_DONE)
			{
				CurlMap::iterator i = sCurlMap->find(msg->easy_handle);
				if (i!=sCurlMap->end())
					i->second->setResult( msg->data.result );
			}
		}
}

bool URLLoader::processAll()
{
   bool added = false;
   do {
      added = false;
	   bool check = sRunning;
	   for(int go=0; go<10 && sRunning; go++)
	   {
		   int code = curl_multi_perform(sCurlM,&sRunning);
		   if (code!= CURLM_CALL_MULTI_PERFORM)
			   break;
	   }
	   if (check) {
         processMultiMessages();
      }
      while(sCurlMap && sCurlList && !sCurlList->empty() && sCurlMap->size()<MAX_ACTIVE )
      {
         CURLLoader *curl = (*sCurlList)[0];
         sCurlList->erase(sCurlList->begin());
         added = true;
         curl->StartProcessing();
      }

   } while(added);

   return sRunning || (sCurlList && sCurlList->size());
}

URLLoader *URLLoader::create(URLRequest &r)
{
	return new CURLLoader(r);
}

typedef int (*get_file_callback_func)(const char *filename, unsigned char **buf);
extern "C"
{
extern get_file_callback_func get_file_callback;
}

#if (defined(HX_MACOS) || defined(ANDROID) ) && defined(NME_CURL_SSL)
#define TRY_GET_FILE
#endif

#ifdef TRY_GET_FILE
static int sGetFile(const char *inFilename, unsigned char **outBuf)
{
   #ifdef ANDROID
   ByteArray bytes = AndroidGetAssetBytes(inFilename);
   #else
   ByteArray bytes = ByteArray::FromFile(inFilename);
   #endif

   ELOG("Loaded cert %s %d bytes.", inFilename, bytes.Size());
   if (bytes.Size()>0)
   {
      *outBuf = (unsigned char *)malloc(bytes.Size());
      memcpy(*outBuf,bytes.Bytes(),bytes.Size());
      return bytes.Size();
   }

   return -1;
}
#endif

void URLLoader::initialize(const char *inCACertFilePath)
{
  #ifdef HX_WINDOWS
  unsigned int flags = CURL_GLOBAL_WIN32;
  #else
  unsigned int flags = 0;
  #endif
  curl_global_init(flags | CURL_GLOBAL_SSL);
  sCACertFile = std::string(inCACertFilePath);

  #ifdef TRY_GET_FILE
  get_file_callback = sGetFile;
  #endif

  /* Set to 1 to print version information for libcurl. */
  if (!sCACertFile.empty())
  {
     FILE *f = fopen(sCACertFile.c_str(),"rb");
     bool loaded = f;
     if (f)
        fclose(f);
     ELOG("Open cert file: %s %s\n", sCACertFile.c_str(), loaded ? "Yes" : "NO!!" );
     #ifdef IPHONE
     if (!loaded)
     {
        sCACertFile = GetResourcePath() + gAssetBase + inCACertFilePath;
        FILE *f = fopen(sCACertFile.c_str(),"rb");
        loaded = f;
        if (f)
          fclose(f);
        ELOG("Open cert file: %s %s\n", sCACertFile.c_str(), loaded ? "Yes" : "NO!!" );
     }
     #endif
  }

  #if 0
  curl_version_info_data * info = curl_version_info(CURLVERSION_NOW);
  ELOG("SSL cert: %s\n", inCACertFilePath);
  ELOG("libcurl version: %s\n", info->version);
  ELOG("Support for SSL in libcurl: %d\n", (info->features) & CURL_VERSION_SSL);
  ELOG("Supported libcurl protocols: ");
  for (int i=0; info->protocols[i] != 0; i++) {
    ELOG(" protocol %d: %s",i,  info->protocols[i]);
  }
  #endif
}

}
<|endoftext|>


<commit_before>// @(#)root/base:$Name:  $:$Id: TAttLine.cxx,v 1.16 2007/01/15 22:08:28 rdm Exp $
// Author: Rene Brun   28/11/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TAttLine.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TVirtualX.h"
#include "TVirtualPadEditor.h"
#include "TColor.h"
#include <cmath>

ClassImp(TAttLine)

//______________________________________________________________________________
/* Begin_Html

Line Attributes class

This class is used (in general by secondary inheritance)
by many other classes (graphics, histograms). It holds all the line attributes.

Line attributes

Line attributes are:

Line Color.

Line Width.

Line Style.

Line Color

The line color is a color index (integer) pointing in the ROOT
color table. The following table shows the first 50 default colors.
End_Html
Begin_Macro(source)
{
   TCanvas *c = new TCanvas("c","Fill Area colors",0,0,500,200);
   c.DrawColorTable();
   return c;
}
End_Macro

Begin_Html

Line Width

The line width is expressed in pixel units.
The following picture shows the line widths from 1 to 10 pixels.
End_Html
Begin_Macro(source)
{
   TCanvas *Lw = new TCanvas("Lw","test",500,200);
   TText  t;
   t.SetTextAlign(32);
   t.SetTextSize(0.08);
   Int_t i=1;
   gStyle->SetLineStyleString(9,"400 20");
   for (float s=0.1; s<1.0 ; s+=0.092) {
      TLine *lh = new TLine(0.15,s,.85,s);
      lh->SetLineWidth(i);
      t.DrawText(0.1,s,Form("%d",i++));
      lh->Draw();
   }
   return Lw;
}
End_Macro

Begin_Html

Line Style

Line styles are identified via integer numbers. The four basic line styles
are:

   1 = solid
   2 = dash
   3 = dot-dot
   4 = dash-dot

Additional line styles can be defined using <tt>TStyle::SetLineStyleString</tt>.

Example:

   gStyle->SetLineStyleString(5,"20 12 4 12");
   gStyle->SetLineStyleString(6,"20 12 4 12 4 12 4 12");
   gStyle->SetLineStyleString(7,"20 20");
   gStyle->SetLineStyleString(8,"20 12 4 12 4 12");
   gStyle->SetLineStyleString(9,"80 20");

The following picture shows the first 10 line styles.
End_Html
Begin_Macro(source)
{
   TCanvas *Ls = new TCanvas("Ls","test",500,200);
   TText  t;
   t.SetTextAlign(32);
   t.SetTextSize(0.08);
   Int_t i=1;
   gStyle->SetLineStyleString(9,"400 20");
   for (float s=0.1; s<1.0 ; s+=0.092) {
      TLine *lh = new TLine(0.15,s,.85,s);
      lh->SetLineStyle(i);
      t.DrawText(0.1,s,Form("%d",i++));
      lh->Draw();
   }
   return Ls;
}
End_Macro */

//______________________________________________________________________________
TAttLine::TAttLine()
{
   // AttLine default constructor.

   if (!gStyle) return;
   fLineColor = gStyle->GetLineColor();
   fLineWidth = gStyle->GetLineWidth();
   fLineStyle = gStyle->GetLineStyle();
}

//______________________________________________________________________________
TAttLine::TAttLine(Color_t color, Style_t style, Width_t width)
{
   // AttLine normal constructor.
   // Line attributes are taking from the argument list
   //   color : must be one of the valid color index
   //   style : 1=solid, 2=dash, 3=dash-dot, 4=dot-dot. New styles can be
   //           defined using TStyle::SetLineStyleString.
   //   width : expressed in pixel units

   fLineColor = color;
   fLineWidth = width;
   fLineStyle = style;
}

//______________________________________________________________________________
TAttLine::~TAttLine()
{
   // AttLine destructor.
}

//______________________________________________________________________________
void TAttLine::Copy(TAttLine &attline) const
{
   // Copy this line attributes to a new TAttLine.

   attline.fLineColor  = fLineColor;
   attline.fLineStyle  = fLineStyle;
   attline.fLineWidth  = fLineWidth;
}

//______________________________________________________________________________
Int_t TAttLine::DistancetoLine(Int_t px, Int_t py, Double_t xp1, Double_t yp1, Double_t xp2, Double_t yp2 )
{
   // Compute distance from point px,py to a line.
   // Compute the closest distance of approach from point px,py to this line.
   // The distance is computed in pixels units.
   //
   // Algorithm:
   //
   //   A(x1,y1)         P                             B(x2,y2)
   //   -----------------+------------------------------
   //                    |
   //                    |
   //                    |
   //                    |
   //                   M(x,y)
   //
   // Let us call  a = distance AM     A=a**2
   //              b = distance BM     B=b**2
   //              c = distance AB     C=c**2
   //              d = distance PM     D=d**2
   //              u = distance AP     U=u**2
   //              v = distance BP     V=v**2     c = u + v
   //
   // D = A - U
   // D = B - V  = B -(c-u)**2
   //    ==> u = (A -B +C)/2c

   Double_t xl, xt, yl, yt;
   Double_t x     = px;
   Double_t y     = py;
   Double_t x1    = gPad->XtoAbsPixel(xp1);
   Double_t y1    = gPad->YtoAbsPixel(yp1);
   Double_t x2    = gPad->XtoAbsPixel(xp2);
   Double_t y2    = gPad->YtoAbsPixel(yp2);
   if (x1 < x2) {xl = x1; xt = x2;}
   else         {xl = x2; xt = x1;}
   if (y1 < y2) {yl = y1; yt = y2;}
   else         {yl = y2; yt = y1;}
   if (x < xl-2 || x> xt+2) return 9999;  //following algorithm only valid in the box
   if (y < yl-2 || y> yt+2) return 9999;  //surrounding the line
   Double_t xx1   = x  - x1;
   Double_t xx2   = x  - x2;
   Double_t x1x2  = x1 - x2;
   Double_t yy1   = y  - y1;
   Double_t yy2   = y  - y2;
   Double_t y1y2  = y1 - y2;
   Double_t a     = xx1*xx1   + yy1*yy1;
   Double_t b     = xx2*xx2   + yy2*yy2;
   Double_t c     = x1x2*x1x2 + y1y2*y1y2;
   if (c <= 0)  return 9999;
   Double_t v     = sqrt(c);
   Double_t u     = (a - b + c)/(2*v);
   Double_t d     = TMath::Abs(a - u*u);
   if (d < 0)   return 9999;

   return Int_t(sqrt(d) - 0.5*Double_t(fLineWidth));
}

//______________________________________________________________________________
void TAttLine::Modify()
{
   // Change current line attributes if necessary.

   if (!gPad) return;
   Int_t lineWidth = TMath::Abs(fLineWidth%100);
   if (!gPad->IsBatch()) {
      gVirtualX->SetLineColor(fLineColor);
      if (fLineStyle > 0 && fLineStyle < 30) gVirtualX->SetLineStyle(fLineStyle);
      else                                   gVirtualX->SetLineStyle(1);
      gVirtualX->SetLineWidth(lineWidth);
   }

   if (fLineStyle > 0 && fLineStyle < 30) gPad->SetAttLinePS(fLineColor,fLineStyle,lineWidth);
   else                                   gPad->SetAttLinePS(fLineColor,1,lineWidth);
}

//______________________________________________________________________________
void TAttLine::ResetAttLine(Option_t *)
{
   // Reset this line attributes to default values.

   fLineColor  = 1;
   fLineStyle  = 1;
   fLineWidth  = 1;
}

//______________________________________________________________________________
void TAttLine::SaveLineAttributes(ostream &out, const char *name, Int_t coldef, Int_t stydef, Int_t widdef)
{
   // Save line attributes as C++ statement(s) on output stream out.

   if (fLineColor != coldef) {
      if (fLineColor > 228) {
         TColor::SaveColor(out, fLineColor);
         out<<"   "<<name<<"->SetLineColor(ci);" << endl;
      } else
         out<<"   "<<name<<"->SetLineColor("<<fLineColor<<");"<<endl;
   }
   if (fLineStyle != stydef) {
      out<<"   "<<name<<"->SetLineStyle("<<fLineStyle<<");"<<endl;
   }
   if (fLineWidth != widdef) {
      out<<"   "<<name<<"->SetLineWidth("<<fLineWidth<<");"<<endl;
   }
}

//______________________________________________________________________________
void TAttLine::SetLineAttributes()
{
   // Invoke the DialogCanvas Line attributes.

   TVirtualPadEditor::UpdateLineAttributes(fLineColor,fLineStyle,fLineWidth);
}
<commit_msg>- Fix a typo in help text.<commit_after>// @(#)root/base:$Name:  $:$Id: TAttLine.cxx,v 1.17 2007/02/21 09:33:21 couet Exp $
// Author: Rene Brun   28/11/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TAttLine.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TVirtualX.h"
#include "TVirtualPadEditor.h"
#include "TColor.h"
#include <cmath>

ClassImp(TAttLine)

//______________________________________________________________________________
/* Begin_Html

Line Attributes class

This class is used (in general by secondary inheritance)
by many other classes (graphics, histograms). It holds all the line attributes.

Line attributes

Line attributes are:

Line Color.

Line Width.

Line Style.

Line Color

The line color is a color index (integer) pointing in the ROOT
color table. The following table shows the first 50 default colors.
End_Html
Begin_Macro(source)
{
   TCanvas *c = new TCanvas("c","Line colors",0,0,500,200);
   c.DrawColorTable();
   return c;
}
End_Macro

Begin_Html

Line Width

The line width is expressed in pixel units.
The following picture shows the line widths from 1 to 10 pixels.
End_Html
Begin_Macro(source)
{
   TCanvas *Lw = new TCanvas("Lw","test",500,200);
   TText  t;
   t.SetTextAlign(32);
   t.SetTextSize(0.08);
   Int_t i=1;
   gStyle->SetLineStyleString(9,"400 20");
   for (float s=0.1; s<1.0 ; s+=0.092) {
      TLine *lh = new TLine(0.15,s,.85,s);
      lh->SetLineWidth(i);
      t.DrawText(0.1,s,Form("%d",i++));
      lh->Draw();
   }
   return Lw;
}
End_Macro

Begin_Html

Line Style

Line styles are identified via integer numbers. The four basic line styles
are:

   1 = solid
   2 = dash
   3 = dot-dot
   4 = dash-dot

Additional line styles can be defined using <tt>TStyle::SetLineStyleString</tt>.

Example:

   gStyle->SetLineStyleString(5,"20 12 4 12");
   gStyle->SetLineStyleString(6,"20 12 4 12 4 12 4 12");
   gStyle->SetLineStyleString(7,"20 20");
   gStyle->SetLineStyleString(8,"20 12 4 12 4 12");
   gStyle->SetLineStyleString(9,"80 20");

The following picture shows the first 10 line styles.
End_Html
Begin_Macro(source)
{
   TCanvas *Ls = new TCanvas("Ls","test",500,200);
   TText  t;
   t.SetTextAlign(32);
   t.SetTextSize(0.08);
   Int_t i=1;
   gStyle->SetLineStyleString(9,"400 20");
   for (float s=0.1; s<1.0 ; s+=0.092) {
      TLine *lh = new TLine(0.15,s,.85,s);
      lh->SetLineStyle(i);
      t.DrawText(0.1,s,Form("%d",i++));
      lh->Draw();
   }
   return Ls;
}
End_Macro */

//______________________________________________________________________________
TAttLine::TAttLine()
{
   // AttLine default constructor.

   if (!gStyle) return;
   fLineColor = gStyle->GetLineColor();
   fLineWidth = gStyle->GetLineWidth();
   fLineStyle = gStyle->GetLineStyle();
}

//______________________________________________________________________________
TAttLine::TAttLine(Color_t color, Style_t style, Width_t width)
{
   // AttLine normal constructor.
   // Line attributes are taking from the argument list
   //   color : must be one of the valid color index
   //   style : 1=solid, 2=dash, 3=dash-dot, 4=dot-dot. New styles can be
   //           defined using TStyle::SetLineStyleString.
   //   width : expressed in pixel units

   fLineColor = color;
   fLineWidth = width;
   fLineStyle = style;
}

//______________________________________________________________________________
TAttLine::~TAttLine()
{
   // AttLine destructor.
}

//______________________________________________________________________________
void TAttLine::Copy(TAttLine &attline) const
{
   // Copy this line attributes to a new TAttLine.

   attline.fLineColor  = fLineColor;
   attline.fLineStyle  = fLineStyle;
   attline.fLineWidth  = fLineWidth;
}

//______________________________________________________________________________
Int_t TAttLine::DistancetoLine(Int_t px, Int_t py, Double_t xp1, Double_t yp1, Double_t xp2, Double_t yp2 )
{
   // Compute distance from point px,py to a line.
   // Compute the closest distance of approach from point px,py to this line.
   // The distance is computed in pixels units.
   //
   // Algorithm:
   //
   //   A(x1,y1)         P                             B(x2,y2)
   //   -----------------+------------------------------
   //                    |
   //                    |
   //                    |
   //                    |
   //                   M(x,y)
   //
   // Let us call  a = distance AM     A=a**2
   //              b = distance BM     B=b**2
   //              c = distance AB     C=c**2
   //              d = distance PM     D=d**2
   //              u = distance AP     U=u**2
   //              v = distance BP     V=v**2     c = u + v
   //
   // D = A - U
   // D = B - V  = B -(c-u)**2
   //    ==> u = (A -B +C)/2c

   Double_t xl, xt, yl, yt;
   Double_t x     = px;
   Double_t y     = py;
   Double_t x1    = gPad->XtoAbsPixel(xp1);
   Double_t y1    = gPad->YtoAbsPixel(yp1);
   Double_t x2    = gPad->XtoAbsPixel(xp2);
   Double_t y2    = gPad->YtoAbsPixel(yp2);
   if (x1 < x2) {xl = x1; xt = x2;}
   else         {xl = x2; xt = x1;}
   if (y1 < y2) {yl = y1; yt = y2;}
   else         {yl = y2; yt = y1;}
   if (x < xl-2 || x> xt+2) return 9999;  //following algorithm only valid in the box
   if (y < yl-2 || y> yt+2) return 9999;  //surrounding the line
   Double_t xx1   = x  - x1;
   Double_t xx2   = x  - x2;
   Double_t x1x2  = x1 - x2;
   Double_t yy1   = y  - y1;
   Double_t yy2   = y  - y2;
   Double_t y1y2  = y1 - y2;
   Double_t a     = xx1*xx1   + yy1*yy1;
   Double_t b     = xx2*xx2   + yy2*yy2;
   Double_t c     = x1x2*x1x2 + y1y2*y1y2;
   if (c <= 0)  return 9999;
   Double_t v     = sqrt(c);
   Double_t u     = (a - b + c)/(2*v);
   Double_t d     = TMath::Abs(a - u*u);
   if (d < 0)   return 9999;

   return Int_t(sqrt(d) - 0.5*Double_t(fLineWidth));
}

//______________________________________________________________________________
void TAttLine::Modify()
{
   // Change current line attributes if necessary.

   if (!gPad) return;
   Int_t lineWidth = TMath::Abs(fLineWidth%100);
   if (!gPad->IsBatch()) {
      gVirtualX->SetLineColor(fLineColor);
      if (fLineStyle > 0 && fLineStyle < 30) gVirtualX->SetLineStyle(fLineStyle);
      else                                   gVirtualX->SetLineStyle(1);
      gVirtualX->SetLineWidth(lineWidth);
   }

   if (fLineStyle > 0 && fLineStyle < 30) gPad->SetAttLinePS(fLineColor,fLineStyle,lineWidth);
   else                                   gPad->SetAttLinePS(fLineColor,1,lineWidth);
}

//______________________________________________________________________________
void TAttLine::ResetAttLine(Option_t *)
{
   // Reset this line attributes to default values.

   fLineColor  = 1;
   fLineStyle  = 1;
   fLineWidth  = 1;
}

//______________________________________________________________________________
void TAttLine::SaveLineAttributes(ostream &out, const char *name, Int_t coldef, Int_t stydef, Int_t widdef)
{
   // Save line attributes as C++ statement(s) on output stream out.

   if (fLineColor != coldef) {
      if (fLineColor > 228) {
         TColor::SaveColor(out, fLineColor);
         out<<"   "<<name<<"->SetLineColor(ci);" << endl;
      } else
         out<<"   "<<name<<"->SetLineColor("<<fLineColor<<");"<<endl;
   }
   if (fLineStyle != stydef) {
      out<<"   "<<name<<"->SetLineStyle("<<fLineStyle<<");"<<endl;
   }
   if (fLineWidth != widdef) {
      out<<"   "<<name<<"->SetLineWidth("<<fLineWidth<<");"<<endl;
   }
}

//______________________________________________________________________________
void TAttLine::SetLineAttributes()
{
   // Invoke the DialogCanvas Line attributes.

   TVirtualPadEditor::UpdateLineAttributes(fLineColor,fLineStyle,fLineWidth);
}
<|endoftext|>