<commit_before>#ifndef DOMImplementationImpl_HEADER_GUARD_
#define DOMImplementationImpl_HEADER_GUARD_
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/DOM.hpp> for the entire
//  DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLMsgLoader;

class DOMImplementationImpl: public XMemory,
                             public DOMImplementation,
                             public DOMImplementationSource
{
private:
    DOMImplementationImpl() {};
    DOMImplementationImpl(const DOMImplementationImpl & other) {};
    DOMImplementationImpl & operator = (const DOMImplementationImpl & other) {return *this;};
public:
    virtual ~DOMImplementationImpl() {};
    static DOMImplementationImpl*   getDOMImplementationImpl();
    static XMLMsgLoader* getMsgLoader4DOM();

    // ------------------------------------------------------------
    // DOMImplementation Virtual interface
    // ------------------------------------------------------------
    virtual bool                hasFeature(const  XMLCh * feature,  const  XMLCh * version) const;

    // Introduced in DOM Level 2
    virtual DOMDocumentType*    createDocumentType(const XMLCh *qualifiedName,
                                                   const XMLCh * publicId,
                                                   const XMLCh *systemId);
    virtual DOMDocument*        createDocument(const XMLCh *namespaceURI,
                                               const XMLCh *qualifiedName,
                                               DOMDocumentType *doctype,
                                               MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // DOM Level 3
    virtual DOMImplementation*  getInterface(const XMLCh* feature);

    // Non-standard extension
    virtual DOMDocument*        createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationLS Virtual interface
    // ------------------------------------------------------------
    // Introduced in DOM Level 3
    // Experimental - subject to change
    virtual DOMBuilder*         createDOMBuilder(const short           mode,
                                                 const XMLCh* const    schemaType,
                                                 MemoryManager* const  manager = XMLPlatformUtils::fgMemoryManager,
                                                 XMLGrammarPool* const gramPool = 0);
    virtual DOMWriter*          createDOMWriter(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMInputSource*     createDOMInputSource();

    // ------------------------------------------------------------
    // DOMImplementationSource Virtual interface
    // ------------------------------------------------------------
    virtual DOMImplementation* getDOMImplementation(const XMLCh* features) const;

};

XERCES_CPP_NAMESPACE_END

#endif
<commit_msg>Changed constuctors to protected so we can derive classes.<commit_after>#ifndef DOMImplementationImpl_HEADER_GUARD_
#define DOMImplementationImpl_HEADER_GUARD_
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/DOM.hpp> for the entire
//  DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLMsgLoader;

class DOMImplementationImpl: public XMemory,
                             public DOMImplementation,
                             public DOMImplementationSource
{
protected:
    DOMImplementationImpl() {};
    DOMImplementationImpl(const DOMImplementationImpl & other) {};
    DOMImplementationImpl & operator = (const DOMImplementationImpl & other) {return *this;};
public:
    virtual ~DOMImplementationImpl() {};
    static DOMImplementationImpl*   getDOMImplementationImpl();
    static XMLMsgLoader* getMsgLoader4DOM();

    // ------------------------------------------------------------
    // DOMImplementation Virtual interface
    // ------------------------------------------------------------
    virtual bool                hasFeature(const  XMLCh * feature,  const  XMLCh * version) const;

    // Introduced in DOM Level 2
    virtual DOMDocumentType*    createDocumentType(const XMLCh *qualifiedName,
                                                   const XMLCh * publicId,
                                                   const XMLCh *systemId);
    virtual DOMDocument*        createDocument(const XMLCh *namespaceURI,
                                               const XMLCh *qualifiedName,
                                               DOMDocumentType *doctype,
                                               MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // DOM Level 3
    virtual DOMImplementation*  getInterface(const XMLCh* feature);

    // Non-standard extension
    virtual DOMDocument*        createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationLS Virtual interface
    // ------------------------------------------------------------
    // Introduced in DOM Level 3
    // Experimental - subject to change
    virtual DOMBuilder*         createDOMBuilder(const short           mode,
                                                 const XMLCh* const    schemaType,
                                                 MemoryManager* const  manager = XMLPlatformUtils::fgMemoryManager,
                                                 XMLGrammarPool* const gramPool = 0);
    virtual DOMWriter*          createDOMWriter(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMInputSource*     createDOMInputSource();

    // ------------------------------------------------------------
    // DOMImplementationSource Virtual interface
    // ------------------------------------------------------------
    virtual DOMImplementation* getDOMImplementation(const XMLCh* features) const;

};

XERCES_CPP_NAMESPACE_END

#endif
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Backtrace.h"

#ifndef _WIN32
#include <execinfo.h>
#include <cxxabi.h>
#endif

#include <stdlib.h>
#include <iostream>

using namespace std;

namespace avg {

void dumpBacktrace()
{
#ifndef _WIN32
    vector<string> sFuncs;
    getBacktrace(sFuncs);
    int i=0;
    vector<string>::iterator it = sFuncs.begin();
    ++it;
    for (; it != sFuncs.end(); ++it) {
        cerr << "  " << i << ": " << *it << endl;
        i++;
    }
#endif
}

string funcNameFromLine(const string& sLine)
{
    try {
#ifdef __APPLE__
        string::size_type addressPos = sLine.find("0x");
        string::size_type namePos = sLine.find(" ", addressPos);
        namePos++;
        string::size_type nameEndPos = sLine.find(" ", namePos);
#else
        string::size_type namePos = sLine.find("(");
        namePos++;
        string::size_type nameEndPos = sLine.find_first_of(")+", namePos);
#endif
        return sLine.substr(namePos, nameEndPos-namePos);
    } catch (exception& e) {
        return sLine;
    }
}

void getBacktrace(std::vector<std::string>& sFuncs)
{
#ifndef _WIN32
    void* callstack[128];
    int numFrames = backtrace(callstack, 128);
    char** ppszLines = backtrace_symbols(callstack, numFrames);
    for (int i = 1; i < numFrames; ++i) {
        string sLine = ppszLines[i];
        string sFuncName = funcNameFromLine(sLine);
        int result;
        char * pszDemangledFuncName = abi::__cxa_demangle(sFuncName.c_str(), 0, 0,
                &result);
        if (!result) {
            sFuncName = pszDemangledFuncName;
            free(pszDemangledFuncName);
        }
        sFuncs.push_back(sFuncName);
    }
    free(ppszLines);
#endif
}

}

<commit_msg>Minor nit.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "Backtrace.h"

#ifndef _WIN32
#include <execinfo.h>
#include <cxxabi.h>
#endif

#include <stdlib.h>
#include <iostream>

using namespace std;

namespace avg {

void dumpBacktrace()
{
#ifndef _WIN32
    vector<string> sFuncs;
    getBacktrace(sFuncs);
    int i=0;
    vector<string>::iterator it = sFuncs.begin();
    ++it;
    for (; it != sFuncs.end(); ++it) {
        cerr << "  " << i << ": " << *it << endl;
        i++;
    }
#endif
}

string funcNameFromLine(const string& sLine)
{
    try {
#ifdef __APPLE__
        string::size_type addressPos = sLine.find("0x");
        string::size_type namePos = sLine.find(" ", addressPos);
        namePos++;
        string::size_type nameEndPos = sLine.find(" ", namePos);
#else
        string::size_type namePos = sLine.find("(");
        namePos++;
        string::size_type nameEndPos = sLine.find_first_of(")+", namePos);
#endif
        return sLine.substr(namePos, nameEndPos-namePos);
    } catch (exception&) {
        return sLine;
    }
}

void getBacktrace(std::vector<std::string>& sFuncs)
{
#ifndef _WIN32
    void* callstack[128];
    int numFrames = backtrace(callstack, 128);
    char** ppszLines = backtrace_symbols(callstack, numFrames);
    for (int i = 1; i < numFrames; ++i) {
        string sLine = ppszLines[i];
        string sFuncName = funcNameFromLine(sLine);
        int result;
        char * pszDemangledFuncName = abi::__cxa_demangle(sFuncName.c_str(), 0, 0,
                &result);
        if (!result) {
            sFuncName = pszDemangledFuncName;
            free(pszDemangledFuncName);
        }
        sFuncs.push_back(sFuncName);
    }
    free(ppszLines);
#endif
}

}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_NORMAL_ID_GLM_LPDF_HPP
#define STAN_MATH_PRIM_MAT_PROB_NORMAL_ID_GLM_LPDF_HPP

#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/mat/meta/is_vector.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <stan/math/prim/scal/fun/sum.hpp>
#include <stan/math/prim/scal/fun/as_array.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Returns the log PDF of the Generalized Linear Model (GLM)
 * with Normal distribution and id link function.
 * If containers are supplied, returns the log sum of the probabilities.
 * The idea is that normal_id_glm_lpdf(y, x, alpha, beta, sigma) should
 * compute a more efficient version of normal_lpdf(y, alpha + x * beta, sigma)
 * by using analytically simplified gradients.
 * @tparam T_y type of vector of dependent variables (labels);
 * @tparam T_x type of the matrix of independent variables (features); this
 * should be an Eigen::Matrix type whose number of rows should match the
 * length of y and whose number of columns should match the length of beta
 * @tparam T_alpha type of the intercept(s);
 * this can be a vector (of the same length as y) of intercepts or a single
 * value (for models with constant intercept);
 * @tparam T_beta type of the weight vector;
 * this can also be a single value;
 * @tparam T_scale type of the (positive) scale(s);
 * this can be a vector (of the same length as y, for heteroskedasticity)
 * or a scalar.
 * @param y vector parameter
 * @param x design matrix
 * @param alpha intercept (in log odds)
 * @param beta weight vector
 * @param sigma (Sequence of) scale parameters for the normal
 * distribution.
 * @return log probability or log sum of probabilities
 * @throw std::domain_error if x, beta or alpha is infinite.
 * @throw std::domain_error if the scale is not positive.
 * @throw std::invalid_argument if container sizes mismatch.
 */
template <bool propto, typename T_y, typename T_x, typename T_alpha,
          typename T_beta, typename T_scale>
typename return_type<T_y, T_x, T_alpha, T_beta, T_scale>::type
normal_id_glm_lpdf(const T_y &y, const T_x &x, const T_alpha &alpha,
                   const T_beta &beta, const T_scale &sigma) {
  static const char *function = "normal_id_glm_lpdf";
  typedef typename stan::partials_return_type<T_y, T_x, T_alpha, T_beta,
                                              T_scale>::type T_partials_return;
  typedef typename std::conditional<
      is_vector<T_scale>::value,
      Eigen::Array<typename stan::partials_return_type<T_scale>::type, -1, 1>,
      typename stan::partials_return_type<T_scale>::type>::type T_scale_val;
//  typedef typename std::conditional<
//          is_vector<T_alpha>::value,
//          Eigen::Array<typename stan::partials_return_type<T_alpha>::type, -1, 1>,
//          typename stan::partials_return_type<T_alpha>::type>::type T_alpha_val;
//  typedef typename std::conditional<
//          is_vector<T_beta>::value,
//          Eigen::Array<typename stan::partials_return_type<T_beta>::type, -1, 1>,
//          typename stan::partials_return_type<T_beta>::type>::type T_beta_val;
//  typedef typename std::conditional<
//      is_vector<T_y>::value,
//      Eigen::Array<typename stan::partials_return_type<T_y>::type, -1, 1>,
//      typename stan::partials_return_type<T_y>::type>::type T_y_val;

  using Eigen::Array;
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using std::exp;

  if (!(stan::length(y) && stan::length(x) && stan::length(beta)
        && stan::length(sigma)))
    return 0.0;

  T_partials_return logp(0.0);

  const size_t N = x.col(0).size();
  const size_t M = x.row(0).size();

  check_finite(function, "Vector of dependent variables", y);
  check_finite(function, "Weight vector", beta);
  check_finite(function, "Intercept", alpha);
  check_positive_finite(function, "Scale vector", sigma);
  check_consistent_size(function, "Vector of dependent variables", y, N);
  check_consistent_size(function, "Weight vector", beta, M);
  if (is_vector<T_scale>::value)
    check_consistent_sizes(function, "Vector of scale parameters", sigma,
                           "Vector of dependent variables", y);
  if (is_vector<T_alpha>::value)
    check_consistent_sizes(function, "Vector of intercepts", alpha,
                           "Vector of dependent variables", y);

  if (!include_summand<propto, T_y, T_x, T_alpha, T_beta, T_scale>::value)
    return 0.0;

  // Set up data structures and compute log-density.
  if (include_summand<propto>::value)
    logp += NEG_LOG_SQRT_TWO_PI * N;

  const auto& x_val = value_of(x);
  const auto& beta_dbl = value_of(beta);
//  Matrix<T_partials_return, Dynamic, 1> beta_dbl(M, 1);
//  {
//    scalar_seq_view<T_beta> beta_vec(beta);
//    for (size_t m = 0; m < M; ++m) {
//      beta_dbl[m] = value_of(beta_vec[m]);
//    }
//  }
  const auto &alpha_val = value_of(alpha);
  const auto &sigma_val = value_of(sigma);
  const auto &y_val = value_of(y);

  T_scale_val inv_sigma = 1 / as_array(sigma_val);
  Array<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma
      = (as_array(y_val) - (x_val * beta_dbl).array() - as_array(alpha_val)) * inv_sigma;
  Matrix<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma_squared
      = y_minus_mu_over_sigma * y_minus_mu_over_sigma;
  check_finite(function, "Matrix of independent variables",
               y_minus_mu_over_sigma_squared);
  if (include_summand<propto, T_scale>::value) {
    if (is_vector<T_scale>::value)
      logp -= sum(log(sigma_val));
    else
      logp -= N * sum(log(sigma_val));
  }

  double y_minus_mu_over_sigma_squared_sum;
  if(include_summand<propto, T_y, T_x, T_alpha, T_beta, T_scale>::value ||
      (!is_constant_struct<T_scale>::value && !is_vector<T_scale>::value)){
    y_minus_mu_over_sigma_squared_sum = y_minus_mu_over_sigma_squared.sum();
  }

  if (include_summand<propto, T_y, T_x, T_alpha, T_beta, T_scale>::value)
    logp -= 0.5 * y_minus_mu_over_sigma_squared_sum;

  // Compute the necessary derivatives.
  operands_and_partials<T_y, T_x, T_alpha, T_beta, T_scale> ops_partials(
      y, x, alpha, beta, sigma);
  if (!(is_constant_struct<T_y>::value && is_constant_struct<T_x>::value
        && is_constant_struct<T_beta>::value
        && is_constant_struct<T_alpha>::value)) {
    Matrix<T_partials_return, Dynamic, 1> mu_derivative
        = (inv_sigma * y_minus_mu_over_sigma).matrix();
    if (!is_constant_struct<T_y>::value) {
      ops_partials.edge1_.partials_ = -mu_derivative;
    }
    if (!is_constant_struct<T_x>::value) {
      ops_partials.edge2_.partials_ = mu_derivative * beta_dbl.transpose();
    }
    if (!is_constant_struct<T_beta>::value) {
      ops_partials.edge4_.partials_ = mu_derivative.transpose() * x_val;
    }
    if (!is_constant_struct<T_alpha>::value) {
      if (is_vector<T_alpha>::value)
        ops_partials.edge3_.partials_ = mu_derivative;
      else
        ops_partials.edge3_.partials_[0] = mu_derivative.sum();
    }
    if (!is_constant_struct<T_scale>::value) {
      if (is_vector<T_scale>::value) {
        ops_partials.edge5_.partials_
            = (y_minus_mu_over_sigma_squared.array() - 1) * inv_sigma;
      } else {
        ops_partials.edge5_.partials_[0]
            = (y_minus_mu_over_sigma_squared_sum - N) * inv_sigma;
      }
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_x, typename T_alpha, typename T_beta,
          typename T_scale>
inline typename return_type<T_y, T_x, T_alpha, T_beta, T_scale>::type
normal_id_glm_lpdf(const T_y &y, const T_x &x, const T_alpha &alpha,
                   const T_beta &beta, const T_scale &sigma) {
  return normal_id_glm_lpdf<false>(y, x, alpha, beta, sigma);
}
}  // namespace math
}  // namespace stan
#endif
<commit_msg>optimized use of temporary variables in normal_id_glm<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_NORMAL_ID_GLM_LPDF_HPP
#define STAN_MATH_PRIM_MAT_PROB_NORMAL_ID_GLM_LPDF_HPP

#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/mat/fun/value_of.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/mat/meta/is_vector.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <stan/math/prim/scal/fun/sum.hpp>
#include <stan/math/prim/scal/fun/as_array.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Returns the log PDF of the Generalized Linear Model (GLM)
 * with Normal distribution and id link function.
 * If containers are supplied, returns the log sum of the probabilities.
 * The idea is that normal_id_glm_lpdf(y, x, alpha, beta, sigma) should
 * compute a more efficient version of normal_lpdf(y, alpha + x * beta, sigma)
 * by using analytically simplified gradients.
 * @tparam T_y type of vector of dependent variables (labels);
 * @tparam T_x type of the matrix of independent variables (features); this
 * should be an Eigen::Matrix type whose number of rows should match the
 * length of y and whose number of columns should match the length of beta
 * @tparam T_alpha type of the intercept(s);
 * this can be a vector (of the same length as y) of intercepts or a single
 * value (for models with constant intercept);
 * @tparam T_beta type of the weight vector;
 * this can also be a single value;
 * @tparam T_scale type of the (positive) scale(s);
 * this can be a vector (of the same length as y, for heteroskedasticity)
 * or a scalar.
 * @param y vector parameter
 * @param x design matrix
 * @param alpha intercept (in log odds)
 * @param beta weight vector
 * @param sigma (Sequence of) scale parameters for the normal
 * distribution.
 * @return log probability or log sum of probabilities
 * @throw std::domain_error if x, beta or alpha is infinite.
 * @throw std::domain_error if the scale is not positive.
 * @throw std::invalid_argument if container sizes mismatch.
 */
template <bool propto, typename T_y, typename T_x, typename T_alpha,
          typename T_beta, typename T_scale>
typename return_type<T_y, T_x, T_alpha, T_beta, T_scale>::type
normal_id_glm_lpdf(const T_y &y, const T_x &x, const T_alpha &alpha,
                   const T_beta &beta, const T_scale &sigma) {
  static const char *function = "normal_id_glm_lpdf";
  typedef typename stan::partials_return_type<T_y, T_x, T_alpha, T_beta,
                                              T_scale>::type T_partials_return;
  typedef typename std::conditional<
      is_vector<T_scale>::value,
      Eigen::Array<typename stan::partials_return_type<T_scale>::type, -1, 1>,
      typename stan::partials_return_type<T_scale>::type>::type T_scale_val;
//  typedef typename std::conditional<
//          is_vector<T_alpha>::value,
//          Eigen::Array<typename stan::partials_return_type<T_alpha>::type, -1, 1>,
//          typename stan::partials_return_type<T_alpha>::type>::type T_alpha_val;
//  typedef typename std::conditional<
//          is_vector<T_beta>::value,
//          Eigen::Array<typename stan::partials_return_type<T_beta>::type, -1, 1>,
//          typename stan::partials_return_type<T_beta>::type>::type T_beta_val;
//  typedef typename std::conditional<
//      is_vector<T_y>::value,
//      Eigen::Array<typename stan::partials_return_type<T_y>::type, -1, 1>,
//      typename stan::partials_return_type<T_y>::type>::type T_y_val;

  using Eigen::Array;
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using std::exp;

  if (!(stan::length(y) && stan::length(x) && stan::length(beta)
        && stan::length(sigma)))
    return 0.0;

  const size_t N = x.col(0).size();
  const size_t M = x.row(0).size();

  check_positive_finite(function, "Scale vector", sigma);
  check_consistent_size(function, "Vector of dependent variables", y, N);
  check_consistent_size(function, "Weight vector", beta, M);
  if (is_vector<T_scale>::value)
    check_consistent_sizes(function, "Vector of scale parameters", sigma,
                           "Vector of dependent variables", y);
  if (is_vector<T_alpha>::value)
    check_consistent_sizes(function, "Vector of intercepts", alpha,
                           "Vector of dependent variables", y);

  if (!include_summand<propto, T_y, T_x, T_alpha, T_beta, T_scale>::value)
    return 0.0;

  const auto& x_val = value_of(x);
  const auto& beta_dbl = value_of(beta);
  const auto &alpha_val = value_of(alpha);
  const auto &sigma_val = value_of(sigma);
  const auto &y_val = value_of(y);

  T_scale_val inv_sigma = 1 / as_array(sigma_val);

  Array<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma = x_val * beta_dbl;
  y_minus_mu_over_sigma = (as_array(y_val) - y_minus_mu_over_sigma - as_array(alpha_val))*inv_sigma;

  // Compute the derivatives.
  operands_and_partials<T_y, T_x, T_alpha, T_beta, T_scale> ops_partials(
      y, x, alpha, beta, sigma);
  double y_minus_mu_over_sigma_squared_sum; // the most efficient way to calculate this depends on template parameters
  if (!(is_constant_struct<T_y>::value && is_constant_struct<T_x>::value
        && is_constant_struct<T_beta>::value
        && is_constant_struct<T_alpha>::value)) {
    Matrix<T_partials_return, Dynamic, 1> mu_derivative = inv_sigma * y_minus_mu_over_sigma;
    if (!is_constant_struct<T_y>::value) {
      ops_partials.edge1_.partials_ = -mu_derivative;
    }
    if (!is_constant_struct<T_x>::value) {
      ops_partials.edge2_.partials_ = mu_derivative * beta_dbl.transpose();
    }
    if (!is_constant_struct<T_beta>::value) {
      ops_partials.edge4_.partials_ = mu_derivative.transpose() * x_val;
    }
    if (!is_constant_struct<T_alpha>::value) {
      if (is_vector<T_alpha>::value)
        ops_partials.edge3_.partials_ = mu_derivative;
      else
        ops_partials.edge3_.partials_[0] = mu_derivative.sum();
    }
    if (!is_constant_struct<T_scale>::value) {
      if (is_vector<T_scale>::value) {
        Array<T_partials_return, Dynamic, 1> y_minus_mu_over_sigma_squared = y_minus_mu_over_sigma * y_minus_mu_over_sigma;
        y_minus_mu_over_sigma_squared_sum = y_minus_mu_over_sigma_squared.sum();
        ops_partials.edge5_.partials_
            = (y_minus_mu_over_sigma_squared - 1) * inv_sigma;
      } else {
        y_minus_mu_over_sigma_squared_sum = (y_minus_mu_over_sigma * y_minus_mu_over_sigma).sum();
        ops_partials.edge5_.partials_[0]
            = (y_minus_mu_over_sigma_squared_sum - N) * inv_sigma;
      }
    }
  }
  else{
    y_minus_mu_over_sigma_squared_sum = (y_minus_mu_over_sigma * y_minus_mu_over_sigma).sum();
  }

  if(!std::isfinite(y_minus_mu_over_sigma_squared_sum)){ //only do potentially expensive checks if they are really needed
    check_finite(function, "Vector of dependent variables", y);
    check_finite(function, "Weight vector", beta);
    check_finite(function, "Intercept", alpha);
    check_finite(function, "Matrix of independent variables", y_minus_mu_over_sigma_squared_sum); // if all other checks passed this will only fail if x is not finite
  }

  // Compute log probability.
  T_partials_return logp(0.0);
  if (include_summand<propto>::value)
    logp += NEG_LOG_SQRT_TWO_PI * N;
  if (include_summand<propto, T_scale>::value) {
    if (is_vector<T_scale>::value)
      logp -= sum(log(sigma_val));
    else
      logp -= N * sum(log(sigma_val));
  }
  if (include_summand<propto, T_y, T_x, T_alpha, T_beta, T_scale>::value)
    logp -= 0.5 * y_minus_mu_over_sigma_squared_sum;

  return ops_partials.build(logp);
}

template <typename T_y, typename T_x, typename T_alpha, typename T_beta,
          typename T_scale>
inline typename return_type<T_y, T_x, T_alpha, T_beta, T_scale>::type
normal_id_glm_lpdf(const T_y &y, const T_x &x, const T_alpha &alpha,
                   const T_beta &beta, const T_scale &sigma) {
  return normal_id_glm_lpdf<false>(y, x, alpha, beta, sigma);
}
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/**
 * @file oivs_init.hpp
 * @author Marcus Edel
 *
 * Definition and implementation of the Optimal Initial Value Setting method
 * (OIVS). This initialization rule is based on geometrical considerations as
 * described by H. Shimodaira.
 *
 * For more information, see the following paper.
 *
 * @code
 * @inproceedings{ShimodairaICTAI1994,
 *   title={A weight value initialization method for improving learning
 *   performance of the backpropagation algorithm in neural networks},
 *   author={Shimodaira, H.},
 *   booktitle={Tools with Artificial Intelligence, 1994. Proceedings.,
 *   Sixth International Conference on},
 *   year={1994}
 * }
 * @endcode
 */
#ifndef __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP
#define __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP

#include <mlpack/core.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>

#include "random_init.hpp"

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * This class is used to initialize the weight matrix with the oivs method. The
 * method is based on the equations representing the characteristics of the
 * information transformation mechanism of a node. The method is defined by
 *
 * @f{eqnarray*}{
 * b &=& |F^{-1}(1 - \epsilon) - f^{-1}(\epsilon)| \\
 * \hat{w} &=& \frac{b}{k \cdot n} \\
 * \gamma &\le& a_i \le \gamma \\
 * w_i &=& \hat{w} \cdot \sqrt{a_i + 1}
 * @f}
 *
 * Where f is the transfer function epsilon, k custom parameters, n the number of
 * neurons in the outgoing layer and gamma a parameter that defines the random
 * interval.
 *
 * @tparam ActivationFunction The activation function used for the oivs method.
 */
template<
    class ActivationFunction = LogisticFunction
>
class OivsInitialization
{
 public:
  /**
   * Initialize the random initialization rule with the given values.
   *
   * @param epsilon Parameter to control the activation region.
   * @param k Parameter to control the activation region width.
   * @param gamma Parameter to define the uniform random range.
   */
  OivsInitialization(const double epsilon = 0.1,
                     const int k = 5,
                     const double gamma = 0.9) :
      epsilon(epsilon), k(k), gamma(gamma)
  {
    double b = std::abs(ActivationFunction::inv(1 - epsilon) -
    ActivationFunction::inv(epsilon));
  }

  /**
   * Initialize the elements of the specified weight matrix with the oivs method.
   *
   * @param W Weight matrix to initialize.
   * @param rows Number of rows.
   * @param cols Number of columns.
   */
  template<typename eT>
  void Initialize(arma::Mat<eT>& W, const size_t rows, const size_t cols)
  {
    RandomInitialization randomInit(-gamma, gamma);
    randomInit.Initialize(W, rows, cols);

    W = (b / (k  * rows)) * arma::sqrt(W + 1);
  }

  /**
   * Initialize the elements of the specified weight 3rd order tensor with the
   * oivs method.
   *
   * @param W 3rd order tensor to initialize.
   * @param rows Number of rows.
   * @param cols Number of columns.
   * @param slices Number of slices.
   */
  template<typename eT>
  void Initialize(arma::Cube<eT>& W,
                  const size_t rows,
                  const size_t cols,
                  const size_t slices)
  {
    W = arma::Cube<eT>(rows, cols, slices);

    for (size_t i = 0; i < slices; i++)
      Initialize(W.slice(i), rows, cols);
  }

 private:
  //! Parameter to control the activation region.
  const double b;

  //! Parameter to control the activation region width.
  const int k;

  //! Parameter to define the uniform random range.
  const double gamma;
}; // class OivsInitialization

}; // namespace ann
}; // namespace mlpack

#endif
<commit_msg>fix constructor bug<commit_after>/**
 * @file oivs_init.hpp
 * @author Marcus Edel
 *
 * Definition and implementation of the Optimal Initial Value Setting method
 * (OIVS). This initialization rule is based on geometrical considerations as
 * described by H. Shimodaira.
 *
 * For more information, see the following paper.
 *
 * @code
 * @inproceedings{ShimodairaICTAI1994,
 *   title={A weight value initialization method for improving learning
 *   performance of the backpropagation algorithm in neural networks},
 *   author={Shimodaira, H.},
 *   booktitle={Tools with Artificial Intelligence, 1994. Proceedings.,
 *   Sixth International Conference on},
 *   year={1994}
 * }
 * @endcode
 */
#ifndef __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP
#define __MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP

#include <mlpack/core.hpp>
#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>

#include "random_init.hpp"

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * This class is used to initialize the weight matrix with the oivs method. The
 * method is based on the equations representing the characteristics of the
 * information transformation mechanism of a node. The method is defined by
 *
 * @f{eqnarray*}{
 * b &=& |F^{-1}(1 - \epsilon) - f^{-1}(\epsilon)| \\
 * \hat{w} &=& \frac{b}{k \cdot n} \\
 * \gamma &\le& a_i \le \gamma \\
 * w_i &=& \hat{w} \cdot \sqrt{a_i + 1}
 * @f}
 *
 * Where f is the transfer function epsilon, k custom parameters, n the number of
 * neurons in the outgoing layer and gamma a parameter that defines the random
 * interval.
 *
 * @tparam ActivationFunction The activation function used for the oivs method.
 */
template<
    class ActivationFunction = LogisticFunction
>
class OivsInitialization
{
 public:
  /**
   * Initialize the random initialization rule with the given values.
   *
   * @param epsilon Parameter to control the activation region.
   * @param k Parameter to control the activation region width.
   * @param gamma Parameter to define the uniform random range.
   */
  OivsInitialization(const double epsilon = 0.1,
                     const int k = 5,
                     const double gamma = 0.9) :
      epsilon(epsilon), k(k), gamma(gamma),
      b(std::abs(ActivationFunction::inv(1 - epsilon) -
                 ActivationFunction::inv(epsilon)))
  {
  }

  /**
   * Initialize the elements of the specified weight matrix with the oivs method.
   *
   * @param W Weight matrix to initialize.
   * @param rows Number of rows.
   * @param cols Number of columns.
   */
  template<typename eT>
  void Initialize(arma::Mat<eT>& W, const size_t rows, const size_t cols)
  {
    RandomInitialization randomInit(-gamma, gamma);
    randomInit.Initialize(W, rows, cols);

    W = (b / (k  * rows)) * arma::sqrt(W + 1);
  }

  /**
   * Initialize the elements of the specified weight 3rd order tensor with the
   * oivs method.
   *
   * @param W 3rd order tensor to initialize.
   * @param rows Number of rows.
   * @param cols Number of columns.
   * @param slices Number of slices.
   */
  template<typename eT>
  void Initialize(arma::Cube<eT>& W,
                  const size_t rows,
                  const size_t cols,
                  const size_t slices)
  {
    W = arma::Cube<eT>(rows, cols, slices);

    for (size_t i = 0; i < slices; i++)
      Initialize(W.slice(i), rows, cols);
  }

 private:
  //! Parameter to control the activation region.
  const double epsilon;

  //! Parameter to control the activation region width.
  const int k;

  //! Parameter to define the uniform random range.
  const double gamma;

  //! Parameter to control the activation region.
  const double b;
}; // class OivsInitialization

}; // namespace ann
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PolarLabelPositionHelper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 12:12:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"

#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"

#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_VECTOR_B2IVECTOR_HXX
#include <basegfx/vector/b2ivector.hxx>
#endif

#include <com/sun/star/chart/DataLabelPlacement.hpp>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

PolarLabelPositionHelper::PolarLabelPositionHelper(
                    PolarPlottingPositionHelper* pPosHelper
                    , sal_Int32 nDimensionCount
                    , const uno::Reference< drawing::XShapes >& xLogicTarget
                    , ShapeFactory* pShapeFactory )
                    : LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
                    , m_pPosHelper(pPosHelper)
{
}

PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForLogicValues(
        LabelAlignment& rAlignment
        , double fLogicValueOnAngleAxis
        , double fLogicValueOnRadiusAxis
        , double fLogicZ
        , sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
    double fUnitCircleAngleDegree = m_pPosHelper->transformToAngleDegree( fLogicValueOnAngleAxis );
    double fUnitCircleRadius = m_pPosHelper->transformToRadius( fLogicValueOnRadiusAxis );

    return getLabelScreenPositionAndAlignmentForUnitCircleValues(
           rAlignment, ::com::sun::star::chart::DataLabelPlacement::OUTSIDE
           , fUnitCircleAngleDegree, 0.0
           , fUnitCircleRadius, fUnitCircleRadius, fLogicZ, nScreenValueOffsetInRadiusDirection );
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForUnitCircleValues(
        LabelAlignment& rAlignment, sal_Int32 nLabelPlacement
        , double fUnitCircleStartAngleDegree, double fUnitCircleWidthAngleDegree
        , double fUnitCircleInnerRadius, double fUnitCircleOuterRadius
        , double fLogicZ
        , sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
    bool bCenter = (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
                && (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::INSIDE);

    double fAngleDegree = fUnitCircleStartAngleDegree + fUnitCircleWidthAngleDegree/2.0;
    double fRadius = 0.0;
    if( !bCenter ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
        fRadius = fUnitCircleOuterRadius;
    else
        fRadius = fUnitCircleInnerRadius + (fUnitCircleOuterRadius-fUnitCircleInnerRadius)/2.0 ;

    awt::Point aRet( this->transformSceneToScreenPosition(
        m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ+0.5 ) ) );

    if(3==m_nDimensionCount && nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
    {
        //check wether the upper or the downer edge is more distant from the center
        //take the farest point to put the label to

        awt::Point aP0( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( 0, 0, fLogicZ ) ) );
        awt::Point aP1(aRet);
        awt::Point aP2( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ-0.5 ) ) );

        ::basegfx::B2DVector aV0( aP0.X, aP0.Y );
        ::basegfx::B2DVector aV1( aP1.X, aP1.Y );
        ::basegfx::B2DVector aV2( aP2.X, aP2.Y );

        double fL1 = ::basegfx::B2DVector(aV1-aV0).getLength();
        double fL2 = ::basegfx::B2DVector(aV2-aV0).getLength();

        if(fL2>fL1)
            aRet = aP2;

        //calculate new angle for alignment
        double fDX = aRet.X-aP0.X;
        double fDY = aRet.Y-aP0.Y;
        fDY*=-1.0;//drawing layer has inverse y values
        if( fDX != 0.0 )
        {
            fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
            if(fDX<0.0)
                fAngleDegree+=180.0;
        }
        else
        {
            if(fDY>0.0)
                fAngleDegree = 90.0;
            else
                fAngleDegree = 270.0;
        }
    }
    //------------------------------
    //set LabelAlignment
    if( !bCenter )
    {
        while(fAngleDegree>360.0)
            fAngleDegree-=360.0;
        while(fAngleDegree<0.0)
            fAngleDegree+=360.0;

        bool bOutside = nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE;

        if(fAngleDegree==0.0)
            rAlignment = LABEL_ALIGN_CENTER;
        else if(fAngleDegree<=22.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
        else if(fAngleDegree<67.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT_TOP : LABEL_ALIGN_LEFT_BOTTOM;
        else if(fAngleDegree<112.5)
            rAlignment = bOutside ? LABEL_ALIGN_TOP : LABEL_ALIGN_BOTTOM;
        else if(fAngleDegree<=157.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT_TOP : LABEL_ALIGN_RIGHT_BOTTOM;
        else if(fAngleDegree<=202.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT : LABEL_ALIGN_RIGHT;
        else if(fAngleDegree<247.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT_BOTTOM : LABEL_ALIGN_RIGHT_TOP;
        else if(fAngleDegree<292.5)
            rAlignment = bOutside ? LABEL_ALIGN_BOTTOM : LABEL_ALIGN_TOP;
        else if(fAngleDegree<337.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT_BOTTOM : LABEL_ALIGN_LEFT_TOP;
        else
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
    }
    else
    {
        rAlignment = LABEL_ALIGN_CENTER;
    }

    //add a scaling independent Offset if requested
    if( nScreenValueOffsetInRadiusDirection != 0)
    {
        awt::Point aOrigin( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( 0.0, 0.0, fLogicZ+0.5 ) ) );
        basegfx::B2IVector aDirection( aRet.X- aOrigin.X, aRet.Y- aOrigin.Y );
        aDirection.setLength(nScreenValueOffsetInRadiusDirection);
        aRet.X += aDirection.getX();
        aRet.Y += aDirection.getY();
    }

    return aRet;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.6.60); FILE MERGED 2008/04/01 15:04:30 thb 1.6.60.2: #i85898# Stripping all external header guards 2008/03/28 16:44:48 rt 1.6.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: PolarLabelPositionHelper.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"

#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/vector/b2ivector.hxx>

#include <com/sun/star/chart/DataLabelPlacement.hpp>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

PolarLabelPositionHelper::PolarLabelPositionHelper(
                    PolarPlottingPositionHelper* pPosHelper
                    , sal_Int32 nDimensionCount
                    , const uno::Reference< drawing::XShapes >& xLogicTarget
                    , ShapeFactory* pShapeFactory )
                    : LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
                    , m_pPosHelper(pPosHelper)
{
}

PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForLogicValues(
        LabelAlignment& rAlignment
        , double fLogicValueOnAngleAxis
        , double fLogicValueOnRadiusAxis
        , double fLogicZ
        , sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
    double fUnitCircleAngleDegree = m_pPosHelper->transformToAngleDegree( fLogicValueOnAngleAxis );
    double fUnitCircleRadius = m_pPosHelper->transformToRadius( fLogicValueOnRadiusAxis );

    return getLabelScreenPositionAndAlignmentForUnitCircleValues(
           rAlignment, ::com::sun::star::chart::DataLabelPlacement::OUTSIDE
           , fUnitCircleAngleDegree, 0.0
           , fUnitCircleRadius, fUnitCircleRadius, fLogicZ, nScreenValueOffsetInRadiusDirection );
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignmentForUnitCircleValues(
        LabelAlignment& rAlignment, sal_Int32 nLabelPlacement
        , double fUnitCircleStartAngleDegree, double fUnitCircleWidthAngleDegree
        , double fUnitCircleInnerRadius, double fUnitCircleOuterRadius
        , double fLogicZ
        , sal_Int32 nScreenValueOffsetInRadiusDirection ) const
{
    bool bCenter = (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
                && (nLabelPlacement != ::com::sun::star::chart::DataLabelPlacement::INSIDE);

    double fAngleDegree = fUnitCircleStartAngleDegree + fUnitCircleWidthAngleDegree/2.0;
    double fRadius = 0.0;
    if( !bCenter ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
        fRadius = fUnitCircleOuterRadius;
    else
        fRadius = fUnitCircleInnerRadius + (fUnitCircleOuterRadius-fUnitCircleInnerRadius)/2.0 ;

    awt::Point aRet( this->transformSceneToScreenPosition(
        m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ+0.5 ) ) );

    if(3==m_nDimensionCount && nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE)
    {
        //check wether the upper or the downer edge is more distant from the center
        //take the farest point to put the label to

        awt::Point aP0( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( 0, 0, fLogicZ ) ) );
        awt::Point aP1(aRet);
        awt::Point aP2( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( fAngleDegree, fRadius, fLogicZ-0.5 ) ) );

        ::basegfx::B2DVector aV0( aP0.X, aP0.Y );
        ::basegfx::B2DVector aV1( aP1.X, aP1.Y );
        ::basegfx::B2DVector aV2( aP2.X, aP2.Y );

        double fL1 = ::basegfx::B2DVector(aV1-aV0).getLength();
        double fL2 = ::basegfx::B2DVector(aV2-aV0).getLength();

        if(fL2>fL1)
            aRet = aP2;

        //calculate new angle for alignment
        double fDX = aRet.X-aP0.X;
        double fDY = aRet.Y-aP0.Y;
        fDY*=-1.0;//drawing layer has inverse y values
        if( fDX != 0.0 )
        {
            fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
            if(fDX<0.0)
                fAngleDegree+=180.0;
        }
        else
        {
            if(fDY>0.0)
                fAngleDegree = 90.0;
            else
                fAngleDegree = 270.0;
        }
    }
    //------------------------------
    //set LabelAlignment
    if( !bCenter )
    {
        while(fAngleDegree>360.0)
            fAngleDegree-=360.0;
        while(fAngleDegree<0.0)
            fAngleDegree+=360.0;

        bool bOutside = nLabelPlacement == ::com::sun::star::chart::DataLabelPlacement::OUTSIDE;

        if(fAngleDegree==0.0)
            rAlignment = LABEL_ALIGN_CENTER;
        else if(fAngleDegree<=22.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
        else if(fAngleDegree<67.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT_TOP : LABEL_ALIGN_LEFT_BOTTOM;
        else if(fAngleDegree<112.5)
            rAlignment = bOutside ? LABEL_ALIGN_TOP : LABEL_ALIGN_BOTTOM;
        else if(fAngleDegree<=157.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT_TOP : LABEL_ALIGN_RIGHT_BOTTOM;
        else if(fAngleDegree<=202.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT : LABEL_ALIGN_RIGHT;
        else if(fAngleDegree<247.5)
            rAlignment = bOutside ? LABEL_ALIGN_LEFT_BOTTOM : LABEL_ALIGN_RIGHT_TOP;
        else if(fAngleDegree<292.5)
            rAlignment = bOutside ? LABEL_ALIGN_BOTTOM : LABEL_ALIGN_TOP;
        else if(fAngleDegree<337.5)
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT_BOTTOM : LABEL_ALIGN_LEFT_TOP;
        else
            rAlignment = bOutside ? LABEL_ALIGN_RIGHT : LABEL_ALIGN_LEFT;
    }
    else
    {
        rAlignment = LABEL_ALIGN_CENTER;
    }

    //add a scaling independent Offset if requested
    if( nScreenValueOffsetInRadiusDirection != 0)
    {
        awt::Point aOrigin( this->transformSceneToScreenPosition(
            m_pPosHelper->transformUnitCircleToScene( 0.0, 0.0, fLogicZ+0.5 ) ) );
        basegfx::B2IVector aDirection( aRet.X- aOrigin.X, aRet.Y- aOrigin.Y );
        aDirection.setLength(nScreenValueOffsetInRadiusDirection);
        aRet.X += aDirection.getX();
        aRet.Y += aDirection.getY();
    }

    return aRet;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef CopyTexSubImage_INCLUDE_ONCE
#define CopyTexSubImage_INCLUDE_ONCE

#include <vlGraphics/Camera.hpp>
#include <vlGraphics/Texture.hpp>
#include <vlGraphics/RenderEventCallback.hpp>

namespace vl
{
  //-----------------------------------------------------------------------------
  // CopyTexSubImage
  //-----------------------------------------------------------------------------
  /** Wrapper class of the OpenGL function glCopyTexSubImage.
    *
    * Is the base class of CopyTexSubImage1D, CopyTexSubImage2D, CopyTexSubImage3D.
    * Copies a rectangular pixels area from the specified read buffer to the specified portion of the texture.
    * Can be bound to a Rendering as a RenderEventCallback in order to automatically copy
    * the result of a rendering into a texture, see Rendering.
    *
    * \note
    * This class supports Frame-Buffer-Objects, 3D textures, cubemaps.
    *
    * \sa
    * FBORenderTarget, FBOAbstractAttachment, Rendering, RenderEventCallback, CopyTexSubImage1D, CopyTexSubImage2D, CopyTexSubImage3D */
  class CopyTexSubImage: public RenderEventCallback
  {
  public:
    virtual const char* className() const { return "vl::CopyTexSubImage"; }
    CopyTexSubImage(): mReadBuffer(RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()
    }

    /** The source buffer used when copying color buffers, ignored when using depth textures. */
    EReadDrawBuffer readBuffer() const { return mReadBuffer; }

    /** The source buffer used when copying color buffers, ignored when using depth textures. */
    void setReadBuffer(EReadDrawBuffer render_buffer) { mReadBuffer = render_buffer; }

    virtual bool onRenderingStarted(const RenderingAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRenderingFinished(const RenderingAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRendererStarted(const RendererAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRendererFinished(const RendererAbstract*)
    {
      copyPixels();
      return true;
    }

    /**
     * Copies the pixels from the specified read buffer to the specified texture.
    */
    virtual void copyPixels() = 0;

  protected:
    EReadDrawBuffer mReadBuffer;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage1D, see also CopyTexSubImage.
  class CopyTexSubImage1D: public CopyTexSubImage
  {
  public:
    CopyTexSubImage1D(int level, int xoffset, int x, int y, int width, Texture* texture=NULL, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mLevel = level;
      mXOffset = xoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mTexture = texture;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage1D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }

    virtual void copyPixels()
    {
      VL_CHECK_OGL()
      VL_CHECK(texture()->dimension() == TD_TEXTURE_1D)

      VL_CHECK(texture()->handle())
      VL_CHECK(xoffset() >= 0)
      VL_CHECK(x() >= 0)
      VL_CHECK(y() >= 0)
      VL_CHECK(xoffset()+width() <= texture()->width())

#if defined(VL_OPENGL)
      int read_buffer = 0;
      if (!texture()->isDepthTexture())
      {
        glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
        glReadBuffer(readBuffer()); VL_CHECK_OGL()
      }
#endif

      glBindTexture(TD_TEXTURE_1D, texture()->handle() ); VL_CHECK_OGL()
      glCopyTexSubImage1D(TD_TEXTURE_1D, level(), xoffset(), x(), y(), width()); VL_CHECK_OGL()
      glBindTexture(TD_TEXTURE_1D, 0 ); VL_CHECK_OGL()

#if defined(VL_OPENGL)
      if (read_buffer)
      {
        glReadBuffer( read_buffer ); VL_CHECK_OGL()
      }
#endif
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mX;
    int mY;
    int mWidth;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage2D, see also CopyTexSubImage. To be used also for 1D array textures.
  class CopyTexSubImage2D: public CopyTexSubImage
  {
  public:

    CopyTexSubImage2D(int level, int xoffset, int yoffset, int x, int y, int width, int height, Texture* texture=NULL, ETex2DTarget target=T2DT_TEXTURE_2D, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()

      mLevel = level;
      mXOffset = xoffset;
      mYOffset = yoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mHeight = height;
      mTexture = texture;
      mTarget = target;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage2D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setYOffset(int yoffset) { mYOffset = yoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }
    void setHeight(int height) { mHeight = height; }
    void setTarget(ETex2DTarget target) { mTarget = target; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int yoffset() const { return mYOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }
    int height() const { return mHeight; }
    ETex2DTarget target() const { return mTarget; }

    virtual void copyPixels()
    {
      VL_CHECK_OGL()

      VL_CHECK(texture()->handle())
      VL_CHECK(xoffset() >= 0)
      VL_CHECK(yoffset() >= 0)
      VL_CHECK(x() >= 0)
      VL_CHECK(y() >= 0)
      VL_CHECK(xoffset()+width() <= texture()->width())
      VL_CHECK(yoffset()+height() <= texture()->height())

#if defined(VL_OPENGL)
      int read_buffer = 0;
      if (!texture()->isDepthTexture())
      {
        glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
        glReadBuffer(readBuffer()); VL_CHECK_OGL()
      }
#endif

      int bind_target = 0;
      switch( target() )
      {
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_X:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_X:
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_Y:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_Y:
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_Z:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_Z:
          bind_target = GL_TEXTURE_CUBE_MAP;
          break;
        default:
          bind_target = target();
      };

      glBindTexture( bind_target, texture()->handle() ); VL_CHECK_OGL()
      glCopyTexSubImage2D( target(), level(), xoffset(), yoffset(), x(), y(), width(), height() ); VL_CHECK_OGL()
      glBindTexture( bind_target, 0 ); VL_CHECK_OGL()

#if defined(VL_OPENGL)
      if (read_buffer)
      {
        glReadBuffer( read_buffer ); VL_CHECK_OGL()
      }
#endif
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mYOffset;
    int mX;
    int mY;
    int mWidth;
    int mHeight;
    ETex2DTarget mTarget;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage3D, see also CopyTexSubImage. To be used also for 2D array textures.
  class CopyTexSubImage3D: public CopyTexSubImage
  {
  public:
    CopyTexSubImage3D(int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height, Texture* texture, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()

      mLevel = level;
      mXOffset = xoffset;
      mYOffset = yoffset;
      mZOffset = zoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mHeight = height;
      mTexture = texture;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage3D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setYOffset(int yoffset) { mYOffset = yoffset; }
    void setZOffset(int zoffset) { mZOffset = zoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }
    void setHeight(int height) { mHeight = height; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int yoffset() const { return mYOffset; }
    int zoffset() const { return mZOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }
    int height() const { return mHeight; }

    virtual void copyPixels()
    {
      if (Has_Texture_3D)
      {
        VL_CHECK_OGL()
        VL_CHECK( texture()->dimension() == TD_TEXTURE_3D )

        VL_CHECK(texture()->handle())
        VL_CHECK(xoffset() >= 0)
        VL_CHECK(yoffset() >= 0)
        VL_CHECK(zoffset() >= 0)
        VL_CHECK(x() >= 0)
        VL_CHECK(y() >= 0)
        VL_CHECK(xoffset()+width()  <= texture()->width())
        VL_CHECK(yoffset()+height() <= texture()->height())
        VL_CHECK(zoffset() < texture()->depth())

#if defined(VL_OPENGL)
        int read_buffer = 0;
        if (!texture()->isDepthTexture())
        {
          glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
          glReadBuffer(readBuffer()); VL_CHECK_OGL()
        }
#endif

        glBindTexture(texture()->dimension(), texture()->handle() ); VL_CHECK_OGL()
        glCopyTexSubImage3D(texture()->dimension(), level(), xoffset(), yoffset(), zoffset(), x(), y(), width(), height()); VL_CHECK_OGL()
        glBindTexture(texture()->dimension(), 0 );

#if defined(VL_OPENGL)
        if (read_buffer)
        {
          glReadBuffer( read_buffer ); VL_CHECK_OGL()
        }
#endif
      }
      else
        Log::error("CopyTexSubImage3D requires OpenGL 1.2!\n");
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mYOffset;
    int mZOffset;
    int mX;
    int mY;
    int mWidth;
    int mHeight;
  };
  //-----------------------------------------------------------------------------
}

#endif
<commit_msg>Use texture 3d wrappers<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef CopyTexSubImage_INCLUDE_ONCE
#define CopyTexSubImage_INCLUDE_ONCE

#include <vlGraphics/Camera.hpp>
#include <vlGraphics/Texture.hpp>
#include <vlGraphics/RenderEventCallback.hpp>

namespace vl
{
  //-----------------------------------------------------------------------------
  // CopyTexSubImage
  //-----------------------------------------------------------------------------
  /** Wrapper class of the OpenGL function glCopyTexSubImage.
    *
    * Is the base class of CopyTexSubImage1D, CopyTexSubImage2D, CopyTexSubImage3D.
    * Copies a rectangular pixels area from the specified read buffer to the specified portion of the texture.
    * Can be bound to a Rendering as a RenderEventCallback in order to automatically copy
    * the result of a rendering into a texture, see Rendering.
    *
    * \note
    * This class supports Frame-Buffer-Objects, 3D textures, cubemaps.
    *
    * \sa
    * FBORenderTarget, FBOAbstractAttachment, Rendering, RenderEventCallback, CopyTexSubImage1D, CopyTexSubImage2D, CopyTexSubImage3D */
  class CopyTexSubImage: public RenderEventCallback
  {
  public:
    virtual const char* className() const { return "vl::CopyTexSubImage"; }
    CopyTexSubImage(): mReadBuffer(RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()
    }

    /** The source buffer used when copying color buffers, ignored when using depth textures. */
    EReadDrawBuffer readBuffer() const { return mReadBuffer; }

    /** The source buffer used when copying color buffers, ignored when using depth textures. */
    void setReadBuffer(EReadDrawBuffer render_buffer) { mReadBuffer = render_buffer; }

    virtual bool onRenderingStarted(const RenderingAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRenderingFinished(const RenderingAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRendererStarted(const RendererAbstract*)
    {
      copyPixels();
      return true;
    }

    virtual bool onRendererFinished(const RendererAbstract*)
    {
      copyPixels();
      return true;
    }

    /**
     * Copies the pixels from the specified read buffer to the specified texture.
    */
    virtual void copyPixels() = 0;

  protected:
    EReadDrawBuffer mReadBuffer;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage1D, see also CopyTexSubImage.
  class CopyTexSubImage1D: public CopyTexSubImage
  {
  public:
    CopyTexSubImage1D(int level, int xoffset, int x, int y, int width, Texture* texture=NULL, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()
      mLevel = level;
      mXOffset = xoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mTexture = texture;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage1D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }

    virtual void copyPixels()
    {
      VL_CHECK_OGL()
      VL_CHECK(texture()->dimension() == TD_TEXTURE_1D)

      VL_CHECK(texture()->handle())
      VL_CHECK(xoffset() >= 0)
      VL_CHECK(x() >= 0)
      VL_CHECK(y() >= 0)
      VL_CHECK(xoffset()+width() <= texture()->width())

#if defined(VL_OPENGL)
      int read_buffer = 0;
      if (!texture()->isDepthTexture())
      {
        glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
        glReadBuffer(readBuffer()); VL_CHECK_OGL()
      }
#endif

      glBindTexture(TD_TEXTURE_1D, texture()->handle() ); VL_CHECK_OGL()
      glCopyTexSubImage1D(TD_TEXTURE_1D, level(), xoffset(), x(), y(), width()); VL_CHECK_OGL()
      glBindTexture(TD_TEXTURE_1D, 0 ); VL_CHECK_OGL()

#if defined(VL_OPENGL)
      if (read_buffer)
      {
        glReadBuffer( read_buffer ); VL_CHECK_OGL()
      }
#endif
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mX;
    int mY;
    int mWidth;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage2D, see also CopyTexSubImage. To be used also for 1D array textures.
  class CopyTexSubImage2D: public CopyTexSubImage
  {
  public:

    CopyTexSubImage2D(int level, int xoffset, int yoffset, int x, int y, int width, int height, Texture* texture=NULL, ETex2DTarget target=T2DT_TEXTURE_2D, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()

      mLevel = level;
      mXOffset = xoffset;
      mYOffset = yoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mHeight = height;
      mTexture = texture;
      mTarget = target;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage2D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setYOffset(int yoffset) { mYOffset = yoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }
    void setHeight(int height) { mHeight = height; }
    void setTarget(ETex2DTarget target) { mTarget = target; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int yoffset() const { return mYOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }
    int height() const { return mHeight; }
    ETex2DTarget target() const { return mTarget; }

    virtual void copyPixels()
    {
      VL_CHECK_OGL()

      VL_CHECK(texture()->handle())
      VL_CHECK(xoffset() >= 0)
      VL_CHECK(yoffset() >= 0)
      VL_CHECK(x() >= 0)
      VL_CHECK(y() >= 0)
      VL_CHECK(xoffset()+width() <= texture()->width())
      VL_CHECK(yoffset()+height() <= texture()->height())

#if defined(VL_OPENGL)
      int read_buffer = 0;
      if (!texture()->isDepthTexture())
      {
        glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
        glReadBuffer(readBuffer()); VL_CHECK_OGL()
      }
#endif

      int bind_target = 0;
      switch( target() )
      {
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_X:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_X:
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_Y:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_Y:
        case T2DT_TEXTURE_CUBE_MAP_POSITIVE_Z:
        case T2DT_TEXTURE_CUBE_MAP_NEGATIVE_Z:
          bind_target = GL_TEXTURE_CUBE_MAP;
          break;
        default:
          bind_target = target();
      };

      glBindTexture( bind_target, texture()->handle() ); VL_CHECK_OGL()
      glCopyTexSubImage2D( target(), level(), xoffset(), yoffset(), x(), y(), width(), height() ); VL_CHECK_OGL()
      glBindTexture( bind_target, 0 ); VL_CHECK_OGL()

#if defined(VL_OPENGL)
      if (read_buffer)
      {
        glReadBuffer( read_buffer ); VL_CHECK_OGL()
      }
#endif
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mYOffset;
    int mX;
    int mY;
    int mWidth;
    int mHeight;
    ETex2DTarget mTarget;
  };
  //-----------------------------------------------------------------------------
  //! Wraps glCopyTexSubImage3D, see also CopyTexSubImage. To be used also for 2D array textures.
  class CopyTexSubImage3D: public CopyTexSubImage
  {
  public:
    CopyTexSubImage3D(int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height, Texture* texture, EReadDrawBuffer read_buffer=RDB_BACK_LEFT)
    {
      VL_DEBUG_SET_OBJECT_NAME()

      mLevel = level;
      mXOffset = xoffset;
      mYOffset = yoffset;
      mZOffset = zoffset;
      mX = x;
      mY = y;
      mWidth  = width;
      mHeight = height;
      mTexture = texture;
      setReadBuffer(read_buffer);
    }
    virtual const char* className() const { return "vl::CopyTexSubImage3D"; }

    void setTexture(Texture* tex) { mTexture = tex; }
    void setLevel(int level) { mLevel = level; }
    void setXOffset(int xoffset) { mXOffset = xoffset; }
    void setYOffset(int yoffset) { mYOffset = yoffset; }
    void setZOffset(int zoffset) { mZOffset = zoffset; }
    void setX(int x) { mX = x; }
    void setY(int y) { mY = y; }
    void setWidth(int width) { mWidth = width; }
    void setHeight(int height) { mHeight = height; }

    Texture* texture() { return mTexture.get(); }
    const Texture* texture() const { return mTexture.get(); }
    int level() const { return mLevel; }
    int xoffset() const { return mXOffset; }
    int yoffset() const { return mYOffset; }
    int zoffset() const { return mZOffset; }
    int x() const { return mX; }
    int y() const { return mY; }
    int width() const { return mWidth; }
    int height() const { return mHeight; }

    virtual void copyPixels()
    {
      if (Has_Texture_3D)
      {
        VL_CHECK_OGL()
        VL_CHECK( texture()->dimension() == TD_TEXTURE_3D )

        VL_CHECK(texture()->handle())
        VL_CHECK(xoffset() >= 0)
        VL_CHECK(yoffset() >= 0)
        VL_CHECK(zoffset() >= 0)
        VL_CHECK(x() >= 0)
        VL_CHECK(y() >= 0)
        VL_CHECK(xoffset()+width()  <= texture()->width())
        VL_CHECK(yoffset()+height() <= texture()->height())
        VL_CHECK(zoffset() < texture()->depth())

#if defined(VL_OPENGL)
        int read_buffer = 0;
        if (!texture()->isDepthTexture())
        {
          glGetIntegerv(GL_READ_BUFFER, &read_buffer); VL_CHECK_OGL()
          glReadBuffer(readBuffer()); VL_CHECK_OGL()
        }
#endif

        glBindTexture(texture()->dimension(), texture()->handle() ); VL_CHECK_OGL()
        VL_glCopyTexSubImage3D(texture()->dimension(), level(), xoffset(), yoffset(), zoffset(), x(), y(), width(), height()); VL_CHECK_OGL()
        glBindTexture(texture()->dimension(), 0 );

#if defined(VL_OPENGL)
        if (read_buffer)
        {
          glReadBuffer( read_buffer ); VL_CHECK_OGL()
        }
#endif
      }
      else
        Log::error("CopyTexSubImage3D requires OpenGL 1.2!\n");
    }

  protected:
    ref<Texture> mTexture;
    int mLevel;
    int mXOffset;
    int mYOffset;
    int mZOffset;
    int mX;
    int mY;
    int mWidth;
    int mHeight;
  };
  //-----------------------------------------------------------------------------
}

#endif
<|endoftext|>


<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 "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 10000;

// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 5000;

// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";

// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
 public:
  MockExtensionView(const GURL& url, Profile* profile)
      : ExtensionView(url, profile), got_message_(false) {
    InitHidden();
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kAlertTimeoutMs);
    ui_test_utils::RunMessageLoop();
  }

  bool got_message() { return got_message_; }
 private:
  virtual void RunJavaScriptMessage(
      const std::wstring& message,
      const std::wstring& default_prompt,
      const GURL& frame_url,
      const int flags,
      IPC::Message* reply_msg,
      bool* did_suppress_message) {
    got_message_ = true;
    MessageLoopForUI::current()->Quit();

    // Call super, otherwise we'll leak reply_msg.
    ExtensionView::RunJavaScriptMessage(
        message, default_prompt, flags, reply_msg, did_suppress_message);
  }

  bool got_message_;
};

// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
 public:
  explicit ExtensionLoadedObserver() : extension_(NULL)  {
    registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
        NotificationService::AllSources());
  }

  Extension* WaitForExtension() {
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kLoadTimeoutMs);
    ui_test_utils::RunMessageLoop();
    return extension_;
  }

 private:
  virtual void Observe(NotificationType type, const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == NotificationType::EXTENSIONS_LOADED) {
      ExtensionList* extensions = Details<ExtensionList>(details).ptr();
      for (size_t i = 0; i < (*extensions).size(); i++) {
        if ((*extensions)[i]->id() == kExtensionId) {
          extension_ = (*extensions)[i];
          MessageLoopForUI::current()->Quit();
          break;
        }
      }
    } else {
      NOTREACHED();
    }
  }

  NotificationRegistrar registrar_;
  Extension* extension_;
};

}  // namespace

class ExtensionViewTest : public InProcessBrowserTest {
 public:
  virtual void SetUp() {
    // Initialize the error reporter here, otherwise BrowserMain will create it
    // with the wrong MessageLoop.
    ExtensionErrorReporter::Init(false);

    InProcessBrowserTest::SetUp();
  }
};

// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Index) {
  // Create an observer first to be sure we have the notification registered
  // before it's sent.
  ExtensionLoadedObserver observer;

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Load it.
  Profile* profile = browser()->profile();
  profile->GetExtensionsService()->Init();
  profile->GetExtensionsService()->LoadExtension(path);

  // Now wait for it to load, and grab a pointer to it.
  Extension* extension = observer.WaitForExtension();
  ASSERT_TRUE(extension);
  GURL url = Extension::GetResourceURL(extension->url(), "index.html");

  // Start the extension process and wait for it to show a javascript alert.
  MockExtensionView view(url, profile);
  EXPECT_TRUE(view.got_message());
}
<commit_msg>Fix build break.<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 "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 10000;

// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 5000;

// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";

// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
 public:
  MockExtensionView(const GURL& url, Profile* profile)
      : ExtensionView(url, profile), got_message_(false) {
    InitHidden();
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kAlertTimeoutMs);
    ui_test_utils::RunMessageLoop();
  }

  bool got_message() { return got_message_; }
 private:
  virtual void RunJavaScriptMessage(
      const std::wstring& message,
      const std::wstring& default_prompt,
      const GURL& frame_url,
      const int flags,
      IPC::Message* reply_msg,
      bool* did_suppress_message) {
    got_message_ = true;
    MessageLoopForUI::current()->Quit();

    // Call super, otherwise we'll leak reply_msg.
    ExtensionView::RunJavaScriptMessage(
        message, default_prompt, frame_url, flags,
        reply_msg, did_suppress_message);
  }

  bool got_message_;
};

// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
 public:
  explicit ExtensionLoadedObserver() : extension_(NULL)  {
    registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
        NotificationService::AllSources());
  }

  Extension* WaitForExtension() {
    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        new MessageLoop::QuitTask, kLoadTimeoutMs);
    ui_test_utils::RunMessageLoop();
    return extension_;
  }

 private:
  virtual void Observe(NotificationType type, const NotificationSource& source,
                       const NotificationDetails& details) {
    if (type == NotificationType::EXTENSIONS_LOADED) {
      ExtensionList* extensions = Details<ExtensionList>(details).ptr();
      for (size_t i = 0; i < (*extensions).size(); i++) {
        if ((*extensions)[i]->id() == kExtensionId) {
          extension_ = (*extensions)[i];
          MessageLoopForUI::current()->Quit();
          break;
        }
      }
    } else {
      NOTREACHED();
    }
  }

  NotificationRegistrar registrar_;
  Extension* extension_;
};

}  // namespace

class ExtensionViewTest : public InProcessBrowserTest {
 public:
  virtual void SetUp() {
    // Initialize the error reporter here, otherwise BrowserMain will create it
    // with the wrong MessageLoop.
    ExtensionErrorReporter::Init(false);

    InProcessBrowserTest::SetUp();
  }
};

// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, Index) {
  // Create an observer first to be sure we have the notification registered
  // before it's sent.
  ExtensionLoadedObserver observer;

  // Get the path to our extension.
  FilePath path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
  path = path.AppendASCII("extensions").
      AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
  ASSERT_TRUE(file_util::DirectoryExists(path));  // sanity check

  // Load it.
  Profile* profile = browser()->profile();
  profile->GetExtensionsService()->Init();
  profile->GetExtensionsService()->LoadExtension(path);

  // Now wait for it to load, and grab a pointer to it.
  Extension* extension = observer.WaitForExtension();
  ASSERT_TRUE(extension);
  GURL url = Extension::GetResourceURL(extension->url(), "index.html");

  // Start the extension process and wait for it to show a javascript alert.
  MockExtensionView view(url, profile);
  EXPECT_TRUE(view.got_message());
}
<|endoftext|>