code stringlengths 4 1.01M |
|---|
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2013-2013
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTRUSIVE_BS_SET_HPP
#define BOOST_INTRUSIVE_BS_SET_HPP
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/bstree.hpp>
#include <iterator>
#include <boost/move/move.hpp>
namespace boost {
namespace intrusive {
//! The class template bs_set is an intrusive container, that mimics most of
//! the interface of std::set as described in the C++ standard.
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<> and
//! \c compare<>.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
#endif
class bs_set_impl
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
: public bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, BsTreeAlgorithms, HeaderHolder>
#endif
{
/// @cond
typedef bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, BsTreeAlgorithms, HeaderHolder> tree_type;
BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set_impl)
typedef tree_type implementation_defined;
/// @endcond
public:
typedef typename implementation_defined::value_type value_type;
typedef typename implementation_defined::value_traits value_traits;
typedef typename implementation_defined::pointer pointer;
typedef typename implementation_defined::const_pointer const_pointer;
typedef typename implementation_defined::reference reference;
typedef typename implementation_defined::const_reference const_reference;
typedef typename implementation_defined::difference_type difference_type;
typedef typename implementation_defined::size_type size_type;
typedef typename implementation_defined::value_compare value_compare;
typedef typename implementation_defined::key_compare key_compare;
typedef typename implementation_defined::iterator iterator;
typedef typename implementation_defined::const_iterator const_iterator;
typedef typename implementation_defined::reverse_iterator reverse_iterator;
typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator;
typedef typename implementation_defined::insert_commit_data insert_commit_data;
typedef typename implementation_defined::node_traits node_traits;
typedef typename implementation_defined::node node;
typedef typename implementation_defined::node_ptr node_ptr;
typedef typename implementation_defined::const_node_ptr const_node_ptr;
typedef typename implementation_defined::node_algorithms node_algorithms;
static const bool constant_time_size = tree_type::constant_time_size;
public:
//! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &)
explicit bs_set_impl( const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: tree_type(cmp, v_traits)
{}
//! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &)
template<class Iterator>
bs_set_impl( Iterator b, Iterator e
, const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: tree_type(true, b, e, cmp, v_traits)
{}
//! @copydoc ::boost::intrusive::bstree::bstree(bstree &&)
bs_set_impl(BOOST_RV_REF(bs_set_impl) x)
: tree_type(::boost::move(static_cast<tree_type&>(x)))
{}
//! @copydoc ::boost::intrusive::bstree::operator=(bstree &&)
bs_set_impl& operator=(BOOST_RV_REF(bs_set_impl) x)
{ return static_cast<bs_set_impl&>(tree_type::operator=(::boost::move(static_cast<tree_type&>(x)))); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::~bstree()
~bs_set_impl();
//! @copydoc ::boost::intrusive::bstree::begin()
iterator begin();
//! @copydoc ::boost::intrusive::bstree::begin()const
const_iterator begin() const;
//! @copydoc ::boost::intrusive::bstree::cbegin()const
const_iterator cbegin() const;
//! @copydoc ::boost::intrusive::bstree::end()
iterator end();
//! @copydoc ::boost::intrusive::bstree::end()const
const_iterator end() const;
//! @copydoc ::boost::intrusive::bstree::cend()const
const_iterator cend() const;
//! @copydoc ::boost::intrusive::bstree::rbegin()
reverse_iterator rbegin();
//! @copydoc ::boost::intrusive::bstree::rbegin()const
const_reverse_iterator rbegin() const;
//! @copydoc ::boost::intrusive::bstree::crbegin()const
const_reverse_iterator crbegin() const;
//! @copydoc ::boost::intrusive::bstree::rend()
reverse_iterator rend();
//! @copydoc ::boost::intrusive::bstree::rend()const
const_reverse_iterator rend() const;
//! @copydoc ::boost::intrusive::bstree::crend()const
const_reverse_iterator crend() const;
//! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator)
static bs_set_impl &container_from_end_iterator(iterator end_iterator);
//! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator)
static const bs_set_impl &container_from_end_iterator(const_iterator end_iterator);
//! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator)
static bs_set_impl &container_from_iterator(iterator it);
//! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator)
static const bs_set_impl &container_from_iterator(const_iterator it);
//! @copydoc ::boost::intrusive::bstree::key_comp()const
key_compare key_comp() const;
//! @copydoc ::boost::intrusive::bstree::value_comp()const
value_compare value_comp() const;
//! @copydoc ::boost::intrusive::bstree::empty()const
bool empty() const;
//! @copydoc ::boost::intrusive::bstree::size()const
size_type size() const;
//! @copydoc ::boost::intrusive::bstree::swap
void swap(bs_set_impl& other);
//! @copydoc ::boost::intrusive::bstree::clone_from
template <class Cloner, class Disposer>
void clone_from(const bs_set_impl &src, Cloner cloner, Disposer disposer);
#endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::insert_unique(reference)
std::pair<iterator, bool> insert(reference value)
{ return tree_type::insert_unique(value); }
//! @copydoc ::boost::intrusive::bstree::insert_unique(const_iterator,reference)
iterator insert(const_iterator hint, reference value)
{ return tree_type::insert_unique(hint, value); }
//! @copydoc ::boost::intrusive::bstree::insert_unique_check(const KeyType&,KeyValueCompare,insert_commit_data&)
template<class KeyType, class KeyValueCompare>
std::pair<iterator, bool> insert_check
(const KeyType &key, KeyValueCompare key_value_comp, insert_commit_data &commit_data)
{ return tree_type::insert_unique_check(key, key_value_comp, commit_data); }
//! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const KeyType&,KeyValueCompare,insert_commit_data&)
template<class KeyType, class KeyValueCompare>
std::pair<iterator, bool> insert_check
(const_iterator hint, const KeyType &key
,KeyValueCompare key_value_comp, insert_commit_data &commit_data)
{ return tree_type::insert_unique_check(hint, key, key_value_comp, commit_data); }
//! @copydoc ::boost::intrusive::bstree::insert_unique(Iterator,Iterator)
template<class Iterator>
void insert(Iterator b, Iterator e)
{ tree_type::insert_unique(b, e); }
//! @copydoc ::boost::intrusive::bstree::insert_unique_commit
iterator insert_commit(reference value, const insert_commit_data &commit_data)
{ return tree_type::insert_unique_commit(value, commit_data); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::insert_before
iterator insert_before(const_iterator pos, reference value);
//! @copydoc ::boost::intrusive::bstree::push_back
void push_back(reference value);
//! @copydoc ::boost::intrusive::bstree::push_front
void push_front(reference value);
//! @copydoc ::boost::intrusive::bstree::erase(const_iterator)
iterator erase(const_iterator i);
//! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator)
iterator erase(const_iterator b, const_iterator e);
//! @copydoc ::boost::intrusive::bstree::erase(const_reference)
size_type erase(const_reference value);
//! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
size_type erase(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer)
template<class Disposer>
iterator erase_and_dispose(const_iterator i, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer)
template<class Disposer>
iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer)
template<class Disposer>
size_type erase_and_dispose(const_reference value, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer)
template<class KeyType, class KeyValueCompare, class Disposer>
size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::clear
void clear();
//! @copydoc ::boost::intrusive::bstree::clear_and_dispose
template<class Disposer>
void clear_and_dispose(Disposer disposer);
#endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::count(const_reference)const
size_type count(const_reference value) const
{ return static_cast<size_type>(this->tree_type::find(value) == this->tree_type::cend()); }
//! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
size_type count(const KeyType& key, KeyValueCompare comp) const
{ return static_cast<size_type>(this->tree_type::find(key, comp) == this->tree_type::cend()); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)
iterator lower_bound(const_reference value);
//! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator lower_bound(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const
const_iterator lower_bound(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)
iterator upper_bound(const_reference value);
//! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator upper_bound(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const
const_iterator upper_bound(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::find(const_reference)
iterator find(const_reference value);
//! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator find(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::find(const_reference)const
const_iterator find(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator find(const KeyType& key, KeyValueCompare comp) const;
#endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::rbtree::equal_range(const_reference)
std::pair<iterator,iterator> equal_range(const_reference value)
{ return this->tree_type::lower_bound_range(value); }
//! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
std::pair<iterator,iterator> equal_range(const KeyType& key, KeyValueCompare comp)
{ return this->tree_type::lower_bound_range(key, comp); }
//! @copydoc ::boost::intrusive::rbtree::equal_range(const_reference)const
std::pair<const_iterator, const_iterator>
equal_range(const_reference value) const
{ return this->tree_type::lower_bound_range(value); }
//! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
std::pair<const_iterator, const_iterator>
equal_range(const KeyType& key, KeyValueCompare comp) const
{ return this->tree_type::lower_bound_range(key, comp); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)
std::pair<iterator,iterator> bounded_range
(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed);
//! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)
template<class KeyType, class KeyValueCompare>
std::pair<iterator,iterator> bounded_range
(const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed);
//! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const
std::pair<const_iterator, const_iterator>
bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const;
//! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const
template<class KeyType, class KeyValueCompare>
std::pair<const_iterator, const_iterator> bounded_range
(const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const;
//! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference)
static iterator s_iterator_to(reference value);
//! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference)
static const_iterator s_iterator_to(const_reference value);
//! @copydoc ::boost::intrusive::bstree::iterator_to(reference)
iterator iterator_to(reference value);
//! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const
const_iterator iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::init_node(reference)
static void init_node(reference value);
//! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance
pointer unlink_leftmost_without_rebalance();
//! @copydoc ::boost::intrusive::bstree::replace_node
void replace_node(iterator replace_this, reference with_this);
//! @copydoc ::boost::intrusive::bstree::remove_node
void remove_node(reference value);
#endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
};
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
bool operator!= (const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator>(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator<=(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator>=(const bs_set_impl<T, Options...> &x, const bs_set_impl<T, Options...> &y);
template<class T, class ...Options>
void swap(bs_set_impl<T, Options...> &x, bs_set_impl<T, Options...> &y);
#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
//! Helper metafunction to define a \c bs_set that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
, class O3 = void, class O4 = void
, class O5 = void>
#endif
struct make_bs_set
{
/// @cond
typedef typename pack_options
< bstree_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type packed_options;
typedef typename detail::get_value_traits
<T, typename packed_options::proto_value_traits>::type value_traits;
typedef typename detail::get_header_holder_type
< value_traits, typename packed_options::header_holder_type >::type header_holder_type;
typedef bs_set_impl
< value_traits
, typename packed_options::compare
, typename packed_options::size_type
, packed_options::constant_time_size
, header_holder_type
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5>
#else
template<class T, class ...Options>
#endif
class bs_set
: public make_bs_set<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type
{
typedef typename make_bs_set
<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type Base;
BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_set)
public:
typedef typename Base::value_compare value_compare;
typedef typename Base::value_traits value_traits;
typedef typename Base::iterator iterator;
typedef typename Base::const_iterator const_iterator;
//Assert if passed value traits are compatible with the type
BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value));
explicit bs_set( const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: Base(cmp, v_traits)
{}
template<class Iterator>
bs_set( Iterator b, Iterator e
, const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: Base(b, e, cmp, v_traits)
{}
bs_set(BOOST_RV_REF(bs_set) x)
: Base(::boost::move(static_cast<Base&>(x)))
{}
bs_set& operator=(BOOST_RV_REF(bs_set) x)
{ return static_cast<bs_set &>(this->Base::operator=(::boost::move(static_cast<Base&>(x)))); }
static bs_set &container_from_end_iterator(iterator end_iterator)
{ return static_cast<bs_set &>(Base::container_from_end_iterator(end_iterator)); }
static const bs_set &container_from_end_iterator(const_iterator end_iterator)
{ return static_cast<const bs_set &>(Base::container_from_end_iterator(end_iterator)); }
static bs_set &container_from_iterator(iterator it)
{ return static_cast<bs_set &>(Base::container_from_iterator(it)); }
static const bs_set &container_from_iterator(const_iterator it)
{ return static_cast<const bs_set &>(Base::container_from_iterator(it)); }
};
#endif
//! The class template bs_multiset is an intrusive container, that mimics most of
//! the interface of std::multiset as described in the C++ standard.
//!
//! The template parameter \c T is the type to be managed by the container.
//! The user can specify additional options and if no options are provided
//! default options are used.
//!
//! The container supports the following options:
//! \c base_hook<>/member_hook<>/value_traits<>,
//! \c constant_time_size<>, \c size_type<> and
//! \c compare<>.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
#else
template<class ValueTraits, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
#endif
class bs_multiset_impl
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
: public bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder>
#endif
{
/// @cond
typedef bstree_impl<ValueTraits, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> tree_type;
BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset_impl)
typedef tree_type implementation_defined;
/// @endcond
public:
typedef typename implementation_defined::value_type value_type;
typedef typename implementation_defined::value_traits value_traits;
typedef typename implementation_defined::pointer pointer;
typedef typename implementation_defined::const_pointer const_pointer;
typedef typename implementation_defined::reference reference;
typedef typename implementation_defined::const_reference const_reference;
typedef typename implementation_defined::difference_type difference_type;
typedef typename implementation_defined::size_type size_type;
typedef typename implementation_defined::value_compare value_compare;
typedef typename implementation_defined::key_compare key_compare;
typedef typename implementation_defined::iterator iterator;
typedef typename implementation_defined::const_iterator const_iterator;
typedef typename implementation_defined::reverse_iterator reverse_iterator;
typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator;
typedef typename implementation_defined::insert_commit_data insert_commit_data;
typedef typename implementation_defined::node_traits node_traits;
typedef typename implementation_defined::node node;
typedef typename implementation_defined::node_ptr node_ptr;
typedef typename implementation_defined::const_node_ptr const_node_ptr;
typedef typename implementation_defined::node_algorithms node_algorithms;
static const bool constant_time_size = tree_type::constant_time_size;
public:
//! @copydoc ::boost::intrusive::bstree::bstree(const value_compare &,const value_traits &)
explicit bs_multiset_impl( const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: tree_type(cmp, v_traits)
{}
//! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const value_compare &,const value_traits &)
template<class Iterator>
bs_multiset_impl( Iterator b, Iterator e
, const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: tree_type(false, b, e, cmp, v_traits)
{}
//! @copydoc ::boost::intrusive::bstree::bstree(bstree &&)
bs_multiset_impl(BOOST_RV_REF(bs_multiset_impl) x)
: tree_type(::boost::move(static_cast<tree_type&>(x)))
{}
//! @copydoc ::boost::intrusive::bstree::operator=(bstree &&)
bs_multiset_impl& operator=(BOOST_RV_REF(bs_multiset_impl) x)
{ return static_cast<bs_multiset_impl&>(tree_type::operator=(::boost::move(static_cast<tree_type&>(x)))); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::~bstree()
~bs_multiset_impl();
//! @copydoc ::boost::intrusive::bstree::begin()
iterator begin();
//! @copydoc ::boost::intrusive::bstree::begin()const
const_iterator begin() const;
//! @copydoc ::boost::intrusive::bstree::cbegin()const
const_iterator cbegin() const;
//! @copydoc ::boost::intrusive::bstree::end()
iterator end();
//! @copydoc ::boost::intrusive::bstree::end()const
const_iterator end() const;
//! @copydoc ::boost::intrusive::bstree::cend()const
const_iterator cend() const;
//! @copydoc ::boost::intrusive::bstree::rbegin()
reverse_iterator rbegin();
//! @copydoc ::boost::intrusive::bstree::rbegin()const
const_reverse_iterator rbegin() const;
//! @copydoc ::boost::intrusive::bstree::crbegin()const
const_reverse_iterator crbegin() const;
//! @copydoc ::boost::intrusive::bstree::rend()
reverse_iterator rend();
//! @copydoc ::boost::intrusive::bstree::rend()const
const_reverse_iterator rend() const;
//! @copydoc ::boost::intrusive::bstree::crend()const
const_reverse_iterator crend() const;
//! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator)
static bs_multiset_impl &container_from_end_iterator(iterator end_iterator);
//! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator)
static const bs_multiset_impl &container_from_end_iterator(const_iterator end_iterator);
//! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator)
static bs_multiset_impl &container_from_iterator(iterator it);
//! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator)
static const bs_multiset_impl &container_from_iterator(const_iterator it);
//! @copydoc ::boost::intrusive::bstree::key_comp()const
key_compare key_comp() const;
//! @copydoc ::boost::intrusive::bstree::value_comp()const
value_compare value_comp() const;
//! @copydoc ::boost::intrusive::bstree::empty()const
bool empty() const;
//! @copydoc ::boost::intrusive::bstree::size()const
size_type size() const;
//! @copydoc ::boost::intrusive::bstree::swap
void swap(bs_multiset_impl& other);
//! @copydoc ::boost::intrusive::bstree::clone_from
template <class Cloner, class Disposer>
void clone_from(const bs_multiset_impl &src, Cloner cloner, Disposer disposer);
#endif //#ifdef BOOST_iNTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::insert_equal(reference)
iterator insert(reference value)
{ return tree_type::insert_equal(value); }
//! @copydoc ::boost::intrusive::bstree::insert_equal(const_iterator,reference)
iterator insert(const_iterator hint, reference value)
{ return tree_type::insert_equal(hint, value); }
//! @copydoc ::boost::intrusive::bstree::insert_equal(Iterator,Iterator)
template<class Iterator>
void insert(Iterator b, Iterator e)
{ tree_type::insert_equal(b, e); }
#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
//! @copydoc ::boost::intrusive::bstree::insert_before
iterator insert_before(const_iterator pos, reference value);
//! @copydoc ::boost::intrusive::bstree::push_back
void push_back(reference value);
//! @copydoc ::boost::intrusive::bstree::push_front
void push_front(reference value);
//! @copydoc ::boost::intrusive::bstree::erase(const_iterator)
iterator erase(const_iterator i);
//! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator)
iterator erase(const_iterator b, const_iterator e);
//! @copydoc ::boost::intrusive::bstree::erase(const_reference)
size_type erase(const_reference value);
//! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
size_type erase(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer)
template<class Disposer>
iterator erase_and_dispose(const_iterator i, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer)
template<class Disposer>
iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_reference, Disposer)
template<class Disposer>
size_type erase_and_dispose(const_reference value, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyValueCompare,Disposer)
template<class KeyType, class KeyValueCompare, class Disposer>
size_type erase_and_dispose(const KeyType& key, KeyValueCompare comp, Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::clear
void clear();
//! @copydoc ::boost::intrusive::bstree::clear_and_dispose
template<class Disposer>
void clear_and_dispose(Disposer disposer);
//! @copydoc ::boost::intrusive::bstree::count(const_reference)const
size_type count(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
size_type count(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)
iterator lower_bound(const_reference value);
//! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator lower_bound(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::lower_bound(const_reference)const
const_iterator lower_bound(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator lower_bound(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)
iterator upper_bound(const_reference value);
//! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator upper_bound(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::upper_bound(const_reference)const
const_iterator upper_bound(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator upper_bound(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::find(const_reference)
iterator find(const_reference value);
//! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
iterator find(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::find(const_reference)const
const_iterator find(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
const_iterator find(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)
std::pair<iterator,iterator> equal_range(const_reference value);
//! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)
template<class KeyType, class KeyValueCompare>
std::pair<iterator,iterator> equal_range(const KeyType& key, KeyValueCompare comp);
//! @copydoc ::boost::intrusive::bstree::equal_range(const_reference)const
std::pair<const_iterator, const_iterator>
equal_range(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyValueCompare)const
template<class KeyType, class KeyValueCompare>
std::pair<const_iterator, const_iterator>
equal_range(const KeyType& key, KeyValueCompare comp) const;
//! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)
std::pair<iterator,iterator> bounded_range
(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed);
//! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)
template<class KeyType, class KeyValueCompare>
std::pair<iterator,iterator> bounded_range
(const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed);
//! @copydoc ::boost::intrusive::bstree::bounded_range(const_reference,const_reference,bool,bool)const
std::pair<const_iterator, const_iterator>
bounded_range(const_reference lower_value, const_reference upper_value, bool left_closed, bool right_closed) const;
//! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyValueCompare,bool,bool)const
template<class KeyType, class KeyValueCompare>
std::pair<const_iterator, const_iterator> bounded_range
(const KeyType& lower_key, const KeyType& upper_key, KeyValueCompare comp, bool left_closed, bool right_closed) const;
//! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference)
static iterator s_iterator_to(reference value);
//! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference)
static const_iterator s_iterator_to(const_reference value);
//! @copydoc ::boost::intrusive::bstree::iterator_to(reference)
iterator iterator_to(reference value);
//! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const
const_iterator iterator_to(const_reference value) const;
//! @copydoc ::boost::intrusive::bstree::init_node(reference)
static void init_node(reference value);
//! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance
pointer unlink_leftmost_without_rebalance();
//! @copydoc ::boost::intrusive::bstree::replace_node
void replace_node(iterator replace_this, reference with_this);
//! @copydoc ::boost::intrusive::bstree::remove_node
void remove_node(reference value);
#endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED
};
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
template<class T, class ...Options>
bool operator!= (const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator>(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator<=(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);
template<class T, class ...Options>
bool operator>=(const bs_multiset_impl<T, Options...> &x, const bs_multiset_impl<T, Options...> &y);
template<class T, class ...Options>
void swap(bs_multiset_impl<T, Options...> &x, bs_multiset_impl<T, Options...> &y);
#endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
//! Helper metafunction to define a \c bs_multiset that yields to the same type when the
//! same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void
, class O3 = void, class O4 = void
, class O5 = void>
#endif
struct make_bs_multiset
{
/// @cond
typedef typename pack_options
< bstree_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type packed_options;
typedef typename detail::get_value_traits
<T, typename packed_options::proto_value_traits>::type value_traits;
typedef typename detail::get_header_holder_type
< value_traits, typename packed_options::header_holder_type >::type header_holder_type;
typedef bs_multiset_impl
< value_traits
, typename packed_options::compare
, typename packed_options::size_type
, packed_options::constant_time_size
, header_holder_type
> implementation_defined;
/// @endcond
typedef implementation_defined type;
};
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5>
#else
template<class T, class ...Options>
#endif
class bs_multiset
: public make_bs_multiset<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type
{
typedef typename make_bs_multiset<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4, O5
#else
Options...
#endif
>::type Base;
BOOST_MOVABLE_BUT_NOT_COPYABLE(bs_multiset)
public:
typedef typename Base::value_compare value_compare;
typedef typename Base::value_traits value_traits;
typedef typename Base::iterator iterator;
typedef typename Base::const_iterator const_iterator;
//Assert if passed value traits are compatible with the type
BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value));
explicit bs_multiset( const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: Base(cmp, v_traits)
{}
template<class Iterator>
bs_multiset( Iterator b, Iterator e
, const value_compare &cmp = value_compare()
, const value_traits &v_traits = value_traits())
: Base(b, e, cmp, v_traits)
{}
bs_multiset(BOOST_RV_REF(bs_multiset) x)
: Base(::boost::move(static_cast<Base&>(x)))
{}
bs_multiset& operator=(BOOST_RV_REF(bs_multiset) x)
{ return static_cast<bs_multiset &>(this->Base::operator=(::boost::move(static_cast<Base&>(x)))); }
static bs_multiset &container_from_end_iterator(iterator end_iterator)
{ return static_cast<bs_multiset &>(Base::container_from_end_iterator(end_iterator)); }
static const bs_multiset &container_from_end_iterator(const_iterator end_iterator)
{ return static_cast<const bs_multiset &>(Base::container_from_end_iterator(end_iterator)); }
static bs_multiset &container_from_iterator(iterator it)
{ return static_cast<bs_multiset &>(Base::container_from_iterator(it)); }
static const bs_multiset &container_from_iterator(const_iterator it)
{ return static_cast<const bs_multiset &>(Base::container_from_iterator(it)); }
};
#endif
} //namespace intrusive
} //namespace boost
#include <boost/intrusive/detail/config_end.hpp>
#endif //BOOST_INTRUSIVE_BS_SET_HPP
|
require 'tempfile'
require 'vagrant/util/template_renderer'
module VagrantPlugins
module GuestPhoton
module Cap
class ConfigureNetworks
include Vagrant::Util
def self.configure_networks(machine, networks)
machine.communicate.tap do |comm|
# Read network interface names
interfaces = []
comm.sudo("ifconfig | grep 'eth' | cut -f1 -d' '") do |_, result|
interfaces = result.split("\n")
end
# Configure interfaces
networks.each do |network|
comm.sudo("ifconfig #{interfaces[network[:interface].to_i]} #{network[:ip]} netmask #{network[:netmask]}")
end
primary_machine_config = machine.env.active_machines.first
primary_machine = machine.env.machine(*primary_machine_config, true)
get_ip = lambda do |machine|
ip = nil
machine.config.vm.networks.each do |type, opts|
if type == :private_network && opts[:ip]
ip = opts[:ip]
break
end
end
ip
end
end
end
end
end
end
end
|
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2013 ARM Limited. All rights reserved.
*
* $Date: 17. January 2013
* $Revision: V1.4.1
*
* Project: CMSIS DSP Library
* Title: arm_add_q7.c
*
* Description: Q7 vector addition.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER 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.
* -------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupMath
*/
/**
* @addtogroup BasicAdd
* @{
*/
/**
* @brief Q7 vector addition.
* @param[in] *pSrcA points to the first input vector
* @param[in] *pSrcB points to the second input vector
* @param[out] *pDst points to the output vector
* @param[in] blockSize number of samples in each vector
* @return none.
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function uses saturating arithmetic.
* Results outside of the allowable Q7 range [0x80 0x7F] will be saturated.
*/
void arm_add_q7(
q7_t * pSrcA,
q7_t * pSrcB,
q7_t * pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* loop counter */
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
/*loop Unrolling */
blkCnt = blockSize >> 2u;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while(blkCnt > 0u)
{
/* C = A + B */
/* Add and then store the results in the destination buffer. */
*__SIMD32(pDst)++ = __QADD8(*__SIMD32(pSrcA)++, *__SIMD32(pSrcB)++);
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize % 0x4u;
while(blkCnt > 0u)
{
/* C = A + B */
/* Add and then store the results in the destination buffer. */
*pDst++ = (q7_t) __SSAT(*pSrcA++ + *pSrcB++, 8);
/* Decrement the loop counter */
blkCnt--;
}
#else
/* Run the below code for Cortex-M0 */
/* Initialize blkCnt with number of samples */
blkCnt = blockSize;
while(blkCnt > 0u)
{
/* C = A + B */
/* Add and then store the results in the destination buffer. */
*pDst++ = (q7_t) __SSAT((q15_t) * pSrcA++ + *pSrcB++, 8);
/* Decrement the loop counter */
blkCnt--;
}
#endif /* #ifndef ARM_MATH_CM0_FAMILY */
}
/**
* @} end of BasicAdd group
*/
|
import "../arrays/merge";
import "../core/rebind";
import "layout";
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort,
children = d3_layout_hierarchyChildren,
value = d3_layout_hierarchyValue;
// Recursively compute the node depth and value.
// Also converts to a standard hierarchy structure.
function recurse(node, depth, nodes) {
var childs = children.call(hierarchy, node, depth);
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1,
n,
c = node.children = [],
v = 0,
j = depth + 1,
d;
while (++i < n) {
d = recurse(childs[i], j, nodes);
d.parent = node;
c.push(d);
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else if (value) {
node.value = +value.call(hierarchy, node, depth) || 0;
}
return node;
}
// Recursively re-evaluates the node value.
function revalue(node, depth) {
var children = node.children,
v = 0;
if (children && (n = children.length)) {
var i = -1,
n,
j = depth + 1;
while (++i < n) v += revalue(children[i], j);
} else if (value) {
v = +value.call(hierarchy, node, depth) || 0;
}
if (value) node.value = v;
return v;
}
function hierarchy(d) {
var nodes = [];
recurse(d, 0, nodes);
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
// Re-evaluates the `value` property for the specified hierarchy.
hierarchy.revalue = function(root) {
revalue(root, 0);
return root;
};
return hierarchy;
};
// A method assignment helper for hierarchy subclasses.
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
// Add an alias for nodes and links, for convenience.
object.nodes = object;
object.links = d3_layout_hierarchyLinks;
return object;
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
// Returns an array source+target objects for the specified nodes.
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {source: parent, target: child};
});
}));
}
|
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.Hadoop.Avro.Schema
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
// Schema Resolution. Citation from the Avro specification:
// A reader of Avro data, whether from an RPC or a file, can always parse that data because its schema is provided. But that
// schema may not be exactly the schema that was expected. For example, if the data was written with a different version of the software than it is read,
// then records may have had fields added or removed. This section specifies how such schema differences should be resolved.
// We call the schema used to write the data as the writer's schema, and the schema that the application expects the reader's schema.
// Differences between these should be resolved as follows:
// • It is an error if the two schemas do not match.
// To match, one of the following must hold:
// ◦both schemas have same primitive type
// ◦the writer's schema may be promoted to the reader's as follows:
// ◾int is promotable to long, float, or double
// ◾long is promotable to float or double
// ◾float is promotable to double
// ◦both schemas are arrays whose item types match
// ◦both schemas are maps whose value types match
// ◦both schemas are enums whose names match
// ◦both schemas are fixed whose sizes and names match
// ◦both schemas are records with the same name
// ◦either schema is a union
// • if both are records:
// ◦the ordering of fields may be different: fields are matched by name.
// ◦schemas for fields with the same name in both records are resolved recursively.
// ◦if the writer's record contains a field with a name not present in the reader's record, the writer's value for that field is ignored.
// ◦if the reader's record schema has a field that contains a default value, and writer's schema does not have a field with the same name,
// then the reader should use the default value from its field.
// ◦if the reader's record schema has a field with no default value, and writer's schema does not have a field with the same name, an error is signalled.
// • if both are enums:
// if the writer's symbol is not present in the reader's enum, then an error is signalled.
// • if both are arrays:
// This resolution algorithm is applied recursively to the reader's and writer's array item schemas.
// • if both are maps:
// This resolution algorithm is applied recursively to the reader's and writer's value schemas.
// • if both are unions:
// The first schema in the reader's union that matches the selected writer's union schema is recursively resolved against it. if none match,
// an error is signalled.
// • if reader's is a union, but writer's is not
// The first schema in the reader's union that matches the writer's schema is recursively resolved against it. If none match, an error is signalled.
// • if writer's is a union, but reader's is not
// If the reader's schema matches the selected writer's schema, it is recursively resolved against it. If they do not match, an error is signalled.
// A schema's "doc" fields are ignored for the purposes of schema resolution. Hence, the "doc" portion of a schema may be dropped at serialization.
/// <summary>
/// Matches the schema of writer to the schema of writer.
/// </summary>
internal sealed class EvolutionSchemaBuilder
{
private readonly Dictionary<TypeSchema, TypeSchema> visited = new Dictionary<TypeSchema, TypeSchema>();
public TypeSchema Build(TypeSchema w, TypeSchema r)
{
this.visited.Clear();
return this.BuildDynamic(w, r);
}
/// <summary>
/// Implements double dispatch.
/// </summary>
/// <param name="w">The writer schema.</param>
/// <param name="r">The reader schema.</param>
/// <returns>True if match.</returns>
private TypeSchema BuildDynamic(TypeSchema w, TypeSchema r)
{
return this.BuildCore((dynamic)w, (dynamic)r);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(IntSchema w, IntSchema r)
{
return new IntSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(BooleanSchema w, BooleanSchema r)
{
return new BooleanSchema();
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(BytesSchema w, BytesSchema r)
{
return new BytesSchema();
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(DoubleSchema w, DoubleSchema r)
{
return new DoubleSchema();
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(FloatSchema w, FloatSchema r)
{
return new FloatSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(LongSchema w, LongSchema r)
{
return new LongSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(StringSchema w, StringSchema r)
{
return new StringSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(IntSchema w, LongSchema r)
{
return new IntSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(IntSchema w, FloatSchema r)
{
return new IntSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(IntSchema w, DoubleSchema r)
{
return new IntSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(LongSchema w, FloatSchema r)
{
return new LongSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(LongSchema w, DoubleSchema r)
{
return new LongSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(FloatSchema w, DoubleSchema r)
{
return new FloatSchema(r.RuntimeType);
}
private TypeSchema BuildCore(ArraySchema w, ArraySchema r)
{
TypeSchema itemSchema = this.BuildDynamic(w.ItemSchema, r.ItemSchema);
return itemSchema != null
? new ArraySchema(itemSchema, r.RuntimeType)
: null;
}
private TypeSchema BuildCore(MapSchema w, MapSchema r)
{
TypeSchema valueSchema = this.BuildDynamic(w.ValueSchema, r.ValueSchema);
TypeSchema keySchema = this.BuildDynamic(w.KeySchema, r.KeySchema);
return valueSchema != null && keySchema != null
? new MapSchema(keySchema, valueSchema, r.RuntimeType)
: null;
}
private TypeSchema BuildCore(EnumSchema w, EnumSchema r)
{
bool match = this.DoNamesMatch(w, r)
&& w.Symbols.Select((s, i) => i < r.Symbols.Count && r.Symbols[i] == s).All(m => m);
if (!match)
{
return null;
}
if (this.visited.ContainsKey(w))
{
return this.visited[w];
}
var attr = new NamedEntityAttributes(new SchemaName(w.Name, w.Namespace), w.Aliases, w.Doc);
var schema = new EnumSchema(attr, r.RuntimeType);
r.Symbols.Where(s => !schema.Symbols.Contains(s)).ToList().ForEach(schema.AddSymbol);
this.visited.Add(w, schema);
return schema;
}
private TypeSchema BuildCore(FixedSchema w, FixedSchema r)
{
bool match = this.DoNamesMatch(w, r) && w.Size == r.Size;
if (!match)
{
return null;
}
if (this.visited.ContainsKey(w))
{
return this.visited[w];
}
var attr = new NamedEntityAttributes(new SchemaName(w.Name, w.Namespace), w.Aliases, w.Doc);
var schema = new FixedSchema(attr, w.Size, r.RuntimeType);
this.visited.Add(w, schema);
return schema;
}
private TypeSchema BuildCore(RecordSchema w, RecordSchema r)
{
if (!this.DoNamesMatch(w, r))
{
return null;
}
if (this.visited.ContainsKey(w))
{
return this.visited[w];
}
var schema = new RecordSchema(
new NamedEntityAttributes(new SchemaName(w.Name, w.Namespace), w.Aliases, w.Doc),
r.RuntimeType);
this.visited.Add(w, schema);
var fields = this.BuildWriterFields(w, r);
fields.AddRange(this.BuildReaderFields(w, r, fields.Count));
fields.Sort((f1, f2) => f1.Position.CompareTo(f2.Position));
fields.ForEach(schema.AddField);
return schema;
}
private List<RecordField> BuildReaderFields(RecordSchema w, RecordSchema r, int startPosition)
{
var readerFieldsWithDefault = r.Fields.Where(field => field.HasDefaultValue);
var fieldsToAdd = new List<RecordField>();
foreach (var readerField in readerFieldsWithDefault)
{
if (!w.Fields.Any(f => this.DoNamesMatch(f, readerField)))
{
var newField = new RecordField(
readerField.NamedEntityAttributes,
readerField.TypeSchema,
readerField.Order,
readerField.HasDefaultValue,
readerField.DefaultValue,
readerField.MemberInfo,
startPosition++)
{
UseDefaultValue = true
};
fieldsToAdd.Add(newField);
}
}
if (r.RuntimeType == typeof(AvroRecord) &&
r.Fields.Any(rf => !rf.HasDefaultValue && !w.Fields.Any(wf => this.DoNamesMatch(wf, rf))))
{
throw new SerializationException(
string.Format(
CultureInfo.InvariantCulture,
"Fields without default values found in type '{0}'. Not corresponding writer fields found.",
r.RuntimeType));
}
return fieldsToAdd;
}
/// <summary>
/// Matches if the writer's record contains a field with a name not present in the reader's record, the writer's value for that field is ignored.
/// </summary>
/// <param name="w">The writer schema.</param>
/// <param name="r">The reader schema.</param>
/// <returns>True if match.</returns>
private List<RecordField> BuildWriterFields(RecordSchema w, RecordSchema r)
{
var fields = new List<RecordField>();
var writerFields = w.Fields.OrderBy(f => f.FullName);
foreach (var writerField in writerFields)
{
writerField.ShouldBeSkipped = true;
RecordField readerField = r.Fields.SingleOrDefault(f => this.DoNamesMatch(writerField, f));
RecordField newField = null;
if (readerField != null)
{
var schema = this.BuildDynamic(writerField.TypeSchema, readerField.TypeSchema);
if (schema == null)
{
throw new SerializationException(
string.Format(
CultureInfo.InvariantCulture,
"Field '{0}' in type '{1}' does not match the reader field.",
writerField.Name,
w.RuntimeType));
}
newField = new RecordField(
writerField.NamedEntityAttributes,
schema,
writerField.Order,
writerField.HasDefaultValue,
writerField.DefaultValue,
readerField.MemberInfo,
writerField.Position)
{
ShouldBeSkipped = false
};
}
else
{
newField = new RecordField(
writerField.NamedEntityAttributes,
writerField.TypeSchema,
writerField.Order,
writerField.HasDefaultValue,
writerField.DefaultValue,
writerField.MemberInfo,
writerField.Position)
{
ShouldBeSkipped = true
};
}
fields.Add(newField);
}
return fields;
}
private TypeSchema BuildCore(UnionSchema w, UnionSchema r)
{
var unionSchemas = new List<TypeSchema>();
foreach (var writerSchema in w.Schemas)
{
TypeSchema schema = null;
foreach (var readerSchema in r.Schemas)
{
schema = this.BuildDynamic(writerSchema, readerSchema);
if (schema != null)
{
break;
}
}
if (schema == null)
{
return null;
}
unionSchemas.Add(schema);
}
return new UnionSchema(unionSchemas, r.RuntimeType);
}
/// <summary>
/// If reader's is a union, but writer's is not the first schema in the reader's union
/// that matches the writer's schema is recursively resolved against it. If none match, an error is signalled.
/// </summary>
/// <param name="w">The writer schema.</param>
/// <param name="r">The reader schema.</param>
/// <returns>True if match.</returns>
private TypeSchema BuildCore(TypeSchema w, UnionSchema r)
{
return r.Schemas.Select(rs => this.BuildDynamic(w, rs)).SingleOrDefault(s => s != null);
}
/// <summary>
/// If writer's is a union, but reader's is not then
/// if the reader's schema matches the selected writer's schema, it is recursively resolved against it. If they do not match, an error is signalled.
/// </summary>
/// <param name="w">The writer schema.</param>
/// <param name="r">The reader schema.</param>
/// <returns>True if match.</returns>
private TypeSchema BuildCore(UnionSchema w, TypeSchema r)
{
var schemas = new List<TypeSchema>();
TypeSchema schemaToReplace = null;
TypeSchema newSchema = null;
foreach (var ws in w.Schemas)
{
newSchema = this.BuildDynamic(ws, r);
if (newSchema != null)
{
schemaToReplace = ws;
break;
}
}
if (newSchema == null)
{
throw new SerializationException("Cannot match the union schema.");
}
foreach (var s in w.Schemas)
{
schemas.Add(s == schemaToReplace ? newSchema : s);
}
return new UnionSchema(schemas, newSchema.RuntimeType);
}
private TypeSchema BuildCore(TypeSchema w, NullableSchema r)
{
var schema = this.BuildDynamic(w, r.ValueSchema);
return schema != null
? new NullableSchema(r.RuntimeType, schema)
: null;
}
private TypeSchema BuildCore(TypeSchema w, SurrogateSchema r)
{
var schema = this.BuildDynamic(w, r.Surrogate);
return schema != null
? new SurrogateSchema(r.RuntimeType, r.SurrogateType, r.Surrogate)
: null;
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Double dispatch.")]
private TypeSchema BuildCore(NullSchema w, NullSchema r)
{
return new NullSchema(r.RuntimeType);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters",
Justification = "The method is used for double dispatch.")]
private TypeSchema BuildCore(object w, object r)
{
return null;
}
private bool DoNamesMatch(NamedSchema w, NamedSchema r)
{
return r.FullName == w.FullName || r.Aliases.Contains(w.FullName);
}
private bool DoNamesMatch(RecordField w, RecordField r)
{
return r.FullName == w.FullName || r.Aliases.Contains(w.FullName);
}
}
}
|
/*! (C) WebReflection Mit Style License */
(function(e,t,n){if(n in e)return;var r=0,i=e.clearTimeout,s=e.setTimeout,o=Element.prototype,u=t.getOwnPropertyDescriptor,a=t.defineProperty,f=function(){document.dispatchEvent(new CustomEvent("readystatechange"))},l=function(e,t){i(r),r=s(f,10)},c=function(e){var t=u(o,e),n={configurable:t.configurable,enumerable:t.enumerable,get:function(){return t.get.call(this)},set:function(r){delete o[e],this[e]=r,a(o,e,n),l(this)}};a(o,e,n)},h=function(e){var t=u(o,e),n=t.value;t.value=function(){var e=n.apply(this,arguments);return l(this),e},a(o,e,t)};c("innerHTML"),c("innerText"),c("outerHTML"),c("outerText"),c("textContent"),h("appendChild"),h("applyElement"),h("insertAdjacentElement"),h("insertAdjacentHTML"),h("insertAdjacentText"),h("insertBefore"),h("insertData"),h("replaceAdjacentText"),h("replaceChild"),h("removeChild"),e[n]=Element})(window,Object,"HTMLElement"); |
{{#markdown}}
```scss
// We use this to control the maximum blocks and spacing
$block-grid-elements: 12;
$block-grid-default-spacing: rem-calc(20);
$align-block-grid-to-grid: false; //removes column gutter so edges of block grid align with grid
// Enables media queries for block-grid classes. Set to false if writing semantic HTML.
$block-grid-media-queries: true;
```
{{/markdown}} |
require "minitest/autorun"
require "fog"
require "fog/bin"
require "helpers/bin"
describe Google do
include Fog::BinSpec
let(:subject) { Google }
end
|
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: 16kHz settings
********************************************************************/
#include "psych_16.h"
#include "residue_16.h"
static const int blocksize_16_short[3]={
1024,512,512
};
static const int blocksize_16_long[3]={
1024,1024,1024
};
static const int _floor_mapping_16a[]={
9,3,3
};
static const int _floor_mapping_16b[]={
9,9,9
};
static const int *_floor_mapping_16[]={
_floor_mapping_16a,
_floor_mapping_16b
};
static const double rate_mapping_16[4]={
12000.,20000.,44000.,86000.
};
static const double rate_mapping_16_uncoupled[4]={
16000.,28000.,64000.,100000.
};
static const double _global_mapping_16[4]={ 1., 2., 3., 4. };
static const double quality_mapping_16[4]={ -.1,.05,.5,1. };
static const double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
static const ve_setup_data_template ve_setup_16_stereo={
3,
rate_mapping_16,
quality_mapping_16,
2,
15000,
19000,
blocksize_16_short,
blocksize_16_long,
_psy_tone_masteratt_16,
_psy_tone_0dB,
_psy_tone_suppress,
_vp_tonemask_adj_16,
_vp_tonemask_adj_16,
_vp_tonemask_adj_16,
_psy_noiseguards_16,
_psy_noisebias_16_impulse,
_psy_noisebias_16_short,
_psy_noisebias_16_short,
_psy_noisebias_16,
_psy_noise_suppress,
_psy_compand_8,
_psy_compand_16_mapping,
_psy_compand_16_mapping,
{_noise_start_16,_noise_start_16},
{ _noise_part_16, _noise_part_16},
_noise_thresh_16,
_psy_ath_floater_16,
_psy_ath_abs_16,
_psy_lowpass_16,
_psy_global_44,
_global_mapping_16,
_psy_stereo_modes_16,
_floor_books,
_floor,
2,
_floor_mapping_16,
_mapres_template_16_stereo
};
static const ve_setup_data_template ve_setup_16_uncoupled={
3,
rate_mapping_16_uncoupled,
quality_mapping_16,
-1,
15000,
19000,
blocksize_16_short,
blocksize_16_long,
_psy_tone_masteratt_16,
_psy_tone_0dB,
_psy_tone_suppress,
_vp_tonemask_adj_16,
_vp_tonemask_adj_16,
_vp_tonemask_adj_16,
_psy_noiseguards_16,
_psy_noisebias_16_impulse,
_psy_noisebias_16_short,
_psy_noisebias_16_short,
_psy_noisebias_16,
_psy_noise_suppress,
_psy_compand_8,
_psy_compand_16_mapping,
_psy_compand_16_mapping,
{_noise_start_16,_noise_start_16},
{ _noise_part_16, _noise_part_16},
_noise_thresh_16,
_psy_ath_floater_16,
_psy_ath_abs_16,
_psy_lowpass_16,
_psy_global_44,
_global_mapping_16,
_psy_stereo_modes_16,
_floor_books,
_floor,
2,
_floor_mapping_16,
_mapres_template_16_uncoupled
};
|
/*
* pervasive backend for the cbe_cpufreq driver
*
* This driver makes use of the pervasive unit to
* engage the desired frequency.
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005-2007
*
* Author: Christian Krafft <krafft@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <asm/machdep.h>
#include <asm/hw_irq.h>
#include <asm/cell-regs.h>
#include "cbe_cpufreq.h"
/* to write to MIC register */
static u64 MIC_Slow_Fast_Timer_table[] = {
[0 ... 7] = 0x007fc00000000000ull,
};
/* more values for the MIC */
static u64 MIC_Slow_Next_Timer_table[] = {
0x0000240000000000ull,
0x0000268000000000ull,
0x000029C000000000ull,
0x00002D0000000000ull,
0x0000300000000000ull,
0x0000334000000000ull,
0x000039C000000000ull,
0x00003FC000000000ull,
};
int cbe_cpufreq_set_pmode(int cpu, unsigned int pmode)
{
struct cbe_pmd_regs __iomem *pmd_regs;
struct cbe_mic_tm_regs __iomem *mic_tm_regs;
u64 flags;
u64 value;
#ifdef DEBUG
long time;
#endif
local_irq_save(flags);
mic_tm_regs = cbe_get_cpu_mic_tm_regs(cpu);
pmd_regs = cbe_get_cpu_pmd_regs(cpu);
#ifdef DEBUG
time = jiffies;
#endif
out_be64(&mic_tm_regs->slow_fast_timer_0, MIC_Slow_Fast_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_fast_timer_1, MIC_Slow_Fast_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_next_timer_0, MIC_Slow_Next_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_next_timer_1, MIC_Slow_Next_Timer_table[pmode]);
value = in_be64(&pmd_regs->pmcr);
/* set bits to zero */
value &= 0xFFFFFFFFFFFFFFF8ull;
/* set bits to next pmode */
value |= pmode;
out_be64(&pmd_regs->pmcr, value);
#ifdef DEBUG
/* wait until new pmode appears in status register */
value = in_be64(&pmd_regs->pmsr) & 0x07;
while (value != pmode) {
cpu_relax();
value = in_be64(&pmd_regs->pmsr) & 0x07;
}
time = jiffies - time;
time = jiffies_to_msecs(time);
pr_debug("had to wait %lu ms for a transition using " \
"pervasive unit\n", time);
#endif
local_irq_restore(flags);
return 0;
}
int cbe_cpufreq_get_pmode(int cpu)
{
int ret;
struct cbe_pmd_regs __iomem *pmd_regs;
pmd_regs = cbe_get_cpu_pmd_regs(cpu);
ret = in_be64(&pmd_regs->pmsr) & 0x07;
return ret;
}
|
- Invoice Outstanding calculation fixed related to advance
- Show Close button only for users with Submit rights and for Delivery Note and Purchase Receipt, only if it is returned
- Don't show Receive for a Purchase Order having non-stock items
- Leave Allocation, Application and Balance report cleanup and fixes |
-- !!! Test seeking
import System.IO
main = do
h <- openFile "hSeek001.in" ReadMode
True <- hIsSeekable h
hSeek h SeekFromEnd (-1)
z <- hGetChar h
putStr (z:"\n")
hSeek h SeekFromEnd (-3)
x <- hGetChar h
putStr (x:"\n")
hSeek h RelativeSeek (-2)
w <- hGetChar h
putStr (w:"\n")
hSeek h RelativeSeek 2
z <- hGetChar h
putStr (z:"\n")
hSeek h AbsoluteSeek (0)
a <- hGetChar h
putStr (a:"\n")
hSeek h AbsoluteSeek (10)
k <- hGetChar h
putStr (k:"\n")
hSeek h AbsoluteSeek (25)
z <- hGetChar h
putStr (z:"\n")
hClose h
|
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6347716
* @summary Test TypeKind.isPrimitive
* @author Joseph D. Darcy
*/
import javax.lang.model.type.TypeKind;
import static javax.lang.model.type.TypeKind.*;
import javax.lang.model.util.*;
import java.util.*;
public class TestTypeKind {
static int testIsPrimitive() {
int failures = 0;
// The eight primitive types
Set<TypeKind> primitives = EnumSet.of(BOOLEAN, // 1
BYTE, // 2
CHAR, // 3
DOUBLE, // 4
FLOAT, // 5
INT, // 6
LONG, // 7
SHORT); // 8
for(TypeKind tk : TypeKind.values()) {
boolean primitiveness;
if ((primitiveness=tk.isPrimitive()) != primitives.contains(tk) ) {
failures++;
System.err.println("Unexpected isPrimitive value " + primitiveness +
"for " + tk);
}
}
return failures;
}
public static void main(String... argv) {
int failures = 0;
failures += testIsPrimitive();
if (failures > 0)
throw new RuntimeException();
}
}
|
# SPDX-License-Identifier: GPL-2.0-only
CFLAGS += -iquote../../../../include/uapi -Wall
TEST_GEN_PROGS := get_syscall_info peeksiginfo
include ../lib.mk
|
/*
YUI 3.4.1 (build 4118)
Copyright 2011 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('oop', function(Y) {
/**
Adds object inheritance and manipulation utilities to the YUI instance. This
module is required by most YUI components.
@module oop
**/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = '_~yuim~_',
hasOwn = OP.hasOwnProperty,
toString = OP.toString;
function dispatch(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
}
/**
Augments the _receiver_ with prototype properties from the _supplier_. The
receiver may be a constructor function or an object. The supplier must be a
constructor function.
If the _receiver_ is an object, then the _supplier_ constructor will be called
immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
If the _receiver_ is a constructor function, then all prototype methods of
_supplier_ that are copied to _receiver_ will be sequestered, and the
_supplier_ constructor will not be called immediately. The first time any
sequestered method is called on the _receiver_'s prototype, all sequestered
methods will be immediately copied to the _receiver_'s prototype, the
_supplier_'s constructor will be executed, and finally the newly unsequestered
method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes
it cheap to perform frequent augmentation by ensuring that suppliers'
constructors are only called if a supplied method is actually used. If none of
the supplied methods is ever used, then there's no need to take the performance
hit of calling the _supplier_'s constructor.
@method augment
@param {Function|Object} receiver Object or function to be augmented.
@param {Function} supplier Function that supplies the prototype properties with
which to augment the _receiver_.
@param {Boolean} [overwrite=false] If `true`, properties already on the receiver
will be overwritten if found on the supplier's prototype.
@param {String[]} [whitelist] An array of property names. If specified,
only the whitelisted prototype properties will be applied to the receiver, and
all others will be ignored.
@param {Array|any} [args] Argument or array of arguments to pass to the
supplier's constructor when initializing.
@return {Function} Augmented object.
@for YUI
**/
Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
var rProto = receiver.prototype,
sequester = rProto && supplier,
sProto = supplier.prototype,
to = rProto || receiver,
copy,
newPrototype,
replacements,
sequestered,
unsequester;
args = args ? Y.Array(args) : [];
if (sequester) {
newPrototype = {};
replacements = {};
sequestered = {};
copy = function (value, key) {
if (overwrite || !(key in rProto)) {
if (toString.call(value) === '[object Function]') {
sequestered[key] = value;
newPrototype[key] = replacements[key] = function () {
return unsequester(this, value, arguments);
};
} else {
newPrototype[key] = value;
}
}
};
unsequester = function (instance, fn, fnArgs) {
// Unsequester all sequestered functions.
for (var key in sequestered) {
if (hasOwn.call(sequestered, key)
&& instance[key] === replacements[key]) {
instance[key] = sequestered[key];
}
}
// Execute the supplier constructor.
supplier.apply(instance, args);
// Finally, execute the original sequestered function.
return fn.apply(instance, fnArgs);
};
if (whitelist) {
Y.Array.each(whitelist, function (name) {
if (name in sProto) {
copy(sProto[name], name);
}
});
} else {
Y.Object.each(sProto, copy, null, true);
}
}
Y.mix(to, newPrototype || sProto, overwrite, whitelist);
if (!sequester) {
supplier.apply(to, args);
}
return receiver;
};
/**
* Applies object properties from the supplier to the receiver. If
* the target has the property, and the property is an object, the target
* object will be augmented with the supplier's value. If the property
* is an array, the suppliers value will be appended to the target.
* @method aggregate
* @param {function} r the object to receive the augmentation.
* @param {function} s the object that supplies the properties to augment.
* @param {boolean} ov if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param {string[]} wl a whitelist. If supplied, only properties in
* this list will be applied to the receiver.
* @return {object} the extended object.
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {function} r the object to modify.
* @param {function} s the object to inherit.
* @param {object} px prototype properties to add/override.
* @param {object} sx static properties to add/override.
* @return {object} the extended object.
*/
Y.extend = function(r, s, px, sx) {
if (!s || !r) {
Y.error('extend failed, verify dependencies');
}
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* NodeLists
* @method each
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {YUI} the YUI instance.
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'each');
};
/**
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* NodeLists.
* @method some
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {boolean} true if the function ever returns true,
* false otherwise.
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'some');
};
/**
* Deep object/array copy. Function clones are actually
* wrappers around the original function.
* Array-like objects are treated as arrays.
* Primitives are returned untouched. Optionally, a
* function can be provided to handle other data types,
* filter keys, validate values, etc.
*
* @method clone
* @param {object} o what to clone.
* @param {boolean} safe if true, objects will not have prototype
* items from the source. If false, they will. In this case, the
* original is initially protected, but the clone is not completely
* immune from changes to the source object prototype. Also, cloned
* prototype items that are deleted from the clone will result
* in the value of the source prototype being exposed. If operating
* on a non-safe clone, items should be nulled out rather than deleted.
* @param {function} f optional function to apply to each item in a
* collection; it will be executed prior to applying the value to
* the new object. Return false to prevent the copy.
* @param {object} c optional execution context for f.
* @param {object} owner Owner object passed when clone is iterating
* an object. Used to set up context for cloned functions.
* @param {object} cloned hash of previously cloned objects to avoid
* multiple clones.
* @return {Array|Object} the cloned object.
*/
Y.clone = function(o, safe, f, c, owner, cloned) {
if (!L.isObject(o)) {
return o;
}
// @todo cloning YUI instances doesn't currently work
if (Y.instanceOf(o, YUI)) {
return o;
}
var o2, marked = cloned || {}, stamp,
yeach = Y.each;
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// if we do this we need to set the flags too
// return new RegExp(o.source);
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
// #2528250 don't try to clone element properties
if (!o.addEventListener && !o.attachEvent) {
yeach(o, function(v, k) {
if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] =
Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
}
if (!cloned) {
Y.Object.each(marked, function(v, k) {
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
v[CLONE_MARKER] = null;
}
}
}, this);
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function.
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ?
Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to append to the end of
* arguments collection supplied to the function.
* @return {function} the wrapped function.
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, '3.4.1' ,{requires:['yui-base']});
|
@{
ModuleVersion = '1.0.1'
GUID = '80c895c4-de3f-4d6d-8fa4-c504c96b6f22'
Author = 'Ansible'
CompanyName = 'Ansible'
Copyright = '(c) 2019'
Description = 'Test DSC Resource for Ansible integration tests'
PowerShellVersion = '5.0'
CLRVersion = '4.0'
FunctionsToExport = '*'
CmdletsToExport = '*'
}
|
// Copyright David Abrahams 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef ARG_FROM_PYTHON_DWA2002128_HPP
# define ARG_FROM_PYTHON_DWA2002128_HPP
# include <boost/python/detail/prefix.hpp>
# include <boost/python/converter/arg_from_python.hpp>
# if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \
|| BOOST_WORKAROUND(BOOST_INTEL_WIN, BOOST_TESTED_AT(800))
# include <boost/type_traits/remove_cv.hpp>
#endif
namespace boost { namespace python {
template <class T>
struct arg_from_python
: converter::select_arg_from_python<
# if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \
|| BOOST_WORKAROUND(BOOST_INTEL_WIN, BOOST_TESTED_AT(800))
typename boost::remove_cv<T>::type
# else
T
# endif
>::type
{
typedef typename converter::select_arg_from_python<
# if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \
|| BOOST_WORKAROUND(BOOST_INTEL_WIN, BOOST_TESTED_AT(800))
typename boost::remove_cv<T>::type
# else
T
# endif
>::type base;
arg_from_python(PyObject*);
};
// specialization for PyObject*
template <>
struct arg_from_python<PyObject*>
{
typedef PyObject* result_type;
arg_from_python(PyObject* p) : m_source(p) {}
bool convertible() const { return true; }
PyObject* operator()() const { return m_source; }
private:
PyObject* m_source;
};
template <>
struct arg_from_python<PyObject* const&>
{
typedef PyObject* const& result_type;
arg_from_python(PyObject* p) : m_source(p) {}
bool convertible() const { return true; }
PyObject*const& operator()() const { return m_source; }
private:
PyObject* m_source;
};
//
// implementations
//
template <class T>
inline arg_from_python<T>::arg_from_python(PyObject* source)
: base(source)
{
}
}} // namespace boost::python
#endif // ARG_FROM_PYTHON_DWA2002128_HPP
|
<html>
<body>
This inspection reports libraries attached to the specified inspection scope that
are not used directly from code. <br> <br>
</body>
</html>
|
/*
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.parsers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.security.zynamics.binnavi.Database.CTableNames;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Interfaces.SQLProvider;
import com.google.security.zynamics.binnavi.Database.MockClasses.MockSqlProvider;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.containers.ViewNotificationContainer;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.Notifications.parsers.PostgreSQLViewNotificationParser;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.INaviProject;
import com.google.security.zynamics.binnavi.disassembly.MockProject;
import com.google.security.zynamics.binnavi.disassembly.MockView;
import com.google.security.zynamics.binnavi.disassembly.Modules.MockModule;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.zylib.disassembly.ViewType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.postgresql.PGNotification;
import java.util.ArrayList;
import java.util.Collection;
@RunWith(JUnit4.class)
public class PostgreSQLViewNotificationParserTest {
private final SQLProvider provider = new MockSqlProvider();
private final INaviView view = MockView.getFullView(provider, ViewType.NonNative, null);
private final Collection<PGNotification> notifications = new ArrayList<PGNotification>();
private void testParser(final String table, final String databaseOperation, final String viewId,
final String containerId) {
final String NOTIFICATION =
containerId != null ? table + " " + databaseOperation + " " + viewId + " " + containerId
: table + " " + databaseOperation + " " + viewId;
notifications.add(new MockPGNotification("view_changes", NOTIFICATION));
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
final Collection<ViewNotificationContainer> result = parser.parse(notifications, provider);
assertNotNull(result);
assertTrue(!result.isEmpty());
assertTrue(result.size() == 1);
final ViewNotificationContainer container = Iterables.getFirst(result, null);
assertNotNull(container);
assertEquals(databaseOperation, container.getDatabaseOperation());
assertEquals(viewId, container.getViewId().toString());
if (containerId != null) {
assertEquals(containerId, container.getNotificationObjectId().get().toString());
}
}
@Test
public void testModuleViewParsing1() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "INSERT",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testModuleViewParsing2() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "UPDATE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testModuleViewParsing3() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing4() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "XXXXXX",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing5() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE", "0xDEADBEEF", "1");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing6() {
testParser(CTableNames.MODULE_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "XXXX");
}
@Test(expected = IllegalStateException.class)
public void testModuleViewParsing7() {
testParser("bn_module_view", "INSERT", String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing1() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "INSERT",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing2() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "UPDATE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test
public void testProjectViewParsing3() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing4() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "XXXXXX",
String.valueOf(view.getConfiguration().getId()), "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing5() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE", "0xDEADBEEF", "1");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing6() {
testParser(CTableNames.PROJECT_VIEWS_TABLE, "DELETE",
String.valueOf(view.getConfiguration().getId()), "XXXX");
}
@Test(expected = IllegalStateException.class)
public void testProjectViewParsing7() {
testParser("bn_project_view", "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing1() {
testParser(
CTableNames.VIEWS_TABLE, "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing2() {
testParser(
CTableNames.VIEWS_TABLE, "UPDATE", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewParsing3() {
testParser(
CTableNames.VIEWS_TABLE, "DELETE", String.valueOf(view.getConfiguration().getId()), null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing4() {
testParser(
CTableNames.VIEWS_TABLE, "XXXXXX", String.valueOf(view.getConfiguration().getId()), null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing5() {
testParser(CTableNames.VIEWS_TABLE, "DELETE", "0xDEADBEEF", null);
}
@Test(expected = IllegalStateException.class)
public void testViewParsing7() {
testParser("bn_view", "INSERT", String.valueOf(view.getConfiguration().getId()), null);
}
@Test
public void testViewInform0() throws CouldntLoadDataException {
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testViewInform1() throws CouldntLoadDataException {
final String description2 = "TEST DESCRIPTION STATE CHANGE";
view.getConfiguration().setDescriptionInternal(description2);
assertEquals(description2, view.getConfiguration().getDescription());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals("DB PROJECT VIEW DESCRIPTION", view.getConfiguration().getDescription());
}
@Test
public void testViewInform2() throws CouldntLoadDataException {
final String name2 = "TEST NAME STATE CHANGE";
view.getConfiguration().setNameInternal(name2);
assertEquals(name2, view.getConfiguration().getName());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals("DB PROJECT VIEW NAME", view.getConfiguration().getName());
}
@Test
public void testViewInform3() throws CouldntLoadDataException {
final boolean starState2 = true;
view.getConfiguration().setStaredInternal(starState2);
assertEquals(starState2, view.getConfiguration().isStared());
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(false, view.getConfiguration().isStared());
}
@Test
public void testViewInform4() throws CouldntLoadDataException {
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.<Integer>absent(),
Optional.<INaviModule>absent(),
Optional.<INaviProject>absent(),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testModuleViewInform0() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final int currentUserViewSize = module.getContent().getViewContainer().getUserViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(
currentUserViewSize + 1, module.getContent().getViewContainer().getUserViews().size());
}
@Test
public void testModuleViewInform1() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test(expected = IllegalArgumentException.class)
public void testModuleViewInform2() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testModuleViewInform3() throws CouldntLoadDataException {
final INaviModule module = new MockModule(provider);
final int currentUserViewSize = module.getContent().getViewContainer().getUserViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(
currentUserViewSize + 1, module.getContent().getViewContainer().getUserViews().size());
final ViewNotificationContainer container2 =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(module.getConfiguration().getId()),
Optional.of(module),
Optional.<INaviProject>absent(),
"DELETE");
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container2), provider);
assertEquals(currentUserViewSize, module.getContent().getViewContainer().getUserViews().size());
}
@Test
public void testProjectViewInform0() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final int currentUserViewSize = project.getContent().getViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(currentUserViewSize + 1, project.getContent().getViews().size());
}
@Test
public void testProjectViewInform1() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"UPDATE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test(expected = IllegalArgumentException.class)
public void testProjectViewInform2() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"DELETE");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
}
@Test
public void testProjectViewInform3() throws CouldntLoadDataException {
final INaviProject project = new MockProject(provider);
final int currentUserViewSize = project.getContent().getViews().size();
final ViewNotificationContainer container =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"INSERT");
final PostgreSQLViewNotificationParser parser = new PostgreSQLViewNotificationParser();
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container), provider);
assertEquals(currentUserViewSize + 1, project.getContent().getViews().size());
final ViewNotificationContainer container2 =
new ViewNotificationContainer(view.getConfiguration().getId(),
Optional.fromNullable(view),
Optional.of(project.getConfiguration().getId()),
Optional.<INaviModule>absent(),
Optional.of(project),
"DELETE");
parser.inform(Lists.<ViewNotificationContainer>newArrayList(container2), provider);
assertEquals(currentUserViewSize, project.getContent().getViews().size());
}
}
|
// SPDX-License-Identifier: GPL-2.0
/******************************************************************************
*
* Copyright(c) 2007 - 2012 Realtek Corporation. All rights reserved.
*
******************************************************************************/
#define _USB_OPS_LINUX_C_
#include <drv_types.h>
#include <recv_osdep.h>
#include <rtw_sreset.h>
static void interrupt_handler_8188eu(struct adapter *adapt, u16 pkt_len, u8 *pbuf)
{
struct hal_data_8188e *haldata = adapt->HalData;
if (pkt_len != INTERRUPT_MSG_FORMAT_LEN) {
DBG_88E("%s Invalid interrupt content length (%d)!\n", __func__, pkt_len);
return;
}
/* HISR */
memcpy(&haldata->IntArray[0], &pbuf[USB_INTR_CONTENT_HISR_OFFSET], 4);
memcpy(&haldata->IntArray[1], &pbuf[USB_INTR_CONTENT_HISRE_OFFSET], 4);
/* C2H Event */
if (pbuf[0] != 0)
memcpy(&haldata->C2hArray[0],
&pbuf[USB_INTR_CONTENT_C2H_OFFSET], 16);
}
static int recvbuf2recvframe(struct adapter *adapt, struct sk_buff *pskb)
{
u8 *pbuf;
u8 shift_sz = 0;
u16 pkt_cnt;
u32 pkt_offset, skb_len, alloc_sz;
s32 transfer_len;
struct recv_stat *prxstat;
struct phy_stat *pphy_status = NULL;
struct sk_buff *pkt_copy = NULL;
struct recv_frame *precvframe = NULL;
struct rx_pkt_attrib *pattrib = NULL;
struct hal_data_8188e *haldata = adapt->HalData;
struct recv_priv *precvpriv = &adapt->recvpriv;
struct __queue *pfree_recv_queue = &precvpriv->free_recv_queue;
transfer_len = (s32)pskb->len;
pbuf = pskb->data;
prxstat = (struct recv_stat *)pbuf;
pkt_cnt = (le32_to_cpu(prxstat->rxdw2) >> 16) & 0xff;
do {
RT_TRACE(_module_rtl871x_recv_c_, _drv_info_,
("%s: rxdesc=offsset 0:0x%08x, 4:0x%08x, 8:0x%08x, C:0x%08x\n",
__func__, prxstat->rxdw0, prxstat->rxdw1,
prxstat->rxdw2, prxstat->rxdw4));
prxstat = (struct recv_stat *)pbuf;
precvframe = rtw_alloc_recvframe(pfree_recv_queue);
if (!precvframe) {
RT_TRACE(_module_rtl871x_recv_c_, _drv_err_,
("%s: precvframe==NULL\n", __func__));
DBG_88E("%s()-%d: rtw_alloc_recvframe() failed! RX Drop!\n", __func__, __LINE__);
goto _exit_recvbuf2recvframe;
}
INIT_LIST_HEAD(&precvframe->list);
update_recvframe_attrib_88e(precvframe, prxstat);
pattrib = &precvframe->attrib;
if ((pattrib->crc_err) || (pattrib->icv_err)) {
DBG_88E("%s: RX Warning! crc_err=%d icv_err=%d, skip!\n", __func__, pattrib->crc_err, pattrib->icv_err);
rtw_free_recvframe(precvframe, pfree_recv_queue);
goto _exit_recvbuf2recvframe;
}
if ((pattrib->physt) && (pattrib->pkt_rpt_type == NORMAL_RX))
pphy_status = (struct phy_stat *)(pbuf + RXDESC_OFFSET);
pkt_offset = RXDESC_SIZE + pattrib->drvinfo_sz + pattrib->shift_sz + pattrib->pkt_len;
if ((pattrib->pkt_len <= 0) || (pkt_offset > transfer_len)) {
RT_TRACE(_module_rtl871x_recv_c_, _drv_info_,
("%s: pkt_len<=0\n", __func__));
DBG_88E("%s()-%d: RX Warning!,pkt_len<=0 or pkt_offset> transfer_len\n", __func__, __LINE__);
rtw_free_recvframe(precvframe, pfree_recv_queue);
goto _exit_recvbuf2recvframe;
}
/* Modified by Albert 20101213 */
/* For 8 bytes IP header alignment. */
if (pattrib->qos) /* Qos data, wireless lan header length is 26 */
shift_sz = 6;
else
shift_sz = 0;
skb_len = pattrib->pkt_len;
/* for first fragment packet, driver need allocate 1536+drvinfo_sz+RXDESC_SIZE to defrag packet. */
/* modify alloc_sz for recvive crc error packet by thomas 2011-06-02 */
if ((pattrib->mfrag == 1) && (pattrib->frag_num == 0)) {
if (skb_len <= 1650)
alloc_sz = 1664;
else
alloc_sz = skb_len + 14;
} else {
alloc_sz = skb_len;
/* 6 is for IP header 8 bytes alignment in QoS packet case. */
/* 8 is for skb->data 4 bytes alignment. */
alloc_sz += 14;
}
pkt_copy = netdev_alloc_skb(adapt->pnetdev, alloc_sz);
if (pkt_copy) {
pkt_copy->dev = adapt->pnetdev;
precvframe->pkt = pkt_copy;
skb_reserve(pkt_copy, 8 - ((size_t)(pkt_copy->data) & 7));/* force pkt_copy->data at 8-byte alignment address */
skb_reserve(pkt_copy, shift_sz);/* force ip_hdr at 8-byte alignment address according to shift_sz. */
skb_put_data(pkt_copy, (pbuf + pattrib->drvinfo_sz + RXDESC_SIZE), skb_len);
} else {
DBG_88E("%s: alloc_skb fail , drop frag frame\n",
__func__);
rtw_free_recvframe(precvframe, pfree_recv_queue);
goto _exit_recvbuf2recvframe;
}
switch (haldata->UsbRxAggMode) {
case USB_RX_AGG_DMA:
case USB_RX_AGG_MIX:
pkt_offset = (u16)round_up(pkt_offset, 128);
break;
case USB_RX_AGG_USB:
pkt_offset = (u16)round_up(pkt_offset, 4);
break;
case USB_RX_AGG_DISABLE:
default:
break;
}
if (pattrib->pkt_rpt_type == NORMAL_RX) { /* Normal rx packet */
if (pattrib->physt)
update_recvframe_phyinfo_88e(precvframe, pphy_status);
if (rtw_recv_entry(precvframe) != _SUCCESS) {
RT_TRACE(_module_rtl871x_recv_c_, _drv_err_,
("%s: rtw_recv_entry(precvframe) != _SUCCESS\n",
__func__));
}
} else if (pattrib->pkt_rpt_type == TX_REPORT1) {
/* CCX-TXRPT ack for xmit mgmt frames. */
handle_txrpt_ccx_88e(adapt, precvframe->pkt->data);
rtw_free_recvframe(precvframe, pfree_recv_queue);
} else if (pattrib->pkt_rpt_type == TX_REPORT2) {
ODM_RA_TxRPT2Handle_8188E(&haldata->odmpriv,
precvframe->pkt->data,
pattrib->pkt_len,
pattrib->MacIDValidEntry[0],
pattrib->MacIDValidEntry[1]);
rtw_free_recvframe(precvframe, pfree_recv_queue);
} else if (pattrib->pkt_rpt_type == HIS_REPORT) {
interrupt_handler_8188eu(adapt, pattrib->pkt_len, precvframe->pkt->data);
rtw_free_recvframe(precvframe, pfree_recv_queue);
}
pkt_cnt--;
transfer_len -= pkt_offset;
pbuf += pkt_offset;
precvframe = NULL;
pkt_copy = NULL;
if (transfer_len > 0 && pkt_cnt == 0)
pkt_cnt = (le32_to_cpu(prxstat->rxdw2) >> 16) & 0xff;
} while ((transfer_len > 0) && (pkt_cnt > 0));
_exit_recvbuf2recvframe:
return _SUCCESS;
}
unsigned int ffaddr2pipehdl(struct dvobj_priv *pdvobj, u32 addr)
{
unsigned int pipe = 0, ep_num = 0;
struct usb_device *pusbd = pdvobj->pusbdev;
if (addr == RECV_BULK_IN_ADDR) {
pipe = usb_rcvbulkpipe(pusbd, pdvobj->RtInPipe[0]);
} else if (addr == RECV_INT_IN_ADDR) {
pipe = usb_rcvbulkpipe(pusbd, pdvobj->RtInPipe[1]);
} else if (addr < HW_QUEUE_ENTRY) {
ep_num = pdvobj->Queue2Pipe[addr];
pipe = usb_sndbulkpipe(pusbd, ep_num);
}
return pipe;
}
static int usbctrl_vendorreq(struct adapter *adapt, u8 request, u16 value, u16 index, void *pdata, u16 len, u8 requesttype)
{
struct dvobj_priv *dvobjpriv = adapter_to_dvobj(adapt);
struct usb_device *udev = dvobjpriv->pusbdev;
unsigned int pipe;
int status = 0;
u8 reqtype;
u8 *pIo_buf;
int vendorreq_times = 0;
if ((adapt->bSurpriseRemoved) || (adapt->pwrctrlpriv.pnp_bstop_trx)) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:(adapt->bSurpriseRemoved ||adapter->pwrctrlpriv.pnp_bstop_trx)!!!\n",
__func__));
status = -EPERM;
goto exit;
}
if (len > MAX_VENDOR_REQ_CMD_SIZE) {
DBG_88E("[%s] Buffer len error ,vendor request failed\n", __func__);
status = -EINVAL;
goto exit;
}
if (mutex_lock_interruptible(&dvobjpriv->usb_vendor_req_mutex)) {
status = -ERESTARTSYS;
goto exit;
}
/* Acquire IO memory for vendorreq */
pIo_buf = kmalloc(MAX_USB_IO_CTL_SIZE, GFP_ATOMIC);
if (!pIo_buf) {
status = -ENOMEM;
goto release_mutex;
}
while (++vendorreq_times <= MAX_USBCTRL_VENDORREQ_TIMES) {
memset(pIo_buf, 0, len);
if (requesttype == 0x01) {
pipe = usb_rcvctrlpipe(udev, 0);/* read_in */
reqtype = REALTEK_USB_VENQT_READ;
} else {
pipe = usb_sndctrlpipe(udev, 0);/* write_out */
reqtype = REALTEK_USB_VENQT_WRITE;
memcpy(pIo_buf, pdata, len);
}
status = usb_control_msg(udev, pipe, request, reqtype, value, index, pIo_buf, len, RTW_USB_CONTROL_MSG_TIMEOUT);
if (status == len) { /* Success this control transfer. */
if (requesttype == 0x01)
memcpy(pdata, pIo_buf, len);
} else { /* error cases */
DBG_88E("reg 0x%x, usb %s %u fail, status:%d value=0x%x, vendorreq_times:%d\n",
value, (requesttype == 0x01) ? "read" : "write",
len, status, *(u32 *)pdata, vendorreq_times);
if (status < 0) {
if (status == (-ESHUTDOWN) || status == -ENODEV)
adapt->bSurpriseRemoved = true;
else
adapt->HalData->srestpriv.wifi_error_status = USB_VEN_REQ_CMD_FAIL;
} else { /* status != len && status >= 0 */
if (status > 0) {
if (requesttype == 0x01) {
/* For Control read transfer, we have to copy the read data from pIo_buf to pdata. */
memcpy(pdata, pIo_buf, len);
}
}
}
}
/* firmware download is checksummed, don't retry */
if ((value >= FW_8188E_START_ADDRESS && value <= FW_8188E_END_ADDRESS) || status == len)
break;
}
kfree(pIo_buf);
release_mutex:
mutex_unlock(&dvobjpriv->usb_vendor_req_mutex);
exit:
return status;
}
u8 usb_read8(struct adapter *adapter, u32 addr)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
u8 data = 0;
request = 0x05;
requesttype = 0x01;/* read_in */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 1;
usbctrl_vendorreq(adapter, request, wvalue, index, &data, len, requesttype);
return data;
}
u16 usb_read16(struct adapter *adapter, u32 addr)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
__le32 data;
request = 0x05;
requesttype = 0x01;/* read_in */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 2;
usbctrl_vendorreq(adapter, request, wvalue, index, &data, len, requesttype);
return (u16)(le32_to_cpu(data) & 0xffff);
}
u32 usb_read32(struct adapter *adapter, u32 addr)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
__le32 data;
request = 0x05;
requesttype = 0x01;/* read_in */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 4;
usbctrl_vendorreq(adapter, request, wvalue, index, &data, len, requesttype);
return le32_to_cpu(data);
}
static void usb_read_port_complete(struct urb *purb, struct pt_regs *regs)
{
struct recv_buf *precvbuf = (struct recv_buf *)purb->context;
struct adapter *adapt = (struct adapter *)precvbuf->adapter;
struct recv_priv *precvpriv = &adapt->recvpriv;
RT_TRACE(_module_hci_ops_os_c_, _drv_err_, ("%s!!!\n", __func__));
if (adapt->bSurpriseRemoved || adapt->bDriverStopped || adapt->bReadPortCancel) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:bDriverStopped(%d) OR bSurpriseRemoved(%d)\n",
__func__, adapt->bDriverStopped,
adapt->bSurpriseRemoved));
precvbuf->reuse = true;
DBG_88E("%s() RX Warning! bDriverStopped(%d) OR bSurpriseRemoved(%d) bReadPortCancel(%d)\n",
__func__, adapt->bDriverStopped,
adapt->bSurpriseRemoved, adapt->bReadPortCancel);
return;
}
if (purb->status == 0) { /* SUCCESS */
if ((purb->actual_length > MAX_RECVBUF_SZ) || (purb->actual_length < RXDESC_SIZE)) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s: (purb->actual_length > MAX_RECVBUF_SZ) || (purb->actual_length < RXDESC_SIZE)\n",
__func__));
precvbuf->reuse = true;
usb_read_port(adapt, RECV_BULK_IN_ADDR, precvbuf);
DBG_88E("%s()-%d: RX Warning!\n", __func__, __LINE__);
} else {
skb_put(precvbuf->pskb, purb->actual_length);
skb_queue_tail(&precvpriv->rx_skb_queue, precvbuf->pskb);
if (skb_queue_len(&precvpriv->rx_skb_queue) <= 1)
tasklet_schedule(&precvpriv->recv_tasklet);
precvbuf->pskb = NULL;
precvbuf->reuse = false;
usb_read_port(adapt, RECV_BULK_IN_ADDR, precvbuf);
}
} else {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s : purb->status(%d) != 0\n",
__func__, purb->status));
DBG_88E("###=> %s => urb status(%d)\n", __func__, purb->status);
skb_put(precvbuf->pskb, purb->actual_length);
precvbuf->pskb = NULL;
switch (purb->status) {
case -EINVAL:
case -EPIPE:
case -ENODEV:
case -ESHUTDOWN:
adapt->bSurpriseRemoved = true;
fallthrough;
case -ENOENT:
adapt->bDriverStopped = true;
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:bDriverStopped=true\n", __func__));
break;
case -EPROTO:
case -EOVERFLOW:
adapt->HalData->srestpriv.wifi_error_status = USB_READ_PORT_FAIL;
precvbuf->reuse = true;
usb_read_port(adapt, RECV_BULK_IN_ADDR, precvbuf);
break;
case -EINPROGRESS:
DBG_88E("ERROR: URB IS IN PROGRESS!\n");
break;
default:
break;
}
}
}
u32 usb_read_port(struct adapter *adapter, u32 addr, struct recv_buf *precvbuf)
{
struct urb *purb = NULL;
struct dvobj_priv *pdvobj = adapter_to_dvobj(adapter);
struct recv_priv *precvpriv = &adapter->recvpriv;
struct usb_device *pusbd = pdvobj->pusbdev;
int err;
unsigned int pipe;
u32 ret = _SUCCESS;
if (adapter->bDriverStopped || adapter->bSurpriseRemoved ||
adapter->pwrctrlpriv.pnp_bstop_trx) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:(adapt->bDriverStopped ||adapt->bSurpriseRemoved ||adapter->pwrctrlpriv.pnp_bstop_trx)!!!\n",
__func__));
return _FAIL;
}
if (!precvbuf) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:precvbuf==NULL\n", __func__));
return _FAIL;
}
if (!precvbuf->reuse || !precvbuf->pskb) {
precvbuf->pskb = skb_dequeue(&precvpriv->free_recv_skb_queue);
if (precvbuf->pskb)
precvbuf->reuse = true;
}
/* re-assign for linux based on skb */
if (!precvbuf->reuse || !precvbuf->pskb) {
precvbuf->pskb = netdev_alloc_skb(adapter->pnetdev, MAX_RECVBUF_SZ);
if (!precvbuf->pskb) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_, ("init_recvbuf(): alloc_skb fail!\n"));
DBG_88E("#### %s() alloc_skb fail!#####\n", __func__);
return _FAIL;
}
} else { /* reuse skb */
precvbuf->reuse = false;
}
purb = precvbuf->purb;
/* translate DMA FIFO addr to pipehandle */
pipe = ffaddr2pipehdl(pdvobj, addr);
usb_fill_bulk_urb(purb, pusbd, pipe,
precvbuf->pskb->data,
MAX_RECVBUF_SZ,
usb_read_port_complete,
precvbuf);/* context is precvbuf */
err = usb_submit_urb(purb, GFP_ATOMIC);
if ((err) && (err != (-EPERM))) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("cannot submit rx in-token(err=0x%.8x), URB_STATUS =0x%.8x",
err, purb->status));
DBG_88E("cannot submit rx in-token(err = 0x%08x),urb_status = %d\n",
err, purb->status);
ret = _FAIL;
}
return ret;
}
void rtw_hal_inirp_deinit(struct adapter *padapter)
{
int i;
struct recv_buf *precvbuf;
precvbuf = padapter->recvpriv.precv_buf;
DBG_88E("%s\n", __func__);
padapter->bReadPortCancel = true;
for (i = 0; i < NR_RECVBUFF; i++) {
precvbuf->reuse = true;
if (precvbuf->purb)
usb_kill_urb(precvbuf->purb);
precvbuf++;
}
}
int usb_write8(struct adapter *adapter, u32 addr, u8 val)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
u8 data;
request = 0x05;
requesttype = 0x00;/* write_out */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 1;
data = val;
return usbctrl_vendorreq(adapter, request, wvalue,
index, &data, len, requesttype);
}
int usb_write16(struct adapter *adapter, u32 addr, u16 val)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
__le32 data;
request = 0x05;
requesttype = 0x00;/* write_out */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 2;
data = cpu_to_le32(val & 0x0000ffff);
return usbctrl_vendorreq(adapter, request, wvalue,
index, &data, len, requesttype);
}
int usb_write32(struct adapter *adapter, u32 addr, u32 val)
{
u8 request;
u8 requesttype;
u16 wvalue;
u16 index;
u16 len;
__le32 data;
request = 0x05;
requesttype = 0x00;/* write_out */
index = 0;/* n/a */
wvalue = (u16)(addr & 0x0000ffff);
len = 4;
data = cpu_to_le32(val);
return usbctrl_vendorreq(adapter, request, wvalue,
index, &data, len, requesttype);
}
static void usb_write_port_complete(struct urb *purb, struct pt_regs *regs)
{
struct xmit_buf *pxmitbuf = (struct xmit_buf *)purb->context;
struct adapter *padapter = pxmitbuf->padapter;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
switch (pxmitbuf->flags) {
case VO_QUEUE_INX:
pxmitpriv->voq_cnt--;
break;
case VI_QUEUE_INX:
pxmitpriv->viq_cnt--;
break;
case BE_QUEUE_INX:
pxmitpriv->beq_cnt--;
break;
case BK_QUEUE_INX:
pxmitpriv->bkq_cnt--;
break;
case HIGH_QUEUE_INX:
#ifdef CONFIG_88EU_AP_MODE
rtw_chk_hi_queue_cmd(padapter);
#endif
break;
default:
break;
}
if (padapter->bSurpriseRemoved || padapter->bDriverStopped ||
padapter->bWritePortCancel) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:bDriverStopped(%d) OR bSurpriseRemoved(%d)",
__func__, padapter->bDriverStopped,
padapter->bSurpriseRemoved));
DBG_88E("%s(): TX Warning! bDriverStopped(%d) OR bSurpriseRemoved(%d) bWritePortCancel(%d) pxmitbuf->ext_tag(%x)\n",
__func__, padapter->bDriverStopped,
padapter->bSurpriseRemoved, padapter->bReadPortCancel,
pxmitbuf->ext_tag);
goto check_completion;
}
if (purb->status) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s : purb->status(%d) != 0\n",
__func__, purb->status));
DBG_88E("###=> %s status(%d)\n", __func__, purb->status);
if ((purb->status == -EPIPE) || (purb->status == -EPROTO)) {
sreset_set_wifi_error_status(padapter, USB_WRITE_PORT_FAIL);
} else if (purb->status == -EINPROGRESS) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s: EINPROGRESS\n", __func__));
goto check_completion;
} else if (purb->status == -ENOENT) {
DBG_88E("%s: -ENOENT\n", __func__);
goto check_completion;
} else if (purb->status == -ECONNRESET) {
DBG_88E("%s: -ECONNRESET\n", __func__);
goto check_completion;
} else if (purb->status == -ESHUTDOWN) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s: ESHUTDOWN\n", __func__));
padapter->bDriverStopped = true;
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:bDriverStopped = true\n", __func__));
goto check_completion;
} else {
padapter->bSurpriseRemoved = true;
DBG_88E("bSurpriseRemoved = true\n");
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:bSurpriseRemoved = true\n", __func__));
goto check_completion;
}
}
check_completion:
rtw_sctx_done_err(&pxmitbuf->sctx,
purb->status ? RTW_SCTX_DONE_WRITE_PORT_ERR :
RTW_SCTX_DONE_SUCCESS);
rtw_free_xmitbuf(pxmitpriv, pxmitbuf);
tasklet_hi_schedule(&pxmitpriv->xmit_tasklet);
}
u32 usb_write_port(struct adapter *padapter, u32 addr, u32 cnt, struct xmit_buf *xmitbuf)
{
unsigned long irqL;
unsigned int pipe;
int status;
u32 ret = _FAIL;
struct urb *purb = NULL;
struct dvobj_priv *pdvobj = adapter_to_dvobj(padapter);
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
struct xmit_frame *pxmitframe = (struct xmit_frame *)xmitbuf->priv_data;
struct usb_device *pusbd = pdvobj->pusbdev;
RT_TRACE(_module_hci_ops_os_c_, _drv_err_, ("+%s\n", __func__));
if ((padapter->bDriverStopped) || (padapter->bSurpriseRemoved) ||
(padapter->pwrctrlpriv.pnp_bstop_trx)) {
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s:( padapter->bDriverStopped ||padapter->bSurpriseRemoved ||adapter->pwrctrlpriv.pnp_bstop_trx)!!!\n",
__func__));
rtw_sctx_done_err(&xmitbuf->sctx, RTW_SCTX_DONE_TX_DENY);
goto exit;
}
spin_lock_irqsave(&pxmitpriv->lock, irqL);
switch (addr) {
case VO_QUEUE_INX:
pxmitpriv->voq_cnt++;
xmitbuf->flags = VO_QUEUE_INX;
break;
case VI_QUEUE_INX:
pxmitpriv->viq_cnt++;
xmitbuf->flags = VI_QUEUE_INX;
break;
case BE_QUEUE_INX:
pxmitpriv->beq_cnt++;
xmitbuf->flags = BE_QUEUE_INX;
break;
case BK_QUEUE_INX:
pxmitpriv->bkq_cnt++;
xmitbuf->flags = BK_QUEUE_INX;
break;
case HIGH_QUEUE_INX:
xmitbuf->flags = HIGH_QUEUE_INX;
break;
default:
xmitbuf->flags = MGT_QUEUE_INX;
break;
}
spin_unlock_irqrestore(&pxmitpriv->lock, irqL);
purb = xmitbuf->pxmit_urb[0];
/* translate DMA FIFO addr to pipehandle */
pipe = ffaddr2pipehdl(pdvobj, addr);
usb_fill_bulk_urb(purb, pusbd, pipe,
pxmitframe->buf_addr, /* xmitbuf->pbuf */
cnt,
usb_write_port_complete,
xmitbuf);/* context is xmitbuf */
status = usb_submit_urb(purb, GFP_ATOMIC);
if (status) {
rtw_sctx_done_err(&xmitbuf->sctx, RTW_SCTX_DONE_WRITE_PORT_ERR);
DBG_88E("%s, status =%d\n", __func__, status);
RT_TRACE(_module_hci_ops_os_c_, _drv_err_,
("%s(): usb_submit_urb, status =%x\n",
__func__, status));
switch (status) {
case -ENODEV:
padapter->bDriverStopped = true;
break;
default:
break;
}
goto exit;
}
ret = _SUCCESS;
/* We add the URB_ZERO_PACKET flag to urb so that the host will send the zero packet automatically. */
RT_TRACE(_module_hci_ops_os_c_, _drv_err_, ("-%s\n", __func__));
exit:
if (ret != _SUCCESS)
rtw_free_xmitbuf(pxmitpriv, xmitbuf);
return ret;
}
void usb_write_port_cancel(struct adapter *padapter)
{
int i, j;
struct xmit_buf *pxmitbuf = (struct xmit_buf *)padapter->xmitpriv.pxmitbuf;
DBG_88E("%s\n", __func__);
padapter->bWritePortCancel = true;
for (i = 0; i < NR_XMITBUFF; i++) {
for (j = 0; j < 8; j++) {
if (pxmitbuf->pxmit_urb[j])
usb_kill_urb(pxmitbuf->pxmit_urb[j]);
}
pxmitbuf++;
}
pxmitbuf = (struct xmit_buf *)padapter->xmitpriv.pxmit_extbuf;
for (i = 0; i < NR_XMIT_EXTBUFF; i++) {
for (j = 0; j < 8; j++) {
if (pxmitbuf->pxmit_urb[j])
usb_kill_urb(pxmitbuf->pxmit_urb[j]);
}
pxmitbuf++;
}
}
void rtl8188eu_recv_tasklet(struct tasklet_struct *t)
{
struct sk_buff *pskb;
struct adapter *adapt = from_tasklet(adapt, t, recvpriv.recv_tasklet);
struct recv_priv *precvpriv = &adapt->recvpriv;
while (NULL != (pskb = skb_dequeue(&precvpriv->rx_skb_queue))) {
if ((adapt->bDriverStopped) || (adapt->bSurpriseRemoved)) {
DBG_88E("recv_tasklet => bDriverStopped or bSurpriseRemoved\n");
dev_kfree_skb_any(pskb);
break;
}
recvbuf2recvframe(adapt, pskb);
skb_reset_tail_pointer(pskb);
pskb->len = 0;
skb_queue_tail(&precvpriv->free_recv_skb_queue, pskb);
}
}
void rtl8188eu_xmit_tasklet(struct tasklet_struct *t)
{
struct adapter *adapt = from_tasklet(adapt, t, xmitpriv.xmit_tasklet);
struct xmit_priv *pxmitpriv = &adapt->xmitpriv;
if (check_fwstate(&adapt->mlmepriv, _FW_UNDER_SURVEY))
return;
while (1) {
if ((adapt->bDriverStopped) ||
(adapt->bSurpriseRemoved) ||
(adapt->bWritePortCancel)) {
DBG_88E("xmit_tasklet => bDriverStopped or bSurpriseRemoved or bWritePortCancel\n");
break;
}
if (!rtl8188eu_xmitframe_complete(adapt, pxmitpriv))
break;
}
}
|
/* ==== editable-form ==== */
/* class for single editable element */
.editable-wrap {
display: inline-block;
white-space: pre;
margin: 0;
}
/* remove bottom-margin for bootstrap */
.editable-wrap .editable-controls,
.editable-wrap .editable-error {
margin-bottom: 0;
}
/* remove bottom-margin of inputs */
.editable-wrap .editable-controls > input,
.editable-wrap .editable-controls > select,
.editable-wrap .editable-controls > textarea {
margin-bottom: 0;
}
/* keep buttons on the same line */
.editable-wrap .editable-input {
display: inline-block;
}
.editable-buttons {
display: inline-block;
vertical-align: top;
}
.editable-buttons button {
margin-left: 5px;
}
/* in bootstrap width: 100% => buttons go outside the box */
.editable-input.editable-has-buttons {
width: auto;
}
/* ==== editable-text ==== */
/* fix padding issue on typeahead */
.editable-text {
white-space: nowrap;
}
/* ==== editable-bsdate ==== */
/* fix padding issue on bsdate popup */
.editable-bsdate {
white-space: nowrap;
}
/* ==== editable-bstime ==== */
/* fix padding issue on bstime */
.editable-bstime {
white-space: nowrap;
}
/* workaround for bootstrap that sets width: 100% and inputs become too wide */
.editable-bstime .editable-input input[type="text"] {
width: 46px;
}
/* less padding for .well */
.editable-bstime .well-small {
margin-bottom: 0;
padding: 10px;
}
/* ==== editable-range ==== */
.editable-range output {
display: inline-block;
min-width: 30px;
vertical-align: top;
text-align: center;
}
/* ==== editable-color ==== */
.editable-color input[type="color"] {
width: 50px;
}
/* ==== editable-checkbox ==== */
/* ==== editable-checklist ==== */
/* ==== editable-radiolist ==== */
.editable-checkbox label span,
.editable-checklist label span,
.editable-radiolist label span {
margin-left: 7px;
margin-right: 10px;
}
/* ==== element ==== */
/* hiding element */
.editable-hide {
display: none !important;
}
.editable-click,
a.editable-click {
text-decoration: none;
color: #428bca;
border-bottom: dashed 1px #428bca;
}
.editable-click:hover,
a.editable-click:hover {
text-decoration: none;
color: #2a6496;
border-bottom-color: #2a6496;
}
/* editable-empty */
.editable-empty,
.editable-empty:hover,
.editable-empty:focus,
a.editable-empty,
a.editable-empty:hover,
a.editable-empty:focus {
font-style: italic;
color: #DD1144;
text-decoration: none;
}
/* ui-bootstrap editable popover */
.ui-popover-wrapper a {
/* make the link always show up */
display: inline !important;
}
.ui-popover-wrapper form {
display: none !important;
}
/* editable popover */
.popover-wrapper > a {
/* make the link always show up */
display: inline !important;
}
.popover-wrapper {
/* make absolutely positioned children constrained to this box*/
display: inline;
position: relative;
}
.popover-wrapper form {
position: absolute;
top: -53px;
background: #FFF;
border: 1px solid #AAA;
border-radius: 5px;
padding: 7px;
width: auto;
display: inline-block;
left: 50%;
z-index: 101;
}
.popover-wrapper form:before {
content:"";
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid #AAA;
position:absolute;
bottom:-10px;
}
.popover-wrapper form:after {
content:"";
width:0;
height:0;
border-left: 9px solid transparent;
border-right: 9px solid transparent;
border-top: 9px solid #FFF;
position:absolute;
bottom:-9px;
}
@media screen and (max-width: 750px) {
.popover-wrapper form {
margin-left: -60px;
}
.popover-wrapper form:before {
left:50px;
}
.popover-wrapper form:after {
left:51px;
}
}
@media screen and (min-width: 750px) {
.popover-wrapper form {
margin-left: -110px;
}
.popover-wrapper form:before {
left:100px;
}
.popover-wrapper form:after {
left:101px;
}
}
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Authentication\Adapter;
use Zend\Authentication;
use Zend\Http\Request as HTTPRequest;
use Zend\Http\Response as HTTPResponse;
use Zend\Uri\UriFactory;
use Zend\Crypt\Utils as CryptUtils;
/**
* HTTP Authentication Adapter
*
* Implements a pretty good chunk of RFC 2617.
*
* @todo Support auth-int
* @todo Track nonces, nonce-count, opaque for replay protection and stale support
* @todo Support Authentication-Info header
*/
class Http implements AdapterInterface
{
/**
* Reference to the HTTP Request object
*
* @var HTTPRequest
*/
protected $request;
/**
* Reference to the HTTP Response object
*
* @var HTTPResponse
*/
protected $response;
/**
* Object that looks up user credentials for the Basic scheme
*
* @var Http\ResolverInterface
*/
protected $basicResolver;
/**
* Object that looks up user credentials for the Digest scheme
*
* @var Http\ResolverInterface
*/
protected $digestResolver;
/**
* List of authentication schemes supported by this class
*
* @var array
*/
protected $supportedSchemes = array('basic', 'digest');
/**
* List of schemes this class will accept from the client
*
* @var array
*/
protected $acceptSchemes;
/**
* Space-delimited list of protected domains for Digest Auth
*
* @var string
*/
protected $domains;
/**
* The protection realm to use
*
* @var string
*/
protected $realm;
/**
* Nonce timeout period
*
* @var int
*/
protected $nonceTimeout;
/**
* Whether to send the opaque value in the header. True by default
*
* @var bool
*/
protected $useOpaque;
/**
* List of the supported digest algorithms. I want to support both MD5 and
* MD5-sess, but MD5-sess won't make it into the first version.
*
* @var array
*/
protected $supportedAlgos = array('MD5');
/**
* The actual algorithm to use. Defaults to MD5
*
* @var string
*/
protected $algo;
/**
* List of supported qop options. My intention is to support both 'auth' and
* 'auth-int', but 'auth-int' won't make it into the first version.
*
* @var array
*/
protected $supportedQops = array('auth');
/**
* Whether or not to do Proxy Authentication instead of origin server
* authentication (send 407's instead of 401's). Off by default.
*
* @var bool
*/
protected $imaProxy;
/**
* Flag indicating the client is IE and didn't bother to return the opaque string
*
* @var bool
*/
protected $ieNoOpaque;
/**
* Constructor
*
* @param array $config Configuration settings:
* 'accept_schemes' => 'basic'|'digest'|'basic digest'
* 'realm' => <string>
* 'digest_domains' => <string> Space-delimited list of URIs
* 'nonce_timeout' => <int>
* 'use_opaque' => <bool> Whether to send the opaque value in the header
* 'algorithm' => <string> See $supportedAlgos. Default: MD5
* 'proxy_auth' => <bool> Whether to do authentication as a Proxy
* @throws Exception\InvalidArgumentException
*/
public function __construct(array $config)
{
$this->request = null;
$this->response = null;
$this->ieNoOpaque = false;
if (empty($config['accept_schemes'])) {
throw new Exception\InvalidArgumentException('Config key "accept_schemes" is required');
}
$schemes = explode(' ', $config['accept_schemes']);
$this->acceptSchemes = array_intersect($schemes, $this->supportedSchemes);
if (empty($this->acceptSchemes)) {
throw new Exception\InvalidArgumentException(sprintf(
'No supported schemes given in "accept_schemes". Valid values: %s',
implode(', ', $this->supportedSchemes)
));
}
// Double-quotes are used to delimit the realm string in the HTTP header,
// and colons are field delimiters in the password file.
if (empty($config['realm']) ||
!ctype_print($config['realm']) ||
strpos($config['realm'], ':') !== false ||
strpos($config['realm'], '"') !== false) {
throw new Exception\InvalidArgumentException(
'Config key \'realm\' is required, and must contain only printable characters,'
. 'excluding quotation marks and colons'
);
} else {
$this->realm = $config['realm'];
}
if (in_array('digest', $this->acceptSchemes)) {
if (empty($config['digest_domains']) ||
!ctype_print($config['digest_domains']) ||
strpos($config['digest_domains'], '"') !== false) {
throw new Exception\InvalidArgumentException(
'Config key \'digest_domains\' is required, and must contain '
. 'only printable characters, excluding quotation marks'
);
} else {
$this->domains = $config['digest_domains'];
}
if (empty($config['nonce_timeout']) ||
!is_numeric($config['nonce_timeout'])) {
throw new Exception\InvalidArgumentException(
'Config key \'nonce_timeout\' is required, and must be an integer'
);
} else {
$this->nonceTimeout = (int) $config['nonce_timeout'];
}
// We use the opaque value unless explicitly told not to
if (isset($config['use_opaque']) && false == (bool) $config['use_opaque']) {
$this->useOpaque = false;
} else {
$this->useOpaque = true;
}
if (isset($config['algorithm']) && in_array($config['algorithm'], $this->supportedAlgos)) {
$this->algo = $config['algorithm'];
} else {
$this->algo = 'MD5';
}
}
// Don't be a proxy unless explicitly told to do so
if (isset($config['proxy_auth']) && true == (bool) $config['proxy_auth']) {
$this->imaProxy = true; // I'm a Proxy
} else {
$this->imaProxy = false;
}
}
/**
* Setter for the basicResolver property
*
* @param Http\ResolverInterface $resolver
* @return Http Provides a fluent interface
*/
public function setBasicResolver(Http\ResolverInterface $resolver)
{
$this->basicResolver = $resolver;
return $this;
}
/**
* Getter for the basicResolver property
*
* @return Http\ResolverInterface
*/
public function getBasicResolver()
{
return $this->basicResolver;
}
/**
* Setter for the digestResolver property
*
* @param Http\ResolverInterface $resolver
* @return Http Provides a fluent interface
*/
public function setDigestResolver(Http\ResolverInterface $resolver)
{
$this->digestResolver = $resolver;
return $this;
}
/**
* Getter for the digestResolver property
*
* @return Http\ResolverInterface
*/
public function getDigestResolver()
{
return $this->digestResolver;
}
/**
* Setter for the Request object
*
* @param HTTPRequest $request
* @return Http Provides a fluent interface
*/
public function setRequest(HTTPRequest $request)
{
$this->request = $request;
return $this;
}
/**
* Getter for the Request object
*
* @return HTTPRequest
*/
public function getRequest()
{
return $this->request;
}
/**
* Setter for the Response object
*
* @param HTTPResponse $response
* @return Http Provides a fluent interface
*/
public function setResponse(HTTPResponse $response)
{
$this->response = $response;
return $this;
}
/**
* Getter for the Response object
*
* @return HTTPResponse
*/
public function getResponse()
{
return $this->response;
}
/**
* Authenticate
*
* @throws Exception\RuntimeException
* @return Authentication\Result
*/
public function authenticate()
{
if (empty($this->request) || empty($this->response)) {
throw new Exception\RuntimeException(
'Request and Response objects must be set before calling authenticate()'
);
}
if ($this->imaProxy) {
$getHeader = 'Proxy-Authorization';
} else {
$getHeader = 'Authorization';
}
$headers = $this->request->getHeaders();
if (!$headers->has($getHeader)) {
return $this->challengeClient();
}
$authHeader = $headers->get($getHeader)->getFieldValue();
if (!$authHeader) {
return $this->challengeClient();
}
list($clientScheme) = explode(' ', $authHeader);
$clientScheme = strtolower($clientScheme);
// The server can issue multiple challenges, but the client should
// answer with only the selected auth scheme.
if (!in_array($clientScheme, $this->supportedSchemes)) {
$this->response->setStatusCode(400);
return new Authentication\Result(
Authentication\Result::FAILURE_UNCATEGORIZED,
array(),
array('Client requested an incorrect or unsupported authentication scheme')
);
}
// client sent a scheme that is not the one required
if (!in_array($clientScheme, $this->acceptSchemes)) {
// challenge again the client
return $this->challengeClient();
}
switch ($clientScheme) {
case 'basic':
$result = $this->_basicAuth($authHeader);
break;
case 'digest':
$result = $this->_digestAuth($authHeader);
break;
default:
throw new Exception\RuntimeException('Unsupported authentication scheme: ' . $clientScheme);
}
return $result;
}
/**
* @deprecated
* @see Http::challengeClient()
* @return Authentication\Result Always returns a non-identity Auth result
*/
protected function _challengeClient()
{
trigger_error(sprintf(
'The method "%s" is deprecated and will be removed in the future; '
. 'please use the public method "%s::challengeClient()" instead',
__METHOD__,
__CLASS__
), E_USER_DEPRECATED);
return $this->challengeClient();
}
/**
* Challenge Client
*
* Sets a 401 or 407 Unauthorized response code, and creates the
* appropriate Authenticate header(s) to prompt for credentials.
*
* @return Authentication\Result Always returns a non-identity Auth result
*/
public function challengeClient()
{
if ($this->imaProxy) {
$statusCode = 407;
$headerName = 'Proxy-Authenticate';
} else {
$statusCode = 401;
$headerName = 'WWW-Authenticate';
}
$this->response->setStatusCode($statusCode);
// Send a challenge in each acceptable authentication scheme
$headers = $this->response->getHeaders();
if (in_array('basic', $this->acceptSchemes)) {
$headers->addHeaderLine($headerName, $this->_basicHeader());
}
if (in_array('digest', $this->acceptSchemes)) {
$headers->addHeaderLine($headerName, $this->_digestHeader());
}
return new Authentication\Result(
Authentication\Result::FAILURE_CREDENTIAL_INVALID,
array(),
array('Invalid or absent credentials; challenging client')
);
}
/**
* Basic Header
*
* Generates a Proxy- or WWW-Authenticate header value in the Basic
* authentication scheme.
*
* @return string Authenticate header value
*/
protected function _basicHeader()
{
return 'Basic realm="' . $this->realm . '"';
}
/**
* Digest Header
*
* Generates a Proxy- or WWW-Authenticate header value in the Digest
* authentication scheme.
*
* @return string Authenticate header value
*/
protected function _digestHeader()
{
$wwwauth = 'Digest realm="' . $this->realm . '", '
. 'domain="' . $this->domains . '", '
. 'nonce="' . $this->_calcNonce() . '", '
. ($this->useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '')
. 'algorithm="' . $this->algo . '", '
. 'qop="' . implode(',', $this->supportedQops) . '"';
return $wwwauth;
}
/**
* Basic Authentication
*
* @param string $header Client's Authorization header
* @throws Exception\ExceptionInterface
* @return Authentication\Result
*/
protected function _basicAuth($header)
{
if (empty($header)) {
throw new Exception\RuntimeException('The value of the client Authorization header is required');
}
if (empty($this->basicResolver)) {
throw new Exception\RuntimeException(
'A basicResolver object must be set before doing Basic authentication'
);
}
// Decode the Authorization header
$auth = substr($header, strlen('Basic '));
$auth = base64_decode($auth);
if (!$auth) {
throw new Exception\RuntimeException('Unable to base64_decode Authorization header value');
}
// See ZF-1253. Validate the credentials the same way the digest
// implementation does. If invalid credentials are detected,
// re-challenge the client.
if (!ctype_print($auth)) {
return $this->challengeClient();
}
// Fix for ZF-1515: Now re-challenges on empty username or password
$creds = array_filter(explode(':', $auth));
if (count($creds) != 2) {
return $this->challengeClient();
}
$result = $this->basicResolver->resolve($creds[0], $this->realm, $creds[1]);
if ($result instanceof Authentication\Result && $result->isValid()) {
return $result;
}
if (!$result instanceof Authentication\Result
&& !is_array($result)
&& CryptUtils::compareStrings($result, $creds[1])
) {
$identity = array('username' => $creds[0], 'realm' => $this->realm);
return new Authentication\Result(Authentication\Result::SUCCESS, $identity);
} elseif (is_array($result)) {
return new Authentication\Result(Authentication\Result::SUCCESS, $result);
}
return $this->challengeClient();
}
/**
* Digest Authentication
*
* @param string $header Client's Authorization header
* @throws Exception\ExceptionInterface
* @return Authentication\Result Valid auth result only on successful auth
*/
protected function _digestAuth($header)
{
if (empty($header)) {
throw new Exception\RuntimeException('The value of the client Authorization header is required');
}
if (empty($this->digestResolver)) {
throw new Exception\RuntimeException('A digestResolver object must be set before doing Digest authentication');
}
$data = $this->_parseDigestAuth($header);
if ($data === false) {
$this->response->setStatusCode(400);
return new Authentication\Result(
Authentication\Result::FAILURE_UNCATEGORIZED,
array(),
array('Invalid Authorization header format')
);
}
// See ZF-1052. This code was a bit too unforgiving of invalid
// usernames. Now, if the username is bad, we re-challenge the client.
if ('::invalid::' == $data['username']) {
return $this->challengeClient();
}
// Verify that the client sent back the same nonce
if ($this->_calcNonce() != $data['nonce']) {
return $this->challengeClient();
}
// The opaque value is also required to match, but of course IE doesn't
// play ball.
if (!$this->ieNoOpaque && $this->_calcOpaque() != $data['opaque']) {
return $this->challengeClient();
}
// Look up the user's password hash. If not found, deny access.
// This makes no assumptions about how the password hash was
// constructed beyond that it must have been built in such a way as
// to be recreatable with the current settings of this object.
$ha1 = $this->digestResolver->resolve($data['username'], $data['realm']);
if ($ha1 === false) {
return $this->challengeClient();
}
// If MD5-sess is used, a1 value is made of the user's password
// hash with the server and client nonce appended, separated by
// colons.
if ($this->algo == 'MD5-sess') {
$ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']);
}
// Calculate h(a2). The value of this hash depends on the qop
// option selected by the client and the supported hash functions
switch ($data['qop']) {
case 'auth':
$a2 = $this->request->getMethod() . ':' . $data['uri'];
break;
case 'auth-int':
// Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body),
// but this isn't supported yet, so fall through to default case
default:
throw new Exception\RuntimeException('Client requested an unsupported qop option');
}
// Using hash() should make parameterizing the hash algorithm
// easier
$ha2 = hash('md5', $a2);
// Calculate the server's version of the request-digest. This must
// match $data['response']. See RFC 2617, section 3.2.2.1
$message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2;
$digest = hash('md5', $ha1 . ':' . $message);
// If our digest matches the client's let them in, otherwise return
// a 401 code and exit to prevent access to the protected resource.
if (CryptUtils::compareStrings($digest, $data['response'])) {
$identity = array('username' => $data['username'], 'realm' => $data['realm']);
return new Authentication\Result(Authentication\Result::SUCCESS, $identity);
}
return $this->challengeClient();
}
/**
* Calculate Nonce
*
* @return string The nonce value
*/
protected function _calcNonce()
{
// Once subtle consequence of this timeout calculation is that it
// actually divides all of time into nonceTimeout-sized sections, such
// that the value of timeout is the point in time of the next
// approaching "boundary" of a section. This allows the server to
// consistently generate the same timeout (and hence the same nonce
// value) across requests, but only as long as one of those
// "boundaries" is not crossed between requests. If that happens, the
// nonce will change on its own, and effectively log the user out. This
// would be surprising if the user just logged in.
$timeout = ceil(time() / $this->nonceTimeout) * $this->nonceTimeout;
$userAgentHeader = $this->request->getHeaders()->get('User-Agent');
if ($userAgentHeader) {
$userAgent = $userAgentHeader->getFieldValue();
} elseif (isset($_SERVER['HTTP_USER_AGENT'])) {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
} else {
$userAgent = 'Zend_Authenticaion';
}
$nonce = hash('md5', $timeout . ':' . $userAgent . ':' . __CLASS__);
return $nonce;
}
/**
* Calculate Opaque
*
* The opaque string can be anything; the client must return it exactly as
* it was sent. It may be useful to store data in this string in some
* applications. Ideally, a new value for this would be generated each time
* a WWW-Authenticate header is sent (in order to reduce predictability),
* but we would have to be able to create the same exact value across at
* least two separate requests from the same client.
*
* @return string The opaque value
*/
protected function _calcOpaque()
{
return hash('md5', 'Opaque Data:' . __CLASS__);
}
/**
* Parse Digest Authorization header
*
* @param string $header Client's Authorization: HTTP header
* @return array|bool Data elements from header, or false if any part of
* the header is invalid
*/
protected function _parseDigestAuth($header)
{
$temp = null;
$data = array();
// See ZF-1052. Detect invalid usernames instead of just returning a
// 400 code.
$ret = preg_match('/username="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])
|| !ctype_print($temp[1])
|| strpos($temp[1], ':') !== false) {
$data['username'] = '::invalid::';
} else {
$data['username'] = $temp[1];
}
$temp = null;
$ret = preg_match('/realm="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) {
return false;
} else {
$data['realm'] = $temp[1];
}
$temp = null;
$ret = preg_match('/nonce="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_xdigit($temp[1])) {
return false;
}
$data['nonce'] = $temp[1];
$temp = null;
$ret = preg_match('/uri="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
// Section 3.2.2.5 in RFC 2617 says the authenticating server must
// verify that the URI field in the Authorization header is for the
// same resource requested in the Request Line.
$rUri = $this->request->getUri();
$cUri = UriFactory::factory($temp[1]);
// Make sure the path portion of both URIs is the same
if ($rUri->getPath() != $cUri->getPath()) {
return false;
}
// Section 3.2.2.5 seems to suggest that the value of the URI
// Authorization field should be made into an absolute URI if the
// Request URI is absolute, but it's vague, and that's a bunch of
// code I don't want to write right now.
$data['uri'] = $temp[1];
$temp = null;
$ret = preg_match('/response="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
return false;
}
$data['response'] = $temp[1];
$temp = null;
// The spec says this should default to MD5 if omitted. OK, so how does
// that square with the algo we send out in the WWW-Authenticate header,
// if it can easily be overridden by the client?
$ret = preg_match('/algorithm="?(' . $this->algo . ')"?/', $header, $temp);
if ($ret && !empty($temp[1])
&& in_array($temp[1], $this->supportedAlgos)) {
$data['algorithm'] = $temp[1];
} else {
$data['algorithm'] = 'MD5'; // = $this->algo; ?
}
$temp = null;
// Not optional in this implementation
$ret = preg_match('/cnonce="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!ctype_print($temp[1])) {
return false;
}
$data['cnonce'] = $temp[1];
$temp = null;
// If the server sent an opaque value, the client must send it back
if ($this->useOpaque) {
$ret = preg_match('/opaque="([^"]+)"/', $header, $temp);
if (!$ret || empty($temp[1])) {
// Big surprise: IE isn't RFC 2617-compliant.
$headers = $this->request->getHeaders();
if (!$headers->has('User-Agent')) {
return false;
}
$userAgent = $headers->get('User-Agent')->getFieldValue();
if (false === strpos($userAgent, 'MSIE')) {
return false;
}
$temp[1] = '';
$this->ieNoOpaque = true;
}
// This implementation only sends MD5 hex strings in the opaque value
if (!$this->ieNoOpaque &&
(32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) {
return false;
}
$data['opaque'] = $temp[1];
$temp = null;
}
// Not optional in this implementation, but must be one of the supported
// qop types
$ret = preg_match('/qop="?(' . implode('|', $this->supportedQops) . ')"?/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (!in_array($temp[1], $this->supportedQops)) {
return false;
}
$data['qop'] = $temp[1];
$temp = null;
// Not optional in this implementation. The spec says this value
// shouldn't be a quoted string, but apparently some implementations
// quote it anyway. See ZF-1544.
$ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp);
if (!$ret || empty($temp[1])) {
return false;
}
if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) {
return false;
}
$data['nc'] = $temp[1];
$temp = null;
return $data;
}
}
|
// SPDX-License-Identifier: GPL-2.0
//
// Copyright (C) 2016 Freescale Semiconductor, Inc.
// Copyright 2017-2018 NXP.
#include <linux/err.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pinctrl/pinctrl.h>
#include "pinctrl-imx.h"
enum imx6sll_pads {
MX6SLL_PAD_RESERVE0 = 0,
MX6SLL_PAD_RESERVE1 = 1,
MX6SLL_PAD_RESERVE2 = 2,
MX6SLL_PAD_RESERVE3 = 3,
MX6SLL_PAD_RESERVE4 = 4,
MX6SLL_PAD_WDOG_B = 5,
MX6SLL_PAD_REF_CLK_24M = 6,
MX6SLL_PAD_REF_CLK_32K = 7,
MX6SLL_PAD_PWM1 = 8,
MX6SLL_PAD_KEY_COL0 = 9,
MX6SLL_PAD_KEY_ROW0 = 10,
MX6SLL_PAD_KEY_COL1 = 11,
MX6SLL_PAD_KEY_ROW1 = 12,
MX6SLL_PAD_KEY_COL2 = 13,
MX6SLL_PAD_KEY_ROW2 = 14,
MX6SLL_PAD_KEY_COL3 = 15,
MX6SLL_PAD_KEY_ROW3 = 16,
MX6SLL_PAD_KEY_COL4 = 17,
MX6SLL_PAD_KEY_ROW4 = 18,
MX6SLL_PAD_KEY_COL5 = 19,
MX6SLL_PAD_KEY_ROW5 = 20,
MX6SLL_PAD_KEY_COL6 = 21,
MX6SLL_PAD_KEY_ROW6 = 22,
MX6SLL_PAD_KEY_COL7 = 23,
MX6SLL_PAD_KEY_ROW7 = 24,
MX6SLL_PAD_EPDC_DATA00 = 25,
MX6SLL_PAD_EPDC_DATA01 = 26,
MX6SLL_PAD_EPDC_DATA02 = 27,
MX6SLL_PAD_EPDC_DATA03 = 28,
MX6SLL_PAD_EPDC_DATA04 = 29,
MX6SLL_PAD_EPDC_DATA05 = 30,
MX6SLL_PAD_EPDC_DATA06 = 31,
MX6SLL_PAD_EPDC_DATA07 = 32,
MX6SLL_PAD_EPDC_DATA08 = 33,
MX6SLL_PAD_EPDC_DATA09 = 34,
MX6SLL_PAD_EPDC_DATA10 = 35,
MX6SLL_PAD_EPDC_DATA11 = 36,
MX6SLL_PAD_EPDC_DATA12 = 37,
MX6SLL_PAD_EPDC_DATA13 = 38,
MX6SLL_PAD_EPDC_DATA14 = 39,
MX6SLL_PAD_EPDC_DATA15 = 40,
MX6SLL_PAD_EPDC_SDCLK = 41,
MX6SLL_PAD_EPDC_SDLE = 42,
MX6SLL_PAD_EPDC_SDOE = 43,
MX6SLL_PAD_EPDC_SDSHR = 44,
MX6SLL_PAD_EPDC_SDCE0 = 45,
MX6SLL_PAD_EPDC_SDCE1 = 46,
MX6SLL_PAD_EPDC_SDCE2 = 47,
MX6SLL_PAD_EPDC_SDCE3 = 48,
MX6SLL_PAD_EPDC_GDCLK = 49,
MX6SLL_PAD_EPDC_GDOE = 50,
MX6SLL_PAD_EPDC_GDRL = 51,
MX6SLL_PAD_EPDC_GDSP = 52,
MX6SLL_PAD_EPDC_VCOM0 = 53,
MX6SLL_PAD_EPDC_VCOM1 = 54,
MX6SLL_PAD_EPDC_BDR0 = 55,
MX6SLL_PAD_EPDC_BDR1 = 56,
MX6SLL_PAD_EPDC_PWR_CTRL0 = 57,
MX6SLL_PAD_EPDC_PWR_CTRL1 = 58,
MX6SLL_PAD_EPDC_PWR_CTRL2 = 59,
MX6SLL_PAD_EPDC_PWR_CTRL3 = 60,
MX6SLL_PAD_EPDC_PWR_COM = 61,
MX6SLL_PAD_EPDC_PWR_INT = 62,
MX6SLL_PAD_EPDC_PWR_STAT = 63,
MX6SLL_PAD_EPDC_PWR_WAKE = 64,
MX6SLL_PAD_LCD_CLK = 65,
MX6SLL_PAD_LCD_ENABLE = 66,
MX6SLL_PAD_LCD_HSYNC = 67,
MX6SLL_PAD_LCD_VSYNC = 68,
MX6SLL_PAD_LCD_RESET = 69,
MX6SLL_PAD_LCD_DATA00 = 70,
MX6SLL_PAD_LCD_DATA01 = 71,
MX6SLL_PAD_LCD_DATA02 = 72,
MX6SLL_PAD_LCD_DATA03 = 73,
MX6SLL_PAD_LCD_DATA04 = 74,
MX6SLL_PAD_LCD_DATA05 = 75,
MX6SLL_PAD_LCD_DATA06 = 76,
MX6SLL_PAD_LCD_DATA07 = 77,
MX6SLL_PAD_LCD_DATA08 = 78,
MX6SLL_PAD_LCD_DATA09 = 79,
MX6SLL_PAD_LCD_DATA10 = 80,
MX6SLL_PAD_LCD_DATA11 = 81,
MX6SLL_PAD_LCD_DATA12 = 82,
MX6SLL_PAD_LCD_DATA13 = 83,
MX6SLL_PAD_LCD_DATA14 = 84,
MX6SLL_PAD_LCD_DATA15 = 85,
MX6SLL_PAD_LCD_DATA16 = 86,
MX6SLL_PAD_LCD_DATA17 = 87,
MX6SLL_PAD_LCD_DATA18 = 88,
MX6SLL_PAD_LCD_DATA19 = 89,
MX6SLL_PAD_LCD_DATA20 = 90,
MX6SLL_PAD_LCD_DATA21 = 91,
MX6SLL_PAD_LCD_DATA22 = 92,
MX6SLL_PAD_LCD_DATA23 = 93,
MX6SLL_PAD_AUD_RXFS = 94,
MX6SLL_PAD_AUD_RXC = 95,
MX6SLL_PAD_AUD_RXD = 96,
MX6SLL_PAD_AUD_TXC = 97,
MX6SLL_PAD_AUD_TXFS = 98,
MX6SLL_PAD_AUD_TXD = 99,
MX6SLL_PAD_AUD_MCLK = 100,
MX6SLL_PAD_UART1_RXD = 101,
MX6SLL_PAD_UART1_TXD = 102,
MX6SLL_PAD_I2C1_SCL = 103,
MX6SLL_PAD_I2C1_SDA = 104,
MX6SLL_PAD_I2C2_SCL = 105,
MX6SLL_PAD_I2C2_SDA = 106,
MX6SLL_PAD_ECSPI1_SCLK = 107,
MX6SLL_PAD_ECSPI1_MOSI = 108,
MX6SLL_PAD_ECSPI1_MISO = 109,
MX6SLL_PAD_ECSPI1_SS0 = 110,
MX6SLL_PAD_ECSPI2_SCLK = 111,
MX6SLL_PAD_ECSPI2_MOSI = 112,
MX6SLL_PAD_ECSPI2_MISO = 113,
MX6SLL_PAD_ECSPI2_SS0 = 114,
MX6SLL_PAD_SD1_CLK = 115,
MX6SLL_PAD_SD1_CMD = 116,
MX6SLL_PAD_SD1_DATA0 = 117,
MX6SLL_PAD_SD1_DATA1 = 118,
MX6SLL_PAD_SD1_DATA2 = 119,
MX6SLL_PAD_SD1_DATA3 = 120,
MX6SLL_PAD_SD1_DATA4 = 121,
MX6SLL_PAD_SD1_DATA5 = 122,
MX6SLL_PAD_SD1_DATA6 = 123,
MX6SLL_PAD_SD1_DATA7 = 124,
MX6SLL_PAD_SD2_RESET = 125,
MX6SLL_PAD_SD2_CLK = 126,
MX6SLL_PAD_SD2_CMD = 127,
MX6SLL_PAD_SD2_DATA0 = 128,
MX6SLL_PAD_SD2_DATA1 = 129,
MX6SLL_PAD_SD2_DATA2 = 130,
MX6SLL_PAD_SD2_DATA3 = 131,
MX6SLL_PAD_SD2_DATA4 = 132,
MX6SLL_PAD_SD2_DATA5 = 133,
MX6SLL_PAD_SD2_DATA6 = 134,
MX6SLL_PAD_SD2_DATA7 = 135,
MX6SLL_PAD_SD3_CLK = 136,
MX6SLL_PAD_SD3_CMD = 137,
MX6SLL_PAD_SD3_DATA0 = 138,
MX6SLL_PAD_SD3_DATA1 = 139,
MX6SLL_PAD_SD3_DATA2 = 140,
MX6SLL_PAD_SD3_DATA3 = 141,
MX6SLL_PAD_GPIO4_IO20 = 142,
MX6SLL_PAD_GPIO4_IO21 = 143,
MX6SLL_PAD_GPIO4_IO19 = 144,
MX6SLL_PAD_GPIO4_IO25 = 145,
MX6SLL_PAD_GPIO4_IO18 = 146,
MX6SLL_PAD_GPIO4_IO24 = 147,
MX6SLL_PAD_GPIO4_IO23 = 148,
MX6SLL_PAD_GPIO4_IO17 = 149,
MX6SLL_PAD_GPIO4_IO22 = 150,
MX6SLL_PAD_GPIO4_IO16 = 151,
MX6SLL_PAD_GPIO4_IO26 = 152,
};
/* Pad names for the pinmux subsystem */
static const struct pinctrl_pin_desc imx6sll_pinctrl_pads[] = {
IMX_PINCTRL_PIN(MX6SLL_PAD_RESERVE0),
IMX_PINCTRL_PIN(MX6SLL_PAD_RESERVE1),
IMX_PINCTRL_PIN(MX6SLL_PAD_RESERVE2),
IMX_PINCTRL_PIN(MX6SLL_PAD_RESERVE3),
IMX_PINCTRL_PIN(MX6SLL_PAD_RESERVE4),
IMX_PINCTRL_PIN(MX6SLL_PAD_WDOG_B),
IMX_PINCTRL_PIN(MX6SLL_PAD_REF_CLK_24M),
IMX_PINCTRL_PIN(MX6SLL_PAD_REF_CLK_32K),
IMX_PINCTRL_PIN(MX6SLL_PAD_PWM1),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL0),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW0),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL1),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW1),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL2),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW2),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL3),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW3),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL4),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW4),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL5),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW5),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL6),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW6),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_COL7),
IMX_PINCTRL_PIN(MX6SLL_PAD_KEY_ROW7),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA00),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA01),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA02),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA03),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA04),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA05),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA06),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA07),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA08),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA09),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA10),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA11),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA12),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA13),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA14),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_DATA15),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDCLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDLE),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDOE),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDSHR),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDCE0),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDCE1),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDCE2),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_SDCE3),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_GDCLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_GDOE),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_GDRL),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_GDSP),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_VCOM0),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_VCOM1),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_BDR0),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_BDR1),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_CTRL0),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_CTRL1),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_CTRL2),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_CTRL3),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_COM),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_INT),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_STAT),
IMX_PINCTRL_PIN(MX6SLL_PAD_EPDC_PWR_WAKE),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_CLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_ENABLE),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_HSYNC),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_VSYNC),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_RESET),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA00),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA01),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA02),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA03),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA04),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA05),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA06),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA07),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA08),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA09),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA10),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA11),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA12),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA13),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA14),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA15),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA16),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA17),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA18),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA19),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA20),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA21),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA22),
IMX_PINCTRL_PIN(MX6SLL_PAD_LCD_DATA23),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_RXFS),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_RXC),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_RXD),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_TXC),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_TXFS),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_TXD),
IMX_PINCTRL_PIN(MX6SLL_PAD_AUD_MCLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_UART1_RXD),
IMX_PINCTRL_PIN(MX6SLL_PAD_UART1_TXD),
IMX_PINCTRL_PIN(MX6SLL_PAD_I2C1_SCL),
IMX_PINCTRL_PIN(MX6SLL_PAD_I2C1_SDA),
IMX_PINCTRL_PIN(MX6SLL_PAD_I2C2_SCL),
IMX_PINCTRL_PIN(MX6SLL_PAD_I2C2_SDA),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI1_SCLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI1_MOSI),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI1_MISO),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI1_SS0),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI2_SCLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI2_MOSI),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI2_MISO),
IMX_PINCTRL_PIN(MX6SLL_PAD_ECSPI2_SS0),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_CLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_CMD),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA0),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA1),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA2),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA3),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA4),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA5),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA6),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD1_DATA7),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_RESET),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_CLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_CMD),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA0),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA1),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA2),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA3),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA4),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA5),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA6),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD2_DATA7),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_CLK),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_CMD),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_DATA0),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_DATA1),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_DATA2),
IMX_PINCTRL_PIN(MX6SLL_PAD_SD3_DATA3),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO20),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO21),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO19),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO25),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO18),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO24),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO23),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO17),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO22),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO16),
IMX_PINCTRL_PIN(MX6SLL_PAD_GPIO4_IO26),
};
static const struct imx_pinctrl_soc_info imx6sll_pinctrl_info = {
.pins = imx6sll_pinctrl_pads,
.npins = ARRAY_SIZE(imx6sll_pinctrl_pads),
.gpr_compatible = "fsl,imx6sll-iomuxc-gpr",
};
static const struct of_device_id imx6sll_pinctrl_of_match[] = {
{ .compatible = "fsl,imx6sll-iomuxc", .data = &imx6sll_pinctrl_info, },
{ /* sentinel */ }
};
static int imx6sll_pinctrl_probe(struct platform_device *pdev)
{
return imx_pinctrl_probe(pdev, &imx6sll_pinctrl_info);
}
static struct platform_driver imx6sll_pinctrl_driver = {
.driver = {
.name = "imx6sll-pinctrl",
.of_match_table = imx6sll_pinctrl_of_match,
.suppress_bind_attrs = true,
},
.probe = imx6sll_pinctrl_probe,
};
static int __init imx6sll_pinctrl_init(void)
{
return platform_driver_register(&imx6sll_pinctrl_driver);
}
arch_initcall(imx6sll_pinctrl_init);
|
tinymce.addI18n('fi',{
"Cut": "Leikkaa",
"Header 2": "Otsikko 2",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Selaimesi ei tue leikekirjan suoraa k\u00e4ytt\u00e4mist\u00e4. Ole hyv\u00e4 ja k\u00e4yt\u00e4 n\u00e4pp\u00e4imist\u00f6n Ctrl+X ja Ctrl+V n\u00e4pp\u00e4inyhdistelmi\u00e4.",
"Div": "Div",
"Paste": "Liit\u00e4",
"Close": "Sulje",
"Font Family": "Fontti",
"Pre": "Esimuotoiltu",
"Align right": "Tasaa oikealle",
"New document": "Uusi dokumentti",
"Blockquote": "Lainauslohko",
"Numbered list": "J\u00e4rjestetty lista",
"Increase indent": "Loitonna",
"Formats": "Muotoilut",
"Headers": "Otsikot",
"Select all": "Valitse kaikki",
"Header 3": "Otsikko 3",
"Blocks": "Lohkot",
"Undo": "Peru",
"Strikethrough": "Yliviivaus",
"Bullet list": "J\u00e4rjest\u00e4m\u00e4t\u00f6n lista",
"Header 1": "Otsikko 1",
"Superscript": "Yl\u00e4indeksi",
"Clear formatting": "Poista muotoilu",
"Font Sizes": "Fonttikoko",
"Subscript": "Alaindeksi",
"Header 6": "Otsikko 6",
"Redo": "Tee uudelleen",
"Paragraph": "Kappale",
"Ok": "Ok",
"Bold": "Lihavointi",
"Code": "Koodi",
"Italic": "Kursivointi",
"Align center": "Keskit\u00e4",
"Header 5": "Otsikko 5",
"Decrease indent": "Sisenn\u00e4",
"Header 4": "Otsikko 4",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Liitt\u00e4minen on nyt pelk\u00e4n tekstin -tilassa. Sis\u00e4ll\u00f6t liitet\u00e4\u00e4n nyt pelkk\u00e4n\u00e4 tekstin\u00e4, kunnes otat vaihtoehdon pois k\u00e4yt\u00f6st\u00e4.",
"Underline": "Alleviivaus",
"Cancel": "Peruuta",
"Justify": "Tasaa",
"Inline": "Samalla rivill\u00e4",
"Copy": "Kopioi",
"Align left": "Tasaa vasemmalle",
"Visual aids": "Visuaaliset neuvot",
"Lower Greek": "pienet kirjaimet: \u03b1, \u03b2, \u03b3",
"Square": "Neli\u00f6",
"Default": "Oletus",
"Lower Alpha": "pienet kirjaimet: a, b, c",
"Circle": "Pallo",
"Disc": "Ympyr\u00e4",
"Upper Alpha": "isot kirjaimet: A, B, C",
"Upper Roman": "isot kirjaimet: I, II, III",
"Lower Roman": "pienet kirjaimet: i, ii, iii",
"Name": "Nimi",
"Anchor": "Ankkuri",
"You have unsaved changes are you sure you want to navigate away?": "Sinulla on tallentamattomia muutoksia, haluatko varmasti siirty\u00e4 toiselle sivulle?",
"Restore last draft": "Palauta aiempi luonnos",
"Special character": "Erikoismerkki",
"Source code": "L\u00e4hdekoodi",
"Right to left": "Oikealta vasemmalle",
"Left to right": "Vasemmalta oikealle",
"Emoticons": "Hymi\u00f6t",
"Robots": "Robotit",
"Document properties": "Dokumentin ominaisuudet",
"Title": "Otsikko",
"Keywords": "Avainsanat",
"Encoding": "Merkist\u00f6",
"Description": "Kuvaus",
"Author": "Tekij\u00e4",
"Fullscreen": "Koko ruutu",
"Horizontal line": "Vaakasuora viiva",
"Horizontal space": "Horisontaalinen tila",
"Insert\/edit image": "Lis\u00e4\u00e4\/muokkaa kuva",
"General": "Yleiset",
"Advanced": "Lis\u00e4asetukset",
"Source": "L\u00e4hde",
"Border": "Reunus",
"Constrain proportions": "S\u00e4ilyt\u00e4 mittasuhteet",
"Vertical space": "Vertikaalinen tila",
"Image description": "Kuvaus",
"Style": "Tyyli",
"Dimensions": "Mittasuhteet",
"Insert image": "Lis\u00e4\u00e4 kuva",
"Insert date\/time": "Lis\u00e4\u00e4 p\u00e4iv\u00e4m\u00e4\u00e4r\u00e4 tai aika",
"Remove link": "Poista linkki",
"Url": "Osoite",
"Text to display": "N\u00e4ytett\u00e4v\u00e4 teksti",
"Anchors": "Ankkurit",
"Insert link": "Lis\u00e4\u00e4 linkki",
"New window": "Uusi ikkuna",
"None": "Ei mit\u00e4\u00e4n",
"Target": "Kohde",
"Insert\/edit link": "Lis\u00e4\u00e4 tai muokkaa linkki",
"Insert\/edit video": "Lis\u00e4\u00e4 tai muokkaa video",
"Poster": "L\u00e4hett\u00e4j\u00e4",
"Alternative source": "Vaihtoehtoinen l\u00e4hde",
"Paste your embed code below:": "Liit\u00e4 upotuskoodisi alapuolelle:",
"Insert video": "Lis\u00e4\u00e4 video",
"Embed": "Upota",
"Nonbreaking space": "Tyhj\u00e4 merkki (nbsp)",
"Page break": "Sivunvaihto",
"Paste as text": "Liit\u00e4 tekstin\u00e4",
"Preview": "Esikatselu",
"Print": "Tulosta",
"Save": "Tallenna",
"Could not find the specified string.": "Haettua merkkijonoa ei l\u00f6ytynyt.",
"Replace": "Korvaa",
"Next": "Seur.",
"Whole words": "Koko sanat",
"Find and replace": "Etsi ja korvaa",
"Replace with": "Korvaa",
"Find": "Etsi",
"Replace all": "Korvaa kaikki",
"Match case": "Erota isot ja pienet kirjaimet",
"Prev": "Edel.",
"Spellcheck": "Oikolue",
"Finish": "Lopeta",
"Ignore all": "\u00c4l\u00e4 huomioi mit\u00e4\u00e4n",
"Ignore": "\u00c4l\u00e4 huomioi",
"Insert row before": "Lis\u00e4\u00e4 rivi ennen",
"Rows": "Rivit",
"Height": "Korkeus",
"Paste row after": "Liit\u00e4 rivi j\u00e4lkeen",
"Alignment": "Tasaus",
"Column group": "Sarakeryhm\u00e4",
"Row": "Rivi",
"Insert column before": "Lis\u00e4\u00e4 rivi ennen",
"Split cell": "Jaa solu",
"Cell padding": "Solun tyhj\u00e4 tila",
"Cell spacing": "Solun v\u00e4li",
"Row type": "Rivityyppi",
"Insert table": "Lis\u00e4\u00e4 taulukko",
"Body": "Runko",
"Caption": "Seloste",
"Footer": "Alaosa",
"Delete row": "Poista rivi",
"Paste row before": "Liit\u00e4 rivi ennen",
"Scope": "Laajuus",
"Delete table": "Poista taulukko",
"Header cell": "Otsikkosolu",
"Column": "Sarake",
"Cell": "Solu",
"Header": "Otsikko",
"Cell type": "Solun tyyppi",
"Copy row": "Kopioi rivi",
"Row properties": "Rivin ominaisuudet",
"Table properties": "Taulukon ominaisuudet",
"Row group": "Riviryhm\u00e4",
"Right": "Oikea",
"Insert column after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen",
"Cols": "Sarakkeet",
"Insert row after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen",
"Width": "Leveys",
"Cell properties": "Solun ominaisuudet",
"Left": "Vasen",
"Cut row": "Leikkaa rivi",
"Delete column": "Poista sarake",
"Center": "Keskell\u00e4",
"Merge cells": "Yhdist\u00e4 solut",
"Insert template": "Lis\u00e4\u00e4 pohja",
"Templates": "Pohjat",
"Background color": "Taustan v\u00e4ri",
"Text color": "Tekstin v\u00e4ri",
"Show blocks": "N\u00e4yt\u00e4 lohkot",
"Show invisible characters": "N\u00e4yt\u00e4 n\u00e4kym\u00e4tt\u00f6m\u00e4t merkit",
"Words: {0}": "Sanat: {0}",
"Insert": "Lis\u00e4\u00e4",
"File": "Tiedosto",
"Edit": "Muokkaa",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rikastetun tekstin alue. Paina ALT-F9 valikkoon. Paina ALT-F10 ty\u00f6kaluriviin. Paina ALT-0 ohjeeseen.",
"Tools": "Ty\u00f6kalut",
"View": "N\u00e4yt\u00e4",
"Table": "Taulukko",
"Format": "Muotoilu"
}); |
/* DO NOT EDIT THIS FILE
* Automatically generated by generate-def-headers.xsl
* DO NOT EDIT THIS FILE
*/
#ifndef __BFIN_DEF_ADSP_BF541_proc__
#define __BFIN_DEF_ADSP_BF541_proc__
#include "../mach-common/ADSP-EDN-core_def.h"
#include "ADSP-EDN-BF542-extended_def.h"
#define CHIPID 0xFFC00014
#define SWRST 0xFFC00100 /* Software Reset Register */
#define SYSCR 0xFFC00104 /* System Configuration register */
#define SRAM_BASE_ADDR 0xFFE00000 /* SRAM Base Address (Read Only) */
#define DMEM_CONTROL 0xFFE00004 /* Data memory control */
#define DCPLB_STATUS 0xFFE00008 /* Data Cache Programmable Look-Aside Buffer Status */
#define DCPLB_FAULT_ADDR 0xFFE0000C /* Data Cache Programmable Look-Aside Buffer Fault Address */
#define DCPLB_ADDR0 0xFFE00100 /* Data Cache Protection Lookaside Buffer 0 */
#define DCPLB_ADDR1 0xFFE00104 /* Data Cache Protection Lookaside Buffer 1 */
#define DCPLB_ADDR2 0xFFE00108 /* Data Cache Protection Lookaside Buffer 2 */
#define DCPLB_ADDR3 0xFFE0010C /* Data Cache Protection Lookaside Buffer 3 */
#define DCPLB_ADDR4 0xFFE00110 /* Data Cache Protection Lookaside Buffer 4 */
#define DCPLB_ADDR5 0xFFE00114 /* Data Cache Protection Lookaside Buffer 5 */
#define DCPLB_ADDR6 0xFFE00118 /* Data Cache Protection Lookaside Buffer 6 */
#define DCPLB_ADDR7 0xFFE0011C /* Data Cache Protection Lookaside Buffer 7 */
#define DCPLB_ADDR8 0xFFE00120 /* Data Cache Protection Lookaside Buffer 8 */
#define DCPLB_ADDR9 0xFFE00124 /* Data Cache Protection Lookaside Buffer 9 */
#define DCPLB_ADDR10 0xFFE00128 /* Data Cache Protection Lookaside Buffer 10 */
#define DCPLB_ADDR11 0xFFE0012C /* Data Cache Protection Lookaside Buffer 11 */
#define DCPLB_ADDR12 0xFFE00130 /* Data Cache Protection Lookaside Buffer 12 */
#define DCPLB_ADDR13 0xFFE00134 /* Data Cache Protection Lookaside Buffer 13 */
#define DCPLB_ADDR14 0xFFE00138 /* Data Cache Protection Lookaside Buffer 14 */
#define DCPLB_ADDR15 0xFFE0013C /* Data Cache Protection Lookaside Buffer 15 */
#define DCPLB_DATA0 0xFFE00200 /* Data Cache 0 Status */
#define DCPLB_DATA1 0xFFE00204 /* Data Cache 1 Status */
#define DCPLB_DATA2 0xFFE00208 /* Data Cache 2 Status */
#define DCPLB_DATA3 0xFFE0020C /* Data Cache 3 Status */
#define DCPLB_DATA4 0xFFE00210 /* Data Cache 4 Status */
#define DCPLB_DATA5 0xFFE00214 /* Data Cache 5 Status */
#define DCPLB_DATA6 0xFFE00218 /* Data Cache 6 Status */
#define DCPLB_DATA7 0xFFE0021C /* Data Cache 7 Status */
#define DCPLB_DATA8 0xFFE00220 /* Data Cache 8 Status */
#define DCPLB_DATA9 0xFFE00224 /* Data Cache 9 Status */
#define DCPLB_DATA10 0xFFE00228 /* Data Cache 10 Status */
#define DCPLB_DATA11 0xFFE0022C /* Data Cache 11 Status */
#define DCPLB_DATA12 0xFFE00230 /* Data Cache 12 Status */
#define DCPLB_DATA13 0xFFE00234 /* Data Cache 13 Status */
#define DCPLB_DATA14 0xFFE00238 /* Data Cache 14 Status */
#define DCPLB_DATA15 0xFFE0023C /* Data Cache 15 Status */
#define DTEST_COMMAND 0xFFE00300 /* Data Test Command Register */
#define DTEST_DATA0 0xFFE00400 /* Data Test Data Register */
#define DTEST_DATA1 0xFFE00404 /* Data Test Data Register */
#define IMEM_CONTROL 0xFFE01004 /* Instruction Memory Control */
#define ICPLB_STATUS 0xFFE01008 /* Instruction Cache Programmable Look-Aside Buffer Status */
#define ICPLB_FAULT_ADDR 0xFFE0100C /* Instruction Cache Programmable Look-Aside Buffer Fault Address */
#define ICPLB_ADDR0 0xFFE01100 /* Instruction Cacheability Protection Lookaside Buffer 0 */
#define ICPLB_ADDR1 0xFFE01104 /* Instruction Cacheability Protection Lookaside Buffer 1 */
#define ICPLB_ADDR2 0xFFE01108 /* Instruction Cacheability Protection Lookaside Buffer 2 */
#define ICPLB_ADDR3 0xFFE0110C /* Instruction Cacheability Protection Lookaside Buffer 3 */
#define ICPLB_ADDR4 0xFFE01110 /* Instruction Cacheability Protection Lookaside Buffer 4 */
#define ICPLB_ADDR5 0xFFE01114 /* Instruction Cacheability Protection Lookaside Buffer 5 */
#define ICPLB_ADDR6 0xFFE01118 /* Instruction Cacheability Protection Lookaside Buffer 6 */
#define ICPLB_ADDR7 0xFFE0111C /* Instruction Cacheability Protection Lookaside Buffer 7 */
#define ICPLB_ADDR8 0xFFE01120 /* Instruction Cacheability Protection Lookaside Buffer 8 */
#define ICPLB_ADDR9 0xFFE01124 /* Instruction Cacheability Protection Lookaside Buffer 9 */
#define ICPLB_ADDR10 0xFFE01128 /* Instruction Cacheability Protection Lookaside Buffer 10 */
#define ICPLB_ADDR11 0xFFE0112C /* Instruction Cacheability Protection Lookaside Buffer 11 */
#define ICPLB_ADDR12 0xFFE01130 /* Instruction Cacheability Protection Lookaside Buffer 12 */
#define ICPLB_ADDR13 0xFFE01134 /* Instruction Cacheability Protection Lookaside Buffer 13 */
#define ICPLB_ADDR14 0xFFE01138 /* Instruction Cacheability Protection Lookaside Buffer 14 */
#define ICPLB_ADDR15 0xFFE0113C /* Instruction Cacheability Protection Lookaside Buffer 15 */
#define ICPLB_DATA0 0xFFE01200 /* Instruction Cache 0 Status */
#define ICPLB_DATA1 0xFFE01204 /* Instruction Cache 1 Status */
#define ICPLB_DATA2 0xFFE01208 /* Instruction Cache 2 Status */
#define ICPLB_DATA3 0xFFE0120C /* Instruction Cache 3 Status */
#define ICPLB_DATA4 0xFFE01210 /* Instruction Cache 4 Status */
#define ICPLB_DATA5 0xFFE01214 /* Instruction Cache 5 Status */
#define ICPLB_DATA6 0xFFE01218 /* Instruction Cache 6 Status */
#define ICPLB_DATA7 0xFFE0121C /* Instruction Cache 7 Status */
#define ICPLB_DATA8 0xFFE01220 /* Instruction Cache 8 Status */
#define ICPLB_DATA9 0xFFE01224 /* Instruction Cache 9 Status */
#define ICPLB_DATA10 0xFFE01228 /* Instruction Cache 10 Status */
#define ICPLB_DATA11 0xFFE0122C /* Instruction Cache 11 Status */
#define ICPLB_DATA12 0xFFE01230 /* Instruction Cache 12 Status */
#define ICPLB_DATA13 0xFFE01234 /* Instruction Cache 13 Status */
#define ICPLB_DATA14 0xFFE01238 /* Instruction Cache 14 Status */
#define ICPLB_DATA15 0xFFE0123C /* Instruction Cache 15 Status */
#define ITEST_COMMAND 0xFFE01300 /* Instruction Test Command Register */
#define ITEST_DATA0 0xFFE01400 /* Instruction Test Data Register */
#define ITEST_DATA1 0xFFE01404 /* Instruction Test Data Register */
#define EVT0 0xFFE02000 /* Event Vector 0 ESR Address */
#define EVT1 0xFFE02004 /* Event Vector 1 ESR Address */
#define EVT2 0xFFE02008 /* Event Vector 2 ESR Address */
#define EVT3 0xFFE0200C /* Event Vector 3 ESR Address */
#define EVT4 0xFFE02010 /* Event Vector 4 ESR Address */
#define EVT5 0xFFE02014 /* Event Vector 5 ESR Address */
#define EVT6 0xFFE02018 /* Event Vector 6 ESR Address */
#define EVT7 0xFFE0201C /* Event Vector 7 ESR Address */
#define EVT8 0xFFE02020 /* Event Vector 8 ESR Address */
#define EVT9 0xFFE02024 /* Event Vector 9 ESR Address */
#define EVT10 0xFFE02028 /* Event Vector 10 ESR Address */
#define EVT11 0xFFE0202C /* Event Vector 11 ESR Address */
#define EVT12 0xFFE02030 /* Event Vector 12 ESR Address */
#define EVT13 0xFFE02034 /* Event Vector 13 ESR Address */
#define EVT14 0xFFE02038 /* Event Vector 14 ESR Address */
#define EVT15 0xFFE0203C /* Event Vector 15 ESR Address */
#define ILAT 0xFFE0210C /* Interrupt Latch Register */
#define IMASK 0xFFE02104 /* Interrupt Mask Register */
#define IPEND 0xFFE02108 /* Interrupt Pending Register */
#define IPRIO 0xFFE02110 /* Interrupt Priority Register */
#define TBUFCTL 0xFFE06000 /* Trace Buffer Control Register */
#define TBUFSTAT 0xFFE06004 /* Trace Buffer Status Register */
#define TBUF 0xFFE06100 /* Trace Buffer */
#endif /* __BFIN_DEF_ADSP_BF541_proc__ */
|
#! /usr/bin/python
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER 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.
"""Tests for google.protobuf.pyext behavior."""
__author__ = 'anuraag@google.com (Anuraag Agrawal)'
import os
os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION'] = '2'
# We must set the implementation version above before the google3 imports.
# pylint: disable=g-import-not-at-top
from google.apputils import basetest
from google.protobuf.internal import api_implementation
# Run all tests from the original module by putting them in our namespace.
# pylint: disable=wildcard-import
from google.protobuf.internal.descriptor_test import *
class ConfirmCppApi2Test(basetest.TestCase):
def testImplementationSetting(self):
self.assertEqual('cpp', api_implementation.Type())
self.assertEqual(2, api_implementation.Version())
if __name__ == '__main__':
basetest.main()
|
package im.actor.messenger.app.fragment.group;
import android.os.Bundle;
import im.actor.messenger.R;
import im.actor.messenger.app.activity.BaseFragmentActivity;
/**
* Created by korka on 25.05.15.
*/
public class JoinPublicGroupActivity extends BaseFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setTitle(R.string.join_public_group_title);
if (savedInstanceState == null) {
showFragment(new JoinPublicGroupFragment(), false, false);
}
}
}
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.model.java;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElement;
/**
* @author nik
*/
public interface JpsJavaDependencyExtension extends JpsElement {
boolean isExported();
void setExported(boolean exported);
@NotNull
JpsJavaDependencyScope getScope();
void setScope(@NotNull JpsJavaDependencyScope scope);
}
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for TransformedDistribution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
from tensorflow.contrib import distributions
from tensorflow.contrib import linalg
from tensorflow.contrib.distributions.python.ops import bijectors
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
bs = bijectors
ds = distributions
la = linalg
class TransformedDistributionTest(test.TestCase):
def _cls(self):
return ds.TransformedDistribution
def testTransformedDistribution(self):
g = ops.Graph()
with g.as_default():
mu = 3.0
sigma = 2.0
# Note: the Jacobian callable only works for this example; more generally
# you may or may not need a reduce_sum.
log_normal = self._cls()(
distribution=ds.Normal(loc=mu, scale=sigma),
bijector=bs.Exp(event_ndims=0))
sp_dist = stats.lognorm(s=sigma, scale=np.exp(mu))
# sample
sample = log_normal.sample(100000, seed=235)
self.assertAllEqual([], log_normal.event_shape)
with self.test_session(graph=g):
self.assertAllEqual([], log_normal.event_shape_tensor().eval())
self.assertAllClose(
sp_dist.mean(), np.mean(sample.eval()), atol=0.0, rtol=0.05)
# pdf, log_pdf, cdf, etc...
# The mean of the lognormal is around 148.
test_vals = np.linspace(0.1, 1000., num=20).astype(np.float32)
for func in [[log_normal.log_prob, sp_dist.logpdf],
[log_normal.prob, sp_dist.pdf],
[log_normal.log_cdf, sp_dist.logcdf],
[log_normal.cdf, sp_dist.cdf],
[log_normal.survival_function, sp_dist.sf],
[log_normal.log_survival_function, sp_dist.logsf]]:
actual = func[0](test_vals)
expected = func[1](test_vals)
with self.test_session(graph=g):
self.assertAllClose(expected, actual.eval(), atol=0, rtol=0.01)
def testCachedSamplesWithoutInverse(self):
with self.test_session() as sess:
mu = 3.0
sigma = 0.02
log_normal = self._cls()(
distribution=ds.Normal(loc=mu, scale=sigma),
bijector=bs.Exp(event_ndims=0))
sample = log_normal.sample(1)
sample_val, log_pdf_val = sess.run([sample, log_normal.log_prob(sample)])
self.assertAllClose(
stats.lognorm.logpdf(sample_val, s=sigma, scale=np.exp(mu)),
log_pdf_val,
atol=1e-2)
def testShapeChangingBijector(self):
with self.test_session():
softmax = bs.SoftmaxCentered()
standard_normal = ds.Normal(loc=0., scale=1.)
multi_logit_normal = self._cls()(
distribution=standard_normal,
bijector=softmax)
x = [[-np.log(3.), 0.],
[np.log(3), np.log(5)]]
y = softmax.forward(x).eval()
expected_log_pdf = (stats.norm(loc=0., scale=1.).logpdf(x) -
np.sum(np.log(y), axis=-1))
self.assertAllClose(expected_log_pdf,
multi_logit_normal.log_prob(y).eval())
self.assertAllClose(
[1, 2, 3, 2],
array_ops.shape(multi_logit_normal.sample([1, 2, 3])).eval())
self.assertAllEqual([2], multi_logit_normal.event_shape)
self.assertAllEqual([2], multi_logit_normal.event_shape_tensor().eval())
def testEntropy(self):
with self.test_session():
shift = np.array([[-1, 0, 1], [-1, -2, -3]], dtype=np.float32)
diag = np.array([[1, 2, 3], [2, 3, 2]], dtype=np.float32)
actual_mvn_entropy = np.concatenate([
[stats.multivariate_normal(shift[i], np.diag(diag[i]**2)).entropy()]
for i in range(len(diag))])
fake_mvn = self._cls()(
ds.MultivariateNormalDiag(
loc=array_ops.zeros_like(shift),
scale_diag=array_ops.ones_like(diag),
validate_args=True),
bs.AffineLinearOperator(
shift,
scale=la.LinearOperatorDiag(diag, is_non_singular=True),
validate_args=True),
validate_args=True)
self.assertAllClose(actual_mvn_entropy,
fake_mvn.entropy().eval())
class ScalarToMultiTest(test.TestCase):
def _cls(self):
return ds.TransformedDistribution
def setUp(self):
self._shift = np.array([-1, 0, 1], dtype=np.float32)
self._tril = np.array([[[1., 0, 0],
[2, 1, 0],
[3, 2, 1]],
[[2, 0, 0],
[3, 2, 0],
[4, 3, 2]]],
dtype=np.float32)
def _testMVN(self,
base_distribution_class,
base_distribution_kwargs,
batch_shape=(),
event_shape=(),
not_implemented_message=None):
with self.test_session() as sess:
# Overriding shapes must be compatible w/bijector; most bijectors are
# batch_shape agnostic and only care about event_ndims.
# In the case of `Affine`, if we got it wrong then it would fire an
# exception due to incompatible dimensions.
batch_shape_pl = array_ops.placeholder(
dtypes.int32, name="dynamic_batch_shape")
event_shape_pl = array_ops.placeholder(
dtypes.int32, name="dynamic_event_shape")
feed_dict = {batch_shape_pl: np.array(batch_shape, dtype=np.int32),
event_shape_pl: np.array(event_shape, dtype=np.int32)}
fake_mvn_dynamic = self._cls()(
distribution=base_distribution_class(validate_args=True,
**base_distribution_kwargs),
bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
batch_shape=batch_shape_pl,
event_shape=event_shape_pl,
validate_args=True)
fake_mvn_static = self._cls()(
distribution=base_distribution_class(validate_args=True,
**base_distribution_kwargs),
bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
batch_shape=batch_shape,
event_shape=event_shape,
validate_args=True)
actual_mean = np.tile(self._shift, [2, 1]) # Affine elided this tile.
actual_cov = np.matmul(self._tril, np.transpose(self._tril, [0, 2, 1]))
def actual_mvn_log_prob(x):
return np.concatenate([
[stats.multivariate_normal(
actual_mean[i], actual_cov[i]).logpdf(x[:, i, :])]
for i in range(len(actual_cov))]).T
actual_mvn_entropy = np.concatenate([
[stats.multivariate_normal(
actual_mean[i], actual_cov[i]).entropy()]
for i in range(len(actual_cov))])
self.assertAllEqual([3], fake_mvn_static.event_shape)
self.assertAllEqual([2], fake_mvn_static.batch_shape)
self.assertAllEqual(tensor_shape.TensorShape(None),
fake_mvn_dynamic.event_shape)
self.assertAllEqual(tensor_shape.TensorShape(None),
fake_mvn_dynamic.batch_shape)
x = fake_mvn_static.sample(5, seed=0).eval()
for unsupported_fn in (fake_mvn_static.log_cdf,
fake_mvn_static.cdf,
fake_mvn_static.survival_function,
fake_mvn_static.log_survival_function):
with self.assertRaisesRegexp(NotImplementedError,
not_implemented_message):
unsupported_fn(x)
num_samples = 5e3
for fake_mvn, feed_dict in ((fake_mvn_static, {}),
(fake_mvn_dynamic, feed_dict)):
# Ensure sample works by checking first, second moments.
y = fake_mvn.sample(int(num_samples), seed=0)
x = y[0:5, ...]
sample_mean = math_ops.reduce_mean(y, 0)
centered_y = array_ops.transpose(y - sample_mean, [1, 2, 0])
sample_cov = math_ops.matmul(
centered_y, centered_y, transpose_b=True) / num_samples
[
sample_mean_,
sample_cov_,
x_,
fake_event_shape_,
fake_batch_shape_,
fake_log_prob_,
fake_prob_,
fake_entropy_,
] = sess.run([
sample_mean,
sample_cov,
x,
fake_mvn.event_shape_tensor(),
fake_mvn.batch_shape_tensor(),
fake_mvn.log_prob(x),
fake_mvn.prob(x),
fake_mvn.entropy(),
], feed_dict=feed_dict)
self.assertAllClose(actual_mean, sample_mean_, atol=0.1, rtol=0.1)
self.assertAllClose(actual_cov, sample_cov_, atol=0., rtol=0.1)
# Ensure all other functions work as intended.
self.assertAllEqual([5, 2, 3], x_.shape)
self.assertAllEqual([3], fake_event_shape_)
self.assertAllEqual([2], fake_batch_shape_)
self.assertAllClose(actual_mvn_log_prob(x_), fake_log_prob_,
atol=0., rtol=1e-6)
self.assertAllClose(np.exp(actual_mvn_log_prob(x_)), fake_prob_,
atol=0., rtol=1e-5)
self.assertAllClose(actual_mvn_entropy, fake_entropy_,
atol=0., rtol=1e-6)
def testScalarBatchScalarEvent(self):
self._testMVN(
base_distribution_class=ds.Normal,
base_distribution_kwargs={"loc": 0., "scale": 1.},
batch_shape=[2],
event_shape=[3],
not_implemented_message="not implemented when overriding event_shape")
def testScalarBatchNonScalarEvent(self):
self._testMVN(
base_distribution_class=ds.MultivariateNormalDiag,
base_distribution_kwargs={"loc": [0., 0., 0.],
"scale_diag": [1., 1, 1]},
batch_shape=[2],
not_implemented_message="not implemented")
with self.test_session():
# Can't override event_shape for scalar batch, non-scalar event.
with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
self._cls()(
distribution=ds.MultivariateNormalDiag(loc=[0.], scale_diag=[1.]),
bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
batch_shape=[2],
event_shape=[3],
validate_args=True)
def testNonScalarBatchScalarEvent(self):
self._testMVN(
base_distribution_class=ds.Normal,
base_distribution_kwargs={"loc": [0., 0], "scale": [1., 1]},
event_shape=[3],
not_implemented_message="not implemented when overriding event_shape")
with self.test_session():
# Can't override batch_shape for non-scalar batch, scalar event.
with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
self._cls()(
distribution=ds.Normal(loc=[0.], scale=[1.]),
bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
batch_shape=[2],
event_shape=[3],
validate_args=True)
def testNonScalarBatchNonScalarEvent(self):
with self.test_session():
# Can't override event_shape and/or batch_shape for non_scalar batch,
# non-scalar event.
with self.assertRaisesRegexp(ValueError, "base distribution not scalar"):
self._cls()(
distribution=ds.MultivariateNormalDiag(loc=[[0.]],
scale_diag=[[1.]]),
bijector=bs.Affine(shift=self._shift, scale_tril=self._tril),
batch_shape=[2],
event_shape=[3],
validate_args=True)
if __name__ == "__main__":
test.main()
|
<?php
class WP_SendGrid_Settings {
// Unique identifier for the settings page
const SETTINGS_PAGE_SLUG = 'wp-sendgrid-settings';
const SETTINGS_SECTION_ID = 'wp-sendgrid-account-settings';
// Where WP SendGrid settings are stored
const SETTINGS_OPTION_NAME = 'wp_sendgrid_options';
const SETTINGS_NETWORK_OPTION_NAME = 'wp_sendgrid_network_options';
// Constants to hold the API access options
const API_REST = 'rest';
const API_SMTP = 'smtp';
private static $settings;
private static $default_settings = array(
'username' => '',
'password' => '',
'api' => self::API_REST,
'secure' => false
);
public static function start() {
add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );
add_action( 'network_admin_menu', array( __CLASS__, 'register_network_menu') );
add_action( 'current_screen', array( __CLASS__, 'queue_resources' ) );
add_action( 'wp_ajax_wp_sendgrid_check_settings', array( __CLASS__, 'ajax_check_settings' ) );
// This action will be triggered when the user submits the network admin SG settings form.
// Based on: http://wordpress.stackexchange.com/questions/64968/settings-api-in-multisite-missing-update-message
add_action( 'network_admin_edit_update_sendgrid_network_options', array(__CLASS__, 'update_network_options'));
}
public static function register_settings() {
$option_name = ( self::is_network_admin_page() ) ? self::SETTINGS_NETWORK_OPTION_NAME : self::SETTINGS_OPTION_NAME;
// Register settings and sections
register_setting( self::SETTINGS_PAGE_SLUG, $option_name, array( __CLASS__, 'validate_settings' ) );
add_settings_section( self::SETTINGS_SECTION_ID, __( 'Account Settings' ), array( __CLASS__, 'show_settings_section_description' ), self::SETTINGS_PAGE_SLUG );
// Username/Password
self::add_settings_field( 'username', __( 'Your SendGrid Username' ), 'text' );
self::add_settings_field( 'password', __( 'Your SendGrid Password' ), 'password' );
self::add_settings_field( 'api', __( 'Send Emails With' ), 'select', array(
'description' => __( 'You shouldn\'t need to change this unless the default doesn\'t work on your server' ),
'options' => array( self::API_REST => __( 'REST' ), self::API_SMTP => __( 'SMTP' ) )
) );
self::add_settings_field( 'secure', __( 'Secure Connection' ), 'checkbox', array(
'description' => ' Make sure you have the SSL extension for PHP installed before enabling.',
'label' => 'Use a secure connection (recommended).'
) );
if ( self::is_network_admin_page() ) {
// Only add the override option if viewing the settings under network admin
self::add_settings_field( 'override', __('Allow Override'), 'checkbox', array(
'label' => __('Allow individual sites to override the network-level settings'),
));
}
//add_settings_field( self::SETTINGS_SECTION_ID . '-username', 'Your SendGrid Username', array( __CLASS__, 'show_settings_field' ), self::SETTINGS_PAGE_SLUG, self::SETTINGS_SECTION_ID );
}
public static function register_menu() {
// Check to be sure the network settings allow for individual site override, before adding option page
$network_settings = self::get_network_settings();
if ( $network_settings['override'] ) {
add_options_page( __( 'SendGrid Settings' ), __( 'SendGrid Settings' ),
'manage_options', self::SETTINGS_PAGE_SLUG, array( __CLASS__, 'show_settings_page' ) );
}
}
public static function register_network_menu() {
// add_options_page does not work for the network admin page, so we need to use add_submenu_page
add_submenu_page('settings.php', __('SendGrid Settings'), __('SendGrid Settings'),
'manage_network_options', self::SETTINGS_PAGE_SLUG, array(__CLASS__, 'show_settings_page'));
}
public static function queue_resources($screen) {
if ( 'settings_page_' . self::SETTINGS_PAGE_SLUG == $screen->base || 'settings_page_' . self::SETTINGS_PAGE_SLUG . '-network' == $screen->base ) {
wp_enqueue_script( 'wp-sendgrid', WP_SendGrid::plugin_url( 'resources/wp-sendgrid.js' ), array( 'jquery' ) );
wp_enqueue_style( 'wp-sendgrid', WP_SendGrid::plugin_url( 'resources/wp-sendgrid.css' ) );
}
}
public static function ajax_check_settings() {
$user_id = get_current_user_id();
$user = get_userdata( $user_id );
if ( wp_mail( $user->user_email, __( 'SendGrid Test' ), __( 'If you\'re reading this, it looks like your SendGrid settings are correct' ) ) ) {
wp_send_json( array( 'success' => 'Test email sent. If it doesn\'t show up, double check your settings.' ) );
} else {
wp_send_json( array( 'error' => 'There was a problem sending the test email. Double check your settings.' ) );
}
}
public static function show_settings_page() {
if ( self::is_network_admin_page() ) {
// Compose the network admin url to post to.
$url = add_query_arg( 'action', 'update_sendgrid_network_options', network_admin_url('edit.php'));
if ( isset( $_REQUEST['settings-updated'] ) ) {
// If the request contains a 'settings-updated' parameter, we know we just saved the settings
// and need to display an 'updated' message along with the 'test' button.
// We can't call 'validate_settings' then 'settings_errors' because the 'update_network_options'
// call happens outside of the normal sttings API (we had to create a custom method to handle
// saving the network admin settings)
?>
<div id='setting-error-wp_sendgrid_settings_updated' class='updated settings-error'>
<p>
<strong><?php _e( 'SendGrid options updated' ); ?>
<input type="button" class="button" id="wp-sendgrid-test-settings" value="<?php echo esc_attr( __( 'Send Test Email' ) ); ?>" />
<span class="spinner"></span>
<span id="wp-sendgrid-test-settings-response"></span>
</strong>
</p>
</div>
<?php
}
} else {
// Use the regular admin options url.
$url = admin_url( 'options.php' );
}
?>
<div class="wrap">
<h2><?php _e( 'WP SendGrid Settings' ); ?></h2>
<form action="<?php echo esc_url( $url ); ?>" method="POST">
<?php do_action( 'wp_sendgrid_settings_form_begin' ); ?>
<?php settings_fields( self::SETTINGS_PAGE_SLUG ); ?>
<?php do_settings_sections( self::SETTINGS_PAGE_SLUG ); ?>
<?php do_action( 'wp_sendgrid_settings_before_submit_button'); ?>
<?php submit_button(); ?>
<?php do_action( 'wp_sendgrid_settings_after_submit_button' ); ?>
<?php do_action( 'wp_sendgrid_settings_form_end' ); ?>
</form>
</div>
<?php
}
public static function show_settings_section_description() {
WP_SendGrid::load_view( 'settings-section-description.php' );
}
public static function add_settings_field( $id, $label, $type, $args = array() ) {
$default_args = array(
'id' => $id,
'description' => '',
'type' => $type,
);
$args = array_merge( $default_args, $args );
$callback = isset( $args['callback'] ) ? $args['callback'] : array( __CLASS__, "show_{$type}_field" );
add_settings_field( self::SETTINGS_SECTION_ID . '-' . $id, $label, $callback, self::SETTINGS_PAGE_SLUG, self::SETTINGS_SECTION_ID, $args );
}
public static function load_field_view( $view, $args ) {
$args['settings'] = self::is_network_admin_page() ? self::get_network_settings() : self::get_local_settings();
$args['value'] = $args['settings'][$args['id']];
WP_SendGrid::load_view( $view, $args );
}
public static function show_input_field( $type, $args ) {
$args['type'] = $type;
self::load_field_view( 'input-field.php', $args );
}
public static function show_text_field( $args ) {
self::show_input_field( 'text', $args );
}
public static function show_password_field( $args ) {
self::show_input_field( 'password', $args );
}
public static function show_select_field( $args ) {
self::load_field_view( 'select-field.php', $args );
}
public static function show_checkbox_field( $args ) {
self::load_field_view( 'checkbox-field.php', $args );
}
public static function get_default_settings() {
return apply_filters( 'wp_sendgrid_default_settings', self::$default_settings );
}
public static function get_default_network_settings() {
$settings = array_merge( self::$default_settings, array( 'override' => true ) );
return apply_filters( 'wp_sendgrid_default_network_settings', $settings );
}
public static function validate_settings( $settings ) {
add_settings_error( 'general', 'wp_sendgrid_settings_updated',
__( 'SendGrid options updated' ) .
' <input type="button" class="button" id="wp-sendgrid-test-settings" value="' .
esc_attr( __( 'Send Test Email' ) ) . '" /><span class="spinner"></span>' .
' <span id="wp-sendgrid-test-settings-response"></span>', 'updated' );
$settings = apply_filters( 'wp_sendgrid_validate_settings', $settings );
return $settings;
}
public static function get_settings() {
if ( isset( self::$settings ) ) {
return self::$settings;
}
// First check the network settings.
$settings = self::get_network_settings();
// If network settings are empty, or override is enabled, check local settings
if ( isset( $settings['override'] ) && $settings['override'] && !self::is_network_admin_page() ) {
$local_settings = self::get_local_settings();
if ( !empty( $local_settings ) ) {
$settings = array_merge( $settings, $local_settings );
}
}
self::$settings = apply_filters( 'wp_sendgrid_get_settings', $settings );
return self::$settings;
}
private static function get_local_settings() {
$settings = array_merge( self::get_default_settings(), get_option( self::SETTINGS_OPTION_NAME, array() ) );
return apply_filters( 'wp_sendgrid_get_local_settings', $settings );
}
private static function get_network_settings() {
$settings = get_site_option( self::SETTINGS_NETWORK_OPTION_NAME, array());
$settings = array_merge( self::get_default_network_settings(), $settings );
return apply_filters( 'wp_sendgrid_get_network_settings', $settings );
}
private static function is_network_admin_page() {
return ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN == 1 );
}
public static function update_network_options() {
// Only make changes if the self::SETTINGS_OPTION_NAME key exists.
// Note: we use the SETTINGS_OPTION_NAME because it is used by files in the '/views' folder
if ( isset( $_REQUEST[self::SETTINGS_OPTION_NAME] ) ) {
$value = stripslashes_deep( $_REQUEST[self::SETTINGS_OPTION_NAME] );
// Since a false value from the override checkbox won't be saved, we need to add it here.
$_REQUEST[self::SETTINGS_OPTION_NAME]['override'] = isset( $_REQUEST[self::SETTINGS_OPTION_NAME]['override'] );
// Update the network option.
update_site_option( self::SETTINGS_NETWORK_OPTION_NAME, $_REQUEST[self::SETTINGS_OPTION_NAME] );
// Redirect back to the network settings page.
$params = array( 'page' => self::SETTINGS_PAGE_SLUG, 'settings-updated' => 'true' );
wp_redirect( add_query_arg( $params, network_admin_url('settings.php') ) );
exit();
}
}
}
WP_SendGrid_Settings::start();
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A token representing the a reference to a static type.
*
* This token is unique for a filePath and name and can be used as a hash table key.
*/
export declare class StaticSymbol {
filePath: string;
name: string;
members: string[];
constructor(filePath: string, name: string, members?: string[]);
}
/**
* A cache of static symbol used by the StaticReflector to return the same symbol for the
* same symbol values.
*/
export declare class StaticSymbolCache {
private cache;
get(declarationFile: string, name: string, members?: string[]): StaticSymbol;
}
|
/*!
* FileInput Czech Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['cz'] = {
fileSingle: 'soubor',
filePlural: 'soubory',
browseLabel: 'Vybrat …',
removeLabel: 'Odstranit',
removeTitle: 'Vyčistit vybrané soubory',
cancelLabel: 'Storno',
cancelTitle: 'Přerušit nahrávání',
uploadLabel: 'Nahrát',
uploadTitle: 'Nahrát vybrané soubory',
msgNo: 'Ne',
msgCancelled: 'Zrušeno',
msgZoomTitle: 'zobrazit podrobnosti',
msgZoomModalHeading: 'Detailní náhled',
msgSizeTooLarge: 'Soubor "{name}" (<b>{size} KB</b>): překročení - maximální povolená velikost <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Musíte vybrat nejméně <b>{n}</b> {files} pro nahrání.',
msgFilesTooMany: 'Počet vybraných souborů pro nahrání <b>({n})</b>: překročení - maximální povolený limit <b>{m}</b>.',
msgFileNotFound: 'Soubor "{name}" nebyl nalezen!',
msgFileSecured: 'Zabezpečení souboru znemožnilo číst soubor "{name}".',
msgFileNotReadable: 'Soubor "{name}" není čitelný.',
msgFilePreviewAborted: 'Náhled souboru byl přerušen pro "{name}".',
msgFilePreviewError: 'Nastala chyba při načtení souboru "{name}".',
msgInvalidFileType: 'Neplatný typ souboru "{name}". Pouze "{types}" souborů jsou podporovány.',
msgInvalidFileExtension: 'Neplatná extenze souboru "{name}". Pouze "{extensions}" souborů jsou podporovány.',
msgUploadAborted: 'Soubor nahrávání byl přerušen',
msgValidationError: 'Chyba ověření',
msgLoading: 'Nahrávání souboru {index} z {files} …',
msgProgress: 'Nahrávání souboru {index} z {files} - {name} - {percent}% dokončeno.',
msgSelected: '{n} {files} vybrano',
msgFoldersNotAllowed: 'Táhni a pusť pouze soubory! Vynechané {n} pustěné složk(y).',
msgImageWidthSmall: 'Šířka image soubor "{name}", musí být alespoň {size} px.',
msgImageHeightSmall: 'Výška image soubor "{name}", musí být alespoň {size} px.',
msgImageWidthLarge: 'Šířka obrazového souboru "{name}" nelze překročit {size} px.',
msgImageHeightLarge: 'Výška obrazového souboru "{name}" nelze překročit {size} px.',
msgImageResizeError: 'Nelze získat rozměry obrázku změnit velikost.',
msgImageResizeException: 'Chyba při změně velikosti obrázku.<pre>{errors}</pre>',
dropZoneTitle: 'Táhni a pusť soubory sem …',
fileActionSettings: {
removeTitle: 'Odstranit soubor',
uploadTitle: 'nahrát soubor',
indicatorNewTitle: 'Ještě nenahrál',
indicatorSuccessTitle: 'Nahraný',
indicatorErrorTitle: 'Nahrát Chyba',
indicatorLoadingTitle: 'Nahrávání ...'
}
};
})(window.jQuery); |
// SPDX-License-Identifier: GPL-2.0-only
/*
* Intel MIC Platform Software Stack (MPSS)
*
* Copyright(c) 2013 Intel Corporation.
*
* Disclaimer: The codes contained in these modules may be specific to
* the Intel Software Development Platform codenamed: Knights Ferry, and
* the Intel product codenamed: Knights Corner, and are not backward
* compatible with other Intel products. Additionally, Intel will NOT
* support the codes or instruction set in future products.
*
* Intel MIC Card driver.
*/
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include "../common/mic_dev.h"
#include "mic_device.h"
/* Debugfs parent dir */
static struct dentry *mic_dbg;
/**
* mic_intr_show - Send interrupts to host.
*/
static int mic_intr_show(struct seq_file *s, void *unused)
{
struct mic_driver *mdrv = s->private;
struct mic_device *mdev = &mdrv->mdev;
mic_send_intr(mdev, 0);
msleep(1000);
mic_send_intr(mdev, 1);
msleep(1000);
mic_send_intr(mdev, 2);
msleep(1000);
mic_send_intr(mdev, 3);
msleep(1000);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(mic_intr);
/**
* mic_create_card_debug_dir - Initialize MIC debugfs entries.
*/
void __init mic_create_card_debug_dir(struct mic_driver *mdrv)
{
if (!mic_dbg)
return;
mdrv->dbg_dir = debugfs_create_dir(mdrv->name, mic_dbg);
debugfs_create_file("intr_test", 0444, mdrv->dbg_dir, mdrv,
&mic_intr_fops);
}
/**
* mic_delete_card_debug_dir - Uninitialize MIC debugfs entries.
*/
void mic_delete_card_debug_dir(struct mic_driver *mdrv)
{
debugfs_remove_recursive(mdrv->dbg_dir);
}
/**
* mic_init_card_debugfs - Initialize global debugfs entry.
*/
void __init mic_init_card_debugfs(void)
{
mic_dbg = debugfs_create_dir(KBUILD_MODNAME, NULL);
}
/**
* mic_exit_card_debugfs - Uninitialize global debugfs entry
*/
void mic_exit_card_debugfs(void)
{
debugfs_remove(mic_dbg);
}
|
/**
@module ember
@submodule ember-htmlbars
*/
import Ember from 'ember-metal/core';
import EmberStringUtils from 'ember-runtime/system/string';
import { SafeString, escapeExpression } from 'htmlbars-util';
/**
Mark a string as safe for unescaped output with Ember templates. If you
return HTML from a helper, use this function to
ensure Ember's rendering layer does not escape the HTML.
```javascript
Ember.String.htmlSafe('<div>someString</div>')
```
@method htmlSafe
@for Ember.String
@static
@return {Handlebars.SafeString} a string that will not be html escaped by Handlebars
@public
*/
function htmlSafe(str) {
if (str === null || str === undefined) {
return '';
}
if (typeof str !== 'string') {
str = '' + str;
}
return new SafeString(str);
}
EmberStringUtils.htmlSafe = htmlSafe;
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
String.prototype.htmlSafe = function() {
return htmlSafe(this);
};
}
export {
SafeString,
htmlSafe,
escapeExpression
};
|
/*
* Copyright (c) 2001 Vojtech Pavlik
*
* CATC EL1210A NetMate USB Ethernet driver
*
* Sponsored by SuSE
*
* Based on the work of
* Donald Becker
*
* Old chipset support added by Simon Evans <spse@secret.org.uk> 2002
* - adds support for Belkin F5U011
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@suse.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <linux/gfp.h>
#include <linux/uaccess.h>
#undef DEBUG
#include <linux/usb.h>
/*
* Version information.
*/
#define DRIVER_VERSION "v2.8"
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@suse.cz>"
#define DRIVER_DESC "CATC EL1210A NetMate USB Ethernet driver"
#define SHORT_DRIVER_DESC "EL1210A NetMate USB Ethernet"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static const char driver_name[] = "catc";
/*
* Some defines.
*/
#define STATS_UPDATE (HZ) /* Time between stats updates */
#define TX_TIMEOUT (5*HZ) /* Max time the queue can be stopped */
#define PKT_SZ 1536 /* Max Ethernet packet size */
#define RX_MAX_BURST 15 /* Max packets per rx buffer (> 0, < 16) */
#define TX_MAX_BURST 15 /* Max full sized packets per tx buffer (> 0) */
#define CTRL_QUEUE 16 /* Max control requests in flight (power of two) */
#define RX_PKT_SZ 1600 /* Max size of receive packet for F5U011 */
/*
* Control requests.
*/
enum control_requests {
ReadMem = 0xf1,
GetMac = 0xf2,
Reset = 0xf4,
SetMac = 0xf5,
SetRxMode = 0xf5, /* F5U011 only */
WriteROM = 0xf8,
SetReg = 0xfa,
GetReg = 0xfb,
WriteMem = 0xfc,
ReadROM = 0xfd,
};
/*
* Registers.
*/
enum register_offsets {
TxBufCount = 0x20,
RxBufCount = 0x21,
OpModes = 0x22,
TxQed = 0x23,
RxQed = 0x24,
MaxBurst = 0x25,
RxUnit = 0x60,
EthStatus = 0x61,
StationAddr0 = 0x67,
EthStats = 0x69,
LEDCtrl = 0x81,
};
enum eth_stats {
TxSingleColl = 0x00,
TxMultiColl = 0x02,
TxExcessColl = 0x04,
RxFramErr = 0x06,
};
enum op_mode_bits {
Op3MemWaits = 0x03,
OpLenInclude = 0x08,
OpRxMerge = 0x10,
OpTxMerge = 0x20,
OpWin95bugfix = 0x40,
OpLoopback = 0x80,
};
enum rx_filter_bits {
RxEnable = 0x01,
RxPolarity = 0x02,
RxForceOK = 0x04,
RxMultiCast = 0x08,
RxPromisc = 0x10,
AltRxPromisc = 0x20, /* F5U011 uses different bit */
};
enum led_values {
LEDFast = 0x01,
LEDSlow = 0x02,
LEDFlash = 0x03,
LEDPulse = 0x04,
LEDLink = 0x08,
};
enum link_status {
LinkNoChange = 0,
LinkGood = 1,
LinkBad = 2
};
/*
* The catc struct.
*/
#define CTRL_RUNNING 0
#define RX_RUNNING 1
#define TX_RUNNING 2
struct catc {
struct net_device *netdev;
struct usb_device *usbdev;
unsigned long flags;
unsigned int tx_ptr, tx_idx;
unsigned int ctrl_head, ctrl_tail;
spinlock_t tx_lock, ctrl_lock;
u8 tx_buf[2][TX_MAX_BURST * (PKT_SZ + 2)];
u8 rx_buf[RX_MAX_BURST * (PKT_SZ + 2)];
u8 irq_buf[2];
u8 ctrl_buf[64];
struct usb_ctrlrequest ctrl_dr;
struct timer_list timer;
u8 stats_buf[8];
u16 stats_vals[4];
unsigned long last_stats;
u8 multicast[64];
struct ctrl_queue {
u8 dir;
u8 request;
u16 value;
u16 index;
void *buf;
int len;
void (*callback)(struct catc *catc, struct ctrl_queue *q);
} ctrl_queue[CTRL_QUEUE];
struct urb *tx_urb, *rx_urb, *irq_urb, *ctrl_urb;
u8 is_f5u011; /* Set if device is an F5U011 */
u8 rxmode[2]; /* Used for F5U011 */
atomic_t recq_sz; /* Used for F5U011 - counter of waiting rx packets */
};
/*
* Useful macros.
*/
#define catc_get_mac(catc, mac) catc_ctrl_msg(catc, USB_DIR_IN, GetMac, 0, 0, mac, 6)
#define catc_reset(catc) catc_ctrl_msg(catc, USB_DIR_OUT, Reset, 0, 0, NULL, 0)
#define catc_set_reg(catc, reg, val) catc_ctrl_msg(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0)
#define catc_get_reg(catc, reg, buf) catc_ctrl_msg(catc, USB_DIR_IN, GetReg, 0, reg, buf, 1)
#define catc_write_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size)
#define catc_read_mem(catc, addr, buf, size) catc_ctrl_msg(catc, USB_DIR_IN, ReadMem, 0, addr, buf, size)
#define f5u011_rxmode(catc, rxmode) catc_ctrl_msg(catc, USB_DIR_OUT, SetRxMode, 0, 1, rxmode, 2)
#define f5u011_rxmode_async(catc, rxmode) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 1, &rxmode, 2, NULL)
#define f5u011_mchash_async(catc, hash) catc_ctrl_async(catc, USB_DIR_OUT, SetRxMode, 0, 2, &hash, 8, NULL)
#define catc_set_reg_async(catc, reg, val) catc_ctrl_async(catc, USB_DIR_OUT, SetReg, val, reg, NULL, 0, NULL)
#define catc_get_reg_async(catc, reg, cb) catc_ctrl_async(catc, USB_DIR_IN, GetReg, 0, reg, NULL, 1, cb)
#define catc_write_mem_async(catc, addr, buf, size) catc_ctrl_async(catc, USB_DIR_OUT, WriteMem, 0, addr, buf, size, NULL)
/*
* Receive routines.
*/
static void catc_rx_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *pkt_start = urb->transfer_buffer;
struct sk_buff *skb;
int pkt_len, pkt_offset = 0;
int status = urb->status;
if (!catc->is_f5u011) {
clear_bit(RX_RUNNING, &catc->flags);
pkt_offset = 2;
}
if (status) {
dev_dbg(&urb->dev->dev, "rx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
do {
if(!catc->is_f5u011) {
pkt_len = le16_to_cpup((__le16*)pkt_start);
if (pkt_len > urb->actual_length) {
catc->netdev->stats.rx_length_errors++;
catc->netdev->stats.rx_errors++;
break;
}
} else {
pkt_len = urb->actual_length;
}
if (!(skb = dev_alloc_skb(pkt_len)))
return;
skb_copy_to_linear_data(skb, pkt_start + pkt_offset, pkt_len);
skb_put(skb, pkt_len);
skb->protocol = eth_type_trans(skb, catc->netdev);
netif_rx(skb);
catc->netdev->stats.rx_packets++;
catc->netdev->stats.rx_bytes += pkt_len;
/* F5U011 only does one packet per RX */
if (catc->is_f5u011)
break;
pkt_start += (((pkt_len + 1) >> 6) + 1) << 6;
} while (pkt_start - (u8 *) urb->transfer_buffer < urb->actual_length);
if (catc->is_f5u011) {
if (atomic_read(&catc->recq_sz)) {
int state;
atomic_dec(&catc->recq_sz);
netdev_dbg(catc->netdev, "getting extra packet\n");
urb->dev = catc->usbdev;
if ((state = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
netdev_dbg(catc->netdev,
"submit(rx_urb) status %d\n", state);
}
} else {
clear_bit(RX_RUNNING, &catc->flags);
}
}
}
static void catc_irq_done(struct urb *urb)
{
struct catc *catc = urb->context;
u8 *data = urb->transfer_buffer;
int status = urb->status;
unsigned int hasdata = 0, linksts = LinkNoChange;
int res;
if (!catc->is_f5u011) {
hasdata = data[1] & 0x80;
if (data[1] & 0x40)
linksts = LinkGood;
else if (data[1] & 0x20)
linksts = LinkBad;
} else {
hasdata = (unsigned int)(be16_to_cpup((__be16*)data) & 0x0fff);
if (data[0] == 0x90)
linksts = LinkGood;
else if (data[0] == 0xA0)
linksts = LinkBad;
}
switch (status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
dev_dbg(&urb->dev->dev,
"irq_done, status %d, data %02x %02x.\n",
status, data[0], data[1]);
goto resubmit;
}
if (linksts == LinkGood) {
netif_carrier_on(catc->netdev);
netdev_dbg(catc->netdev, "link ok\n");
}
if (linksts == LinkBad) {
netif_carrier_off(catc->netdev);
netdev_dbg(catc->netdev, "link bad\n");
}
if (hasdata) {
if (test_and_set_bit(RX_RUNNING, &catc->flags)) {
if (catc->is_f5u011)
atomic_inc(&catc->recq_sz);
} else {
catc->rx_urb->dev = catc->usbdev;
if ((res = usb_submit_urb(catc->rx_urb, GFP_ATOMIC)) < 0) {
dev_err(&catc->usbdev->dev,
"submit(rx_urb) status %d\n", res);
}
}
}
resubmit:
res = usb_submit_urb (urb, GFP_ATOMIC);
if (res)
dev_err(&catc->usbdev->dev,
"can't resubmit intr, %s-%s, status %d\n",
catc->usbdev->bus->bus_name,
catc->usbdev->devpath, res);
}
/*
* Transmit routines.
*/
static int catc_tx_run(struct catc *catc)
{
int status;
if (catc->is_f5u011)
catc->tx_ptr = (catc->tx_ptr + 63) & ~63;
catc->tx_urb->transfer_buffer_length = catc->tx_ptr;
catc->tx_urb->transfer_buffer = catc->tx_buf[catc->tx_idx];
catc->tx_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->tx_urb, GFP_ATOMIC)) < 0)
dev_err(&catc->usbdev->dev, "submit(tx_urb), status %d\n",
status);
catc->tx_idx = !catc->tx_idx;
catc->tx_ptr = 0;
netif_trans_update(catc->netdev);
return status;
}
static void catc_tx_done(struct urb *urb)
{
struct catc *catc = urb->context;
unsigned long flags;
int r, status = urb->status;
if (status == -ECONNRESET) {
dev_dbg(&urb->dev->dev, "Tx Reset.\n");
urb->status = 0;
netif_trans_update(catc->netdev);
catc->netdev->stats.tx_errors++;
clear_bit(TX_RUNNING, &catc->flags);
netif_wake_queue(catc->netdev);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "tx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
spin_lock_irqsave(&catc->tx_lock, flags);
if (catc->tx_ptr) {
r = catc_tx_run(catc);
if (unlikely(r < 0))
clear_bit(TX_RUNNING, &catc->flags);
} else {
clear_bit(TX_RUNNING, &catc->flags);
}
netif_wake_queue(catc->netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
}
static netdev_tx_t catc_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
unsigned long flags;
int r = 0;
char *tx_buf;
spin_lock_irqsave(&catc->tx_lock, flags);
catc->tx_ptr = (((catc->tx_ptr - 1) >> 6) + 1) << 6;
tx_buf = catc->tx_buf[catc->tx_idx] + catc->tx_ptr;
if (catc->is_f5u011)
*(__be16 *)tx_buf = cpu_to_be16(skb->len);
else
*(__le16 *)tx_buf = cpu_to_le16(skb->len);
skb_copy_from_linear_data(skb, tx_buf + 2, skb->len);
catc->tx_ptr += skb->len + 2;
if (!test_and_set_bit(TX_RUNNING, &catc->flags)) {
r = catc_tx_run(catc);
if (r < 0)
clear_bit(TX_RUNNING, &catc->flags);
}
if ((catc->is_f5u011 && catc->tx_ptr) ||
(catc->tx_ptr >= ((TX_MAX_BURST - 1) * (PKT_SZ + 2))))
netif_stop_queue(netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
if (r >= 0) {
catc->netdev->stats.tx_bytes += skb->len;
catc->netdev->stats.tx_packets++;
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static void catc_tx_timeout(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
dev_warn(&netdev->dev, "Transmit timed out.\n");
usb_unlink_urb(catc->tx_urb);
}
/*
* Control messages.
*/
static int catc_ctrl_msg(struct catc *catc, u8 dir, u8 request, u16 value, u16 index, void *buf, int len)
{
int retval = usb_control_msg(catc->usbdev,
dir ? usb_rcvctrlpipe(catc->usbdev, 0) : usb_sndctrlpipe(catc->usbdev, 0),
request, 0x40 | dir, value, index, buf, len, 1000);
return retval < 0 ? retval : 0;
}
static void catc_ctrl_run(struct catc *catc)
{
struct ctrl_queue *q = catc->ctrl_queue + catc->ctrl_tail;
struct usb_device *usbdev = catc->usbdev;
struct urb *urb = catc->ctrl_urb;
struct usb_ctrlrequest *dr = &catc->ctrl_dr;
int status;
dr->bRequest = q->request;
dr->bRequestType = 0x40 | q->dir;
dr->wValue = cpu_to_le16(q->value);
dr->wIndex = cpu_to_le16(q->index);
dr->wLength = cpu_to_le16(q->len);
urb->pipe = q->dir ? usb_rcvctrlpipe(usbdev, 0) : usb_sndctrlpipe(usbdev, 0);
urb->transfer_buffer_length = q->len;
urb->transfer_buffer = catc->ctrl_buf;
urb->setup_packet = (void *) dr;
urb->dev = usbdev;
if (!q->dir && q->buf && q->len)
memcpy(catc->ctrl_buf, q->buf, q->len);
if ((status = usb_submit_urb(catc->ctrl_urb, GFP_ATOMIC)))
dev_err(&catc->usbdev->dev, "submit(ctrl_urb) status %d\n",
status);
}
static void catc_ctrl_done(struct urb *urb)
{
struct catc *catc = urb->context;
struct ctrl_queue *q;
unsigned long flags;
int status = urb->status;
if (status)
dev_dbg(&urb->dev->dev, "ctrl_done, status %d, len %d.\n",
status, urb->actual_length);
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_tail;
if (q->dir) {
if (q->buf && q->len)
memcpy(q->buf, catc->ctrl_buf, q->len);
else
q->buf = catc->ctrl_buf;
}
if (q->callback)
q->callback(catc, q);
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head != catc->ctrl_tail)
catc_ctrl_run(catc);
else
clear_bit(CTRL_RUNNING, &catc->flags);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
}
static int catc_ctrl_async(struct catc *catc, u8 dir, u8 request, u16 value,
u16 index, void *buf, int len, void (*callback)(struct catc *catc, struct ctrl_queue *q))
{
struct ctrl_queue *q;
int retval = 0;
unsigned long flags;
spin_lock_irqsave(&catc->ctrl_lock, flags);
q = catc->ctrl_queue + catc->ctrl_head;
q->dir = dir;
q->request = request;
q->value = value;
q->index = index;
q->buf = buf;
q->len = len;
q->callback = callback;
catc->ctrl_head = (catc->ctrl_head + 1) & (CTRL_QUEUE - 1);
if (catc->ctrl_head == catc->ctrl_tail) {
dev_err(&catc->usbdev->dev, "ctrl queue full\n");
catc->ctrl_tail = (catc->ctrl_tail + 1) & (CTRL_QUEUE - 1);
retval = -1;
}
if (!test_and_set_bit(CTRL_RUNNING, &catc->flags))
catc_ctrl_run(catc);
spin_unlock_irqrestore(&catc->ctrl_lock, flags);
return retval;
}
/*
* Statistics.
*/
static void catc_stats_done(struct catc *catc, struct ctrl_queue *q)
{
int index = q->index - EthStats;
u16 data, last;
catc->stats_buf[index] = *((char *)q->buf);
if (index & 1)
return;
data = ((u16)catc->stats_buf[index] << 8) | catc->stats_buf[index + 1];
last = catc->stats_vals[index >> 1];
switch (index) {
case TxSingleColl:
case TxMultiColl:
catc->netdev->stats.collisions += data - last;
break;
case TxExcessColl:
catc->netdev->stats.tx_aborted_errors += data - last;
catc->netdev->stats.tx_errors += data - last;
break;
case RxFramErr:
catc->netdev->stats.rx_frame_errors += data - last;
catc->netdev->stats.rx_errors += data - last;
break;
}
catc->stats_vals[index >> 1] = data;
}
static void catc_stats_timer(struct timer_list *t)
{
struct catc *catc = from_timer(catc, t, timer);
int i;
for (i = 0; i < 8; i++)
catc_get_reg_async(catc, EthStats + 7 - i, catc_stats_done);
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
}
/*
* Receive modes. Broadcast, Multicast, Promisc.
*/
static void catc_multicast(unsigned char *addr, u8 *multicast)
{
u32 crc;
crc = ether_crc_le(6, addr);
multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
}
static void catc_set_multicast_list(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
struct netdev_hw_addr *ha;
u8 broadcast[ETH_ALEN];
u8 rx = RxEnable | RxPolarity | RxMultiCast;
eth_broadcast_addr(broadcast);
memset(catc->multicast, 0, 64);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
if (netdev->flags & IFF_PROMISC) {
memset(catc->multicast, 0xff, 64);
rx |= (!catc->is_f5u011) ? RxPromisc : AltRxPromisc;
}
if (netdev->flags & IFF_ALLMULTI) {
memset(catc->multicast, 0xff, 64);
} else {
netdev_for_each_mc_addr(ha, netdev) {
u32 crc = ether_crc_le(6, ha->addr);
if (!catc->is_f5u011) {
catc->multicast[(crc >> 3) & 0x3f] |= 1 << (crc & 7);
} else {
catc->multicast[7-(crc >> 29)] |= 1 << ((crc >> 26) & 7);
}
}
}
if (!catc->is_f5u011) {
catc_set_reg_async(catc, RxUnit, rx);
catc_write_mem_async(catc, 0xfa80, catc->multicast, 64);
} else {
f5u011_mchash_async(catc, catc->multicast);
if (catc->rxmode[0] != rx) {
catc->rxmode[0] = rx;
netdev_dbg(catc->netdev,
"Setting RX mode to %2.2X %2.2X\n",
catc->rxmode[0], catc->rxmode[1]);
f5u011_rxmode_async(catc, catc->rxmode);
}
}
}
static void catc_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct catc *catc = netdev_priv(dev);
strlcpy(info->driver, driver_name, sizeof(info->driver));
strlcpy(info->version, DRIVER_VERSION, sizeof(info->version));
usb_make_path(catc->usbdev, info->bus_info, sizeof(info->bus_info));
}
static int catc_get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *cmd)
{
struct catc *catc = netdev_priv(dev);
if (!catc->is_f5u011)
return -EOPNOTSUPP;
ethtool_link_ksettings_zero_link_mode(cmd, supported);
ethtool_link_ksettings_add_link_mode(cmd, supported, 10baseT_Half);
ethtool_link_ksettings_add_link_mode(cmd, supported, TP);
ethtool_link_ksettings_zero_link_mode(cmd, advertising);
ethtool_link_ksettings_add_link_mode(cmd, advertising, 10baseT_Half);
ethtool_link_ksettings_add_link_mode(cmd, advertising, TP);
cmd->base.speed = SPEED_10;
cmd->base.duplex = DUPLEX_HALF;
cmd->base.port = PORT_TP;
cmd->base.phy_address = 0;
cmd->base.autoneg = AUTONEG_DISABLE;
return 0;
}
static const struct ethtool_ops ops = {
.get_drvinfo = catc_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_link_ksettings = catc_get_link_ksettings,
};
/*
* Open, close.
*/
static int catc_open(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
int status;
catc->irq_urb->dev = catc->usbdev;
if ((status = usb_submit_urb(catc->irq_urb, GFP_KERNEL)) < 0) {
dev_err(&catc->usbdev->dev, "submit(irq_urb) status %d\n",
status);
return -1;
}
netif_start_queue(netdev);
if (!catc->is_f5u011)
mod_timer(&catc->timer, jiffies + STATS_UPDATE);
return 0;
}
static int catc_stop(struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
netif_stop_queue(netdev);
if (!catc->is_f5u011)
del_timer_sync(&catc->timer);
usb_kill_urb(catc->rx_urb);
usb_kill_urb(catc->tx_urb);
usb_kill_urb(catc->irq_urb);
usb_kill_urb(catc->ctrl_urb);
return 0;
}
static const struct net_device_ops catc_netdev_ops = {
.ndo_open = catc_open,
.ndo_stop = catc_stop,
.ndo_start_xmit = catc_start_xmit,
.ndo_tx_timeout = catc_tx_timeout,
.ndo_set_rx_mode = catc_set_multicast_list,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/*
* USB probe, disconnect.
*/
static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
timer_setup(&catc->timer, catc_stats_timer, 0);
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
u32 *buf;
int i;
dev_dbg(dev, "Checking memory size\n");
buf = kmalloc(4, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto fail_free;
}
*buf = 0x12345678;
catc_write_mem(catc, 0x7a80, buf, 4);
*buf = 0x87654321;
catc_write_mem(catc, 0xfa80, buf, 4);
catc_read_mem(catc, 0x7a80, buf, 4);
switch (*buf) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
kfree(buf);
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
static void catc_disconnect(struct usb_interface *intf)
{
struct catc *catc = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (catc) {
unregister_netdev(catc->netdev);
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(catc->netdev);
}
}
/*
* Module functions and tables.
*/
static const struct usb_device_id catc_id_table[] = {
{ USB_DEVICE(0x0423, 0xa) }, /* CATC Netmate, Belkin F5U011 */
{ USB_DEVICE(0x0423, 0xc) }, /* CATC Netmate II, Belkin F5U111 */
{ USB_DEVICE(0x08d1, 0x1) }, /* smartBridges smartNIC */
{ }
};
MODULE_DEVICE_TABLE(usb, catc_id_table);
static struct usb_driver catc_driver = {
.name = driver_name,
.probe = catc_probe,
.disconnect = catc_disconnect,
.id_table = catc_id_table,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(catc_driver);
|
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-abc'">
<body>
<script nonce="abc">
function assert_csp_event_for_element(test, element) {
assert_equals(typeof SecurityPolicyViolationEvent, "function", "These tests require 'SecurityPolicyViolationEvent'.");
document.addEventListener("securitypolicyviolation", test.step_func(e => {
if (e.target != element)
return;
assert_equals(e.blockedURI, "inline");
assert_equals(e.effectiveDirective, "script-src");
assert_equals(element.contentDocument.body.innerText, "", "Ensure that 'Fail' doesn't appear in the child document.");
element.remove();
test.done();
}));
}
function navigate_to_javascript_onload(test, iframe) {
iframe.addEventListener("load", test.step_func(e => {
assert_equals(typeof SecurityPolicyViolationEvent, "function");
iframe.contentDocument.addEventListener(
"securitypolicyviolation",
test.unreached_func("The CSP event should be fired in the embedding document, not in the embedee.")
);
iframe.src = "javascript:'Fail.'";
}));
}
async_test(t => {
var i = document.createElement("iframe");
i.src = "javascript:'Fail.'";
assert_csp_event_for_element(t, i);
document.body.appendChild(i);
}, "<iframe src='javascript:'> blocked without 'unsafe-inline'.");
async_test(t => {
var i = document.createElement("iframe");
assert_csp_event_for_element(t, i);
navigate_to_javascript_onload(t, i);
document.body.appendChild(i);
}, "<iframe> navigated to 'javascript:' blocked without 'unsafe-inline'.");
async_test(t => {
var i = document.createElement("iframe");
i.src = "../support/echo-policy.py?policy=" + encodeURIComponent("script-src 'unsafe-inline'");
assert_csp_event_for_element(t, i);
navigate_to_javascript_onload(t, i);
document.body.appendChild(i);
}, "<iframe src='...'> with 'unsafe-inline' navigated to 'javascript:' blocked in this document");
async_test(t => {
var i = document.createElement("iframe");
i.src = "../support/echo-policy.py?policy=" + encodeURIComponent("script-src 'none'");
assert_csp_event_for_element(t, i);
navigate_to_javascript_onload(t, i);
document.body.appendChild(i);
}, "<iframe src='...'> without 'unsafe-inline' navigated to 'javascript:' blocked in this document.");
</script>
|
/*
* Format of an instruction in memory.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1996, 2000 by Ralf Baechle
* Copyright (C) 2006 by Thiemo Seufer
* Copyright (C) 2012 MIPS Technologies, Inc. All rights reserved.
* Copyright (C) 2014 Imagination Technologies Ltd.
*/
#ifndef _UAPI_ASM_INST_H
#define _UAPI_ASM_INST_H
#include <asm/bitfield.h>
/*
* Major opcodes; before MIPS IV cop1x was called cop3.
*/
enum major_op {
spec_op, bcond_op, j_op, jal_op,
beq_op, bne_op, blez_op, bgtz_op,
addi_op, cbcond0_op = addi_op, addiu_op, slti_op, sltiu_op,
andi_op, ori_op, xori_op, lui_op,
cop0_op, cop1_op, cop2_op, cop1x_op,
beql_op, bnel_op, blezl_op, bgtzl_op,
daddi_op, cbcond1_op = daddi_op, daddiu_op, ldl_op, ldr_op,
spec2_op, jalx_op, mdmx_op, msa_op = mdmx_op, spec3_op,
lb_op, lh_op, lwl_op, lw_op,
lbu_op, lhu_op, lwr_op, lwu_op,
sb_op, sh_op, swl_op, sw_op,
sdl_op, sdr_op, swr_op, cache_op,
ll_op, lwc1_op, lwc2_op, bc6_op = lwc2_op, pref_op,
lld_op, ldc1_op, ldc2_op, beqzcjic_op = ldc2_op, ld_op,
sc_op, swc1_op, swc2_op, balc6_op = swc2_op, major_3b_op,
scd_op, sdc1_op, sdc2_op, bnezcjialc_op = sdc2_op, sd_op
};
/*
* func field of spec opcode.
*/
enum spec_op {
sll_op, movc_op, srl_op, sra_op,
sllv_op, pmon_op, srlv_op, srav_op,
jr_op, jalr_op, movz_op, movn_op,
syscall_op, break_op, spim_op, sync_op,
mfhi_op, mthi_op, mflo_op, mtlo_op,
dsllv_op, spec2_unused_op, dsrlv_op, dsrav_op,
mult_op, multu_op, div_op, divu_op,
dmult_op, dmultu_op, ddiv_op, ddivu_op,
add_op, addu_op, sub_op, subu_op,
and_op, or_op, xor_op, nor_op,
spec3_unused_op, spec4_unused_op, slt_op, sltu_op,
dadd_op, daddu_op, dsub_op, dsubu_op,
tge_op, tgeu_op, tlt_op, tltu_op,
teq_op, spec5_unused_op, tne_op, spec6_unused_op,
dsll_op, spec7_unused_op, dsrl_op, dsra_op,
dsll32_op, spec8_unused_op, dsrl32_op, dsra32_op
};
/*
* func field of spec2 opcode.
*/
enum spec2_op {
madd_op, maddu_op, mul_op, spec2_3_unused_op,
msub_op, msubu_op, /* more unused ops */
clz_op = 0x20, clo_op,
dclz_op = 0x24, dclo_op,
sdbpp_op = 0x3f
};
/*
* func field of spec3 opcode.
*/
enum spec3_op {
ext_op, dextm_op, dextu_op, dext_op,
ins_op, dinsm_op, dinsu_op, dins_op,
yield_op = 0x09, lx_op = 0x0a,
lwle_op = 0x19, lwre_op = 0x1a,
cachee_op = 0x1b, sbe_op = 0x1c,
she_op = 0x1d, sce_op = 0x1e,
swe_op = 0x1f, bshfl_op = 0x20,
swle_op = 0x21, swre_op = 0x22,
prefe_op = 0x23, dbshfl_op = 0x24,
cache6_op = 0x25, sc6_op = 0x26,
scd6_op = 0x27, lbue_op = 0x28,
lhue_op = 0x29, lbe_op = 0x2c,
lhe_op = 0x2d, lle_op = 0x2e,
lwe_op = 0x2f, pref6_op = 0x35,
ll6_op = 0x36, lld6_op = 0x37,
rdhwr_op = 0x3b
};
/*
* rt field of bcond opcodes.
*/
enum rt_op {
bltz_op, bgez_op, bltzl_op, bgezl_op,
spimi_op, unused_rt_op_0x05, unused_rt_op_0x06, unused_rt_op_0x07,
tgei_op, tgeiu_op, tlti_op, tltiu_op,
teqi_op, unused_0x0d_rt_op, tnei_op, unused_0x0f_rt_op,
bltzal_op, bgezal_op, bltzall_op, bgezall_op,
rt_op_0x14, rt_op_0x15, rt_op_0x16, rt_op_0x17,
rt_op_0x18, rt_op_0x19, rt_op_0x1a, rt_op_0x1b,
bposge32_op, rt_op_0x1d, rt_op_0x1e, rt_op_0x1f
};
/*
* rs field of cop opcodes.
*/
enum cop_op {
mfc_op = 0x00, dmfc_op = 0x01,
cfc_op = 0x02, mfhc0_op = 0x02,
mfhc_op = 0x03, mtc_op = 0x04,
dmtc_op = 0x05, ctc_op = 0x06,
mthc0_op = 0x06, mthc_op = 0x07,
bc_op = 0x08, bc1eqz_op = 0x09,
mfmc0_op = 0x0b, bc1nez_op = 0x0d,
wrpgpr_op = 0x0e, cop_op = 0x10,
copm_op = 0x18
};
/*
* rt field of cop.bc_op opcodes
*/
enum bcop_op {
bcf_op, bct_op, bcfl_op, bctl_op
};
/*
* func field of cop0 coi opcodes.
*/
enum cop0_coi_func {
tlbr_op = 0x01, tlbwi_op = 0x02,
tlbwr_op = 0x06, tlbp_op = 0x08,
rfe_op = 0x10, eret_op = 0x18,
wait_op = 0x20,
};
/*
* func field of cop0 com opcodes.
*/
enum cop0_com_func {
tlbr1_op = 0x01, tlbw_op = 0x02,
tlbp1_op = 0x08, dctr_op = 0x09,
dctw_op = 0x0a
};
/*
* fmt field of cop1 opcodes.
*/
enum cop1_fmt {
s_fmt, d_fmt, e_fmt, q_fmt,
w_fmt, l_fmt
};
/*
* func field of cop1 instructions using d, s or w format.
*/
enum cop1_sdw_func {
fadd_op = 0x00, fsub_op = 0x01,
fmul_op = 0x02, fdiv_op = 0x03,
fsqrt_op = 0x04, fabs_op = 0x05,
fmov_op = 0x06, fneg_op = 0x07,
froundl_op = 0x08, ftruncl_op = 0x09,
fceill_op = 0x0a, ffloorl_op = 0x0b,
fround_op = 0x0c, ftrunc_op = 0x0d,
fceil_op = 0x0e, ffloor_op = 0x0f,
fmovc_op = 0x11, fmovz_op = 0x12,
fmovn_op = 0x13, fseleqz_op = 0x14,
frecip_op = 0x15, frsqrt_op = 0x16,
fselnez_op = 0x17, fmaddf_op = 0x18,
fmsubf_op = 0x19, frint_op = 0x1a,
fclass_op = 0x1b, fmin_op = 0x1c,
fmina_op = 0x1d, fmax_op = 0x1e,
fmaxa_op = 0x1f, fcvts_op = 0x20,
fcvtd_op = 0x21, fcvte_op = 0x22,
fcvtw_op = 0x24, fcvtl_op = 0x25,
fcmp_op = 0x30
};
/*
* func field of cop1x opcodes (MIPS IV).
*/
enum cop1x_func {
lwxc1_op = 0x00, ldxc1_op = 0x01,
swxc1_op = 0x08, sdxc1_op = 0x09,
pfetch_op = 0x0f, madd_s_op = 0x20,
madd_d_op = 0x21, madd_e_op = 0x22,
msub_s_op = 0x28, msub_d_op = 0x29,
msub_e_op = 0x2a, nmadd_s_op = 0x30,
nmadd_d_op = 0x31, nmadd_e_op = 0x32,
nmsub_s_op = 0x38, nmsub_d_op = 0x39,
nmsub_e_op = 0x3a
};
/*
* func field for mad opcodes (MIPS IV).
*/
enum mad_func {
madd_fp_op = 0x08, msub_fp_op = 0x0a,
nmadd_fp_op = 0x0c, nmsub_fp_op = 0x0e
};
/*
* func field for special3 lx opcodes (Cavium Octeon).
*/
enum lx_func {
lwx_op = 0x00,
lhx_op = 0x04,
lbux_op = 0x06,
ldx_op = 0x08,
lwux_op = 0x10,
lhux_op = 0x14,
lbx_op = 0x16,
};
/*
* BSHFL opcodes
*/
enum bshfl_func {
wsbh_op = 0x2,
dshd_op = 0x5,
seb_op = 0x10,
seh_op = 0x18,
};
/*
* func field for MSA MI10 format.
*/
enum msa_mi10_func {
msa_ld_op = 8,
msa_st_op = 9,
};
/*
* MSA 2 bit format fields.
*/
enum msa_2b_fmt {
msa_fmt_b = 0,
msa_fmt_h = 1,
msa_fmt_w = 2,
msa_fmt_d = 3,
};
/*
* (microMIPS) Major opcodes.
*/
enum mm_major_op {
mm_pool32a_op, mm_pool16a_op, mm_lbu16_op, mm_move16_op,
mm_addi32_op, mm_lbu32_op, mm_sb32_op, mm_lb32_op,
mm_pool32b_op, mm_pool16b_op, mm_lhu16_op, mm_andi16_op,
mm_addiu32_op, mm_lhu32_op, mm_sh32_op, mm_lh32_op,
mm_pool32i_op, mm_pool16c_op, mm_lwsp16_op, mm_pool16d_op,
mm_ori32_op, mm_pool32f_op, mm_reserved1_op, mm_reserved2_op,
mm_pool32c_op, mm_lwgp16_op, mm_lw16_op, mm_pool16e_op,
mm_xori32_op, mm_jals32_op, mm_addiupc_op, mm_reserved3_op,
mm_reserved4_op, mm_pool16f_op, mm_sb16_op, mm_beqz16_op,
mm_slti32_op, mm_beq32_op, mm_swc132_op, mm_lwc132_op,
mm_reserved5_op, mm_reserved6_op, mm_sh16_op, mm_bnez16_op,
mm_sltiu32_op, mm_bne32_op, mm_sdc132_op, mm_ldc132_op,
mm_reserved7_op, mm_reserved8_op, mm_swsp16_op, mm_b16_op,
mm_andi32_op, mm_j32_op, mm_sd32_op, mm_ld32_op,
mm_reserved11_op, mm_reserved12_op, mm_sw16_op, mm_li16_op,
mm_jalx32_op, mm_jal32_op, mm_sw32_op, mm_lw32_op,
};
/*
* (microMIPS) POOL32I minor opcodes.
*/
enum mm_32i_minor_op {
mm_bltz_op, mm_bltzal_op, mm_bgez_op, mm_bgezal_op,
mm_blez_op, mm_bnezc_op, mm_bgtz_op, mm_beqzc_op,
mm_tlti_op, mm_tgei_op, mm_tltiu_op, mm_tgeiu_op,
mm_tnei_op, mm_lui_op, mm_teqi_op, mm_reserved13_op,
mm_synci_op, mm_bltzals_op, mm_reserved14_op, mm_bgezals_op,
mm_bc2f_op, mm_bc2t_op, mm_reserved15_op, mm_reserved16_op,
mm_reserved17_op, mm_reserved18_op, mm_bposge64_op, mm_bposge32_op,
mm_bc1f_op, mm_bc1t_op, mm_reserved19_op, mm_reserved20_op,
mm_bc1any2f_op, mm_bc1any2t_op, mm_bc1any4f_op, mm_bc1any4t_op,
};
/*
* (microMIPS) POOL32A minor opcodes.
*/
enum mm_32a_minor_op {
mm_sll32_op = 0x000,
mm_ins_op = 0x00c,
mm_sllv32_op = 0x010,
mm_ext_op = 0x02c,
mm_pool32axf_op = 0x03c,
mm_srl32_op = 0x040,
mm_sra_op = 0x080,
mm_srlv32_op = 0x090,
mm_rotr_op = 0x0c0,
mm_lwxs_op = 0x118,
mm_addu32_op = 0x150,
mm_subu32_op = 0x1d0,
mm_wsbh_op = 0x1ec,
mm_mul_op = 0x210,
mm_and_op = 0x250,
mm_or32_op = 0x290,
mm_xor32_op = 0x310,
mm_slt_op = 0x350,
mm_sltu_op = 0x390,
};
/*
* (microMIPS) POOL32B functions.
*/
enum mm_32b_func {
mm_lwc2_func = 0x0,
mm_lwp_func = 0x1,
mm_ldc2_func = 0x2,
mm_ldp_func = 0x4,
mm_lwm32_func = 0x5,
mm_cache_func = 0x6,
mm_ldm_func = 0x7,
mm_swc2_func = 0x8,
mm_swp_func = 0x9,
mm_sdc2_func = 0xa,
mm_sdp_func = 0xc,
mm_swm32_func = 0xd,
mm_sdm_func = 0xf,
};
/*
* (microMIPS) POOL32C functions.
*/
enum mm_32c_func {
mm_pref_func = 0x2,
mm_ll_func = 0x3,
mm_swr_func = 0x9,
mm_sc_func = 0xb,
mm_lwu_func = 0xe,
};
/*
* (microMIPS) POOL32AXF minor opcodes.
*/
enum mm_32axf_minor_op {
mm_mfc0_op = 0x003,
mm_mtc0_op = 0x00b,
mm_tlbp_op = 0x00d,
mm_mfhi32_op = 0x035,
mm_jalr_op = 0x03c,
mm_tlbr_op = 0x04d,
mm_mflo32_op = 0x075,
mm_jalrhb_op = 0x07c,
mm_tlbwi_op = 0x08d,
mm_tlbwr_op = 0x0cd,
mm_jalrs_op = 0x13c,
mm_jalrshb_op = 0x17c,
mm_sync_op = 0x1ad,
mm_syscall_op = 0x22d,
mm_wait_op = 0x24d,
mm_eret_op = 0x3cd,
mm_divu_op = 0x5dc,
};
/*
* (microMIPS) POOL32F minor opcodes.
*/
enum mm_32f_minor_op {
mm_32f_00_op = 0x00,
mm_32f_01_op = 0x01,
mm_32f_02_op = 0x02,
mm_32f_10_op = 0x08,
mm_32f_11_op = 0x09,
mm_32f_12_op = 0x0a,
mm_32f_20_op = 0x10,
mm_32f_30_op = 0x18,
mm_32f_40_op = 0x20,
mm_32f_41_op = 0x21,
mm_32f_42_op = 0x22,
mm_32f_50_op = 0x28,
mm_32f_51_op = 0x29,
mm_32f_52_op = 0x2a,
mm_32f_60_op = 0x30,
mm_32f_70_op = 0x38,
mm_32f_73_op = 0x3b,
mm_32f_74_op = 0x3c,
};
/*
* (microMIPS) POOL32F secondary minor opcodes.
*/
enum mm_32f_10_minor_op {
mm_lwxc1_op = 0x1,
mm_swxc1_op,
mm_ldxc1_op,
mm_sdxc1_op,
mm_luxc1_op,
mm_suxc1_op,
};
enum mm_32f_func {
mm_lwxc1_func = 0x048,
mm_swxc1_func = 0x088,
mm_ldxc1_func = 0x0c8,
mm_sdxc1_func = 0x108,
};
/*
* (microMIPS) POOL32F secondary minor opcodes.
*/
enum mm_32f_40_minor_op {
mm_fmovf_op,
mm_fmovt_op,
};
/*
* (microMIPS) POOL32F secondary minor opcodes.
*/
enum mm_32f_60_minor_op {
mm_fadd_op,
mm_fsub_op,
mm_fmul_op,
mm_fdiv_op,
};
/*
* (microMIPS) POOL32F secondary minor opcodes.
*/
enum mm_32f_70_minor_op {
mm_fmovn_op,
mm_fmovz_op,
};
/*
* (microMIPS) POOL32FXF secondary minor opcodes for POOL32F.
*/
enum mm_32f_73_minor_op {
mm_fmov0_op = 0x01,
mm_fcvtl_op = 0x04,
mm_movf0_op = 0x05,
mm_frsqrt_op = 0x08,
mm_ffloorl_op = 0x0c,
mm_fabs0_op = 0x0d,
mm_fcvtw_op = 0x24,
mm_movt0_op = 0x25,
mm_fsqrt_op = 0x28,
mm_ffloorw_op = 0x2c,
mm_fneg0_op = 0x2d,
mm_cfc1_op = 0x40,
mm_frecip_op = 0x48,
mm_fceill_op = 0x4c,
mm_fcvtd0_op = 0x4d,
mm_ctc1_op = 0x60,
mm_fceilw_op = 0x6c,
mm_fcvts0_op = 0x6d,
mm_mfc1_op = 0x80,
mm_fmov1_op = 0x81,
mm_movf1_op = 0x85,
mm_ftruncl_op = 0x8c,
mm_fabs1_op = 0x8d,
mm_mtc1_op = 0xa0,
mm_movt1_op = 0xa5,
mm_ftruncw_op = 0xac,
mm_fneg1_op = 0xad,
mm_mfhc1_op = 0xc0,
mm_froundl_op = 0xcc,
mm_fcvtd1_op = 0xcd,
mm_mthc1_op = 0xe0,
mm_froundw_op = 0xec,
mm_fcvts1_op = 0xed,
};
/*
* (microMIPS) POOL16C minor opcodes.
*/
enum mm_16c_minor_op {
mm_lwm16_op = 0x04,
mm_swm16_op = 0x05,
mm_jr16_op = 0x0c,
mm_jrc_op = 0x0d,
mm_jalr16_op = 0x0e,
mm_jalrs16_op = 0x0f,
mm_jraddiusp_op = 0x18,
};
/*
* (microMIPS) POOL16D minor opcodes.
*/
enum mm_16d_minor_op {
mm_addius5_func,
mm_addiusp_func,
};
/*
* (MIPS16e) opcodes.
*/
enum MIPS16e_ops {
MIPS16e_jal_op = 003,
MIPS16e_ld_op = 007,
MIPS16e_i8_op = 014,
MIPS16e_sd_op = 017,
MIPS16e_lb_op = 020,
MIPS16e_lh_op = 021,
MIPS16e_lwsp_op = 022,
MIPS16e_lw_op = 023,
MIPS16e_lbu_op = 024,
MIPS16e_lhu_op = 025,
MIPS16e_lwpc_op = 026,
MIPS16e_lwu_op = 027,
MIPS16e_sb_op = 030,
MIPS16e_sh_op = 031,
MIPS16e_swsp_op = 032,
MIPS16e_sw_op = 033,
MIPS16e_rr_op = 035,
MIPS16e_extend_op = 036,
MIPS16e_i64_op = 037,
};
enum MIPS16e_i64_func {
MIPS16e_ldsp_func,
MIPS16e_sdsp_func,
MIPS16e_sdrasp_func,
MIPS16e_dadjsp_func,
MIPS16e_ldpc_func,
};
enum MIPS16e_rr_func {
MIPS16e_jr_func,
};
enum MIPS6e_i8_func {
MIPS16e_swrasp_func = 02,
};
/*
* (microMIPS) NOP instruction.
*/
#define MM_NOP16 0x0c00
struct j_format {
__BITFIELD_FIELD(unsigned int opcode : 6, /* Jump format */
__BITFIELD_FIELD(unsigned int target : 26,
;))
};
struct i_format { /* signed immediate format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(signed int simmediate : 16,
;))))
};
struct u_format { /* unsigned immediate format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int uimmediate : 16,
;))))
};
struct c_format { /* Cache (>= R6000) format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int c_op : 3,
__BITFIELD_FIELD(unsigned int cache : 2,
__BITFIELD_FIELD(unsigned int simmediate : 16,
;)))))
};
struct r_format { /* Register format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int rd : 5,
__BITFIELD_FIELD(unsigned int re : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct p_format { /* Performance counter format (R10000) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int rd : 5,
__BITFIELD_FIELD(unsigned int re : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct f_format { /* FPU register format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int : 1,
__BITFIELD_FIELD(unsigned int fmt : 4,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int rd : 5,
__BITFIELD_FIELD(unsigned int re : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;)))))))
};
struct ma_format { /* FPU multiply and add format (MIPS IV) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int fr : 5,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int func : 4,
__BITFIELD_FIELD(unsigned int fmt : 2,
;)))))))
};
struct b_format { /* BREAK and SYSCALL */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int code : 20,
__BITFIELD_FIELD(unsigned int func : 6,
;)))
};
struct ps_format { /* MIPS-3D / paired single format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct v_format { /* MDMX vector format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int sel : 4,
__BITFIELD_FIELD(unsigned int fmt : 1,
__BITFIELD_FIELD(unsigned int vt : 5,
__BITFIELD_FIELD(unsigned int vs : 5,
__BITFIELD_FIELD(unsigned int vd : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;)))))))
};
struct msa_mi10_format { /* MSA MI10 */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(signed int s10 : 10,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(unsigned int wd : 5,
__BITFIELD_FIELD(unsigned int func : 4,
__BITFIELD_FIELD(unsigned int df : 2,
;))))))
};
struct spec3_format { /* SPEC3 */
__BITFIELD_FIELD(unsigned int opcode:6,
__BITFIELD_FIELD(unsigned int rs:5,
__BITFIELD_FIELD(unsigned int rt:5,
__BITFIELD_FIELD(signed int simmediate:9,
__BITFIELD_FIELD(unsigned int func:7,
;)))))
};
/*
* microMIPS instruction formats (32-bit length)
*
* NOTE:
* Parenthesis denote whether the format is a microMIPS instruction or
* if it is MIPS32 instruction re-encoded for use in the microMIPS ASE.
*/
struct fb_format { /* FPU branch format (MIPS32) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int bc : 5,
__BITFIELD_FIELD(unsigned int cc : 3,
__BITFIELD_FIELD(unsigned int flag : 2,
__BITFIELD_FIELD(signed int simmediate : 16,
;)))))
};
struct fp0_format { /* FPU multiply and add format (MIPS32) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int fmt : 5,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_fp0_format { /* FPU multiply and add format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int fmt : 3,
__BITFIELD_FIELD(unsigned int op : 2,
__BITFIELD_FIELD(unsigned int func : 6,
;)))))))
};
struct fp1_format { /* FPU mfc1 and cfc1 format (MIPS32) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int op : 5,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_fp1_format { /* FPU mfc1 and cfc1 format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fmt : 2,
__BITFIELD_FIELD(unsigned int op : 8,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_fp2_format { /* FPU movt and movf format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int cc : 3,
__BITFIELD_FIELD(unsigned int zero : 2,
__BITFIELD_FIELD(unsigned int fmt : 2,
__BITFIELD_FIELD(unsigned int op : 3,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))))
};
struct mm_fp3_format { /* FPU abs and neg format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fmt : 3,
__BITFIELD_FIELD(unsigned int op : 7,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_fp4_format { /* FPU c.cond format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int cc : 3,
__BITFIELD_FIELD(unsigned int fmt : 3,
__BITFIELD_FIELD(unsigned int cond : 4,
__BITFIELD_FIELD(unsigned int func : 6,
;)))))))
};
struct mm_fp5_format { /* FPU lwxc1 and swxc1 format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int index : 5,
__BITFIELD_FIELD(unsigned int base : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int op : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct fp6_format { /* FPU madd and msub format (MIPS IV) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int fr : 5,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_fp6_format { /* FPU madd and msub format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int ft : 5,
__BITFIELD_FIELD(unsigned int fs : 5,
__BITFIELD_FIELD(unsigned int fd : 5,
__BITFIELD_FIELD(unsigned int fr : 5,
__BITFIELD_FIELD(unsigned int func : 6,
;))))))
};
struct mm_i_format { /* Immediate format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(unsigned int rs : 5,
__BITFIELD_FIELD(signed int simmediate : 16,
;))))
};
struct mm_m_format { /* Multi-word load/store format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rd : 5,
__BITFIELD_FIELD(unsigned int base : 5,
__BITFIELD_FIELD(unsigned int func : 4,
__BITFIELD_FIELD(signed int simmediate : 12,
;)))))
};
struct mm_x_format { /* Scaled indexed load format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int index : 5,
__BITFIELD_FIELD(unsigned int base : 5,
__BITFIELD_FIELD(unsigned int rd : 5,
__BITFIELD_FIELD(unsigned int func : 11,
;)))))
};
struct mm_a_format { /* ADDIUPC format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 3,
__BITFIELD_FIELD(signed int simmediate : 23,
;)))
};
/*
* microMIPS instruction formats (16-bit length)
*/
struct mm_b0_format { /* Unconditional branch format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(signed int simmediate : 10,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;)))
};
struct mm_b1_format { /* Conditional branch format (microMIPS) */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rs : 3,
__BITFIELD_FIELD(signed int simmediate : 7,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;))))
};
struct mm16_m_format { /* Multi-word load/store format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int func : 4,
__BITFIELD_FIELD(unsigned int rlist : 2,
__BITFIELD_FIELD(unsigned int imm : 4,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;)))))
};
struct mm16_rb_format { /* Signed immediate format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 3,
__BITFIELD_FIELD(unsigned int base : 3,
__BITFIELD_FIELD(signed int simmediate : 4,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;)))))
};
struct mm16_r3_format { /* Load from global pointer format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 3,
__BITFIELD_FIELD(signed int simmediate : 7,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;))))
};
struct mm16_r5_format { /* Load/store from stack pointer format */
__BITFIELD_FIELD(unsigned int opcode : 6,
__BITFIELD_FIELD(unsigned int rt : 5,
__BITFIELD_FIELD(signed int simmediate : 5,
__BITFIELD_FIELD(unsigned int : 16, /* Ignored */
;))))
};
/*
* MIPS16e instruction formats (16-bit length)
*/
struct m16e_rr {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int rx : 3,
__BITFIELD_FIELD(unsigned int nd : 1,
__BITFIELD_FIELD(unsigned int l : 1,
__BITFIELD_FIELD(unsigned int ra : 1,
__BITFIELD_FIELD(unsigned int func : 5,
;))))))
};
struct m16e_jal {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int x : 1,
__BITFIELD_FIELD(unsigned int imm20_16 : 5,
__BITFIELD_FIELD(signed int imm25_21 : 5,
;))))
};
struct m16e_i64 {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int func : 3,
__BITFIELD_FIELD(unsigned int imm : 8,
;)))
};
struct m16e_ri64 {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int func : 3,
__BITFIELD_FIELD(unsigned int ry : 3,
__BITFIELD_FIELD(unsigned int imm : 5,
;))))
};
struct m16e_ri {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int rx : 3,
__BITFIELD_FIELD(unsigned int imm : 8,
;)))
};
struct m16e_rri {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int rx : 3,
__BITFIELD_FIELD(unsigned int ry : 3,
__BITFIELD_FIELD(unsigned int imm : 5,
;))))
};
struct m16e_i8 {
__BITFIELD_FIELD(unsigned int opcode : 5,
__BITFIELD_FIELD(unsigned int func : 3,
__BITFIELD_FIELD(unsigned int imm : 8,
;)))
};
union mips_instruction {
unsigned int word;
unsigned short halfword[2];
unsigned char byte[4];
struct j_format j_format;
struct i_format i_format;
struct u_format u_format;
struct c_format c_format;
struct r_format r_format;
struct p_format p_format;
struct f_format f_format;
struct ma_format ma_format;
struct msa_mi10_format msa_mi10_format;
struct b_format b_format;
struct ps_format ps_format;
struct v_format v_format;
struct spec3_format spec3_format;
struct fb_format fb_format;
struct fp0_format fp0_format;
struct mm_fp0_format mm_fp0_format;
struct fp1_format fp1_format;
struct mm_fp1_format mm_fp1_format;
struct mm_fp2_format mm_fp2_format;
struct mm_fp3_format mm_fp3_format;
struct mm_fp4_format mm_fp4_format;
struct mm_fp5_format mm_fp5_format;
struct fp6_format fp6_format;
struct mm_fp6_format mm_fp6_format;
struct mm_i_format mm_i_format;
struct mm_m_format mm_m_format;
struct mm_x_format mm_x_format;
struct mm_a_format mm_a_format;
struct mm_b0_format mm_b0_format;
struct mm_b1_format mm_b1_format;
struct mm16_m_format mm16_m_format ;
struct mm16_rb_format mm16_rb_format;
struct mm16_r3_format mm16_r3_format;
struct mm16_r5_format mm16_r5_format;
};
union mips16e_instruction {
unsigned int full : 16;
struct m16e_rr rr;
struct m16e_jal jal;
struct m16e_i64 i64;
struct m16e_ri64 ri64;
struct m16e_ri ri;
struct m16e_rri rri;
struct m16e_i8 i8;
};
#endif /* _UAPI_ASM_INST_H */
|
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-8 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba
#ifndef BOOST_THREAD_MOVE_HPP
#define BOOST_THREAD_MOVE_HPP
#include <boost/thread/detail/config.hpp>
#ifndef BOOST_NO_SFINAE
#include <boost/core/enable_if.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/decay.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/type_traits/remove_extent.hpp>
#include <boost/type_traits/is_array.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/add_pointer.hpp>
#include <boost/type_traits/decay.hpp>
#endif
#include <boost/thread/detail/delete.hpp>
#include <boost/move/utility.hpp>
#include <boost/move/traits.hpp>
#include <boost/config/abi_prefix.hpp>
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
#include <type_traits>
#endif
namespace boost
{
namespace detail
{
template <typename T>
struct enable_move_utility_emulation_dummy_specialization;
template<typename T>
struct thread_move_t
{
T& t;
explicit thread_move_t(T& t_):
t(t_)
{}
T& operator*() const
{
return t;
}
T* operator->() const
{
return &t;
}
private:
void operator=(thread_move_t&);
};
}
#if !defined BOOST_THREAD_USES_MOVE
#ifndef BOOST_NO_SFINAE
template<typename T>
typename enable_if<boost::is_convertible<T&,boost::detail::thread_move_t<T> >, boost::detail::thread_move_t<T> >::type move(T& t)
{
return boost::detail::thread_move_t<T>(t);
}
#endif
template<typename T>
boost::detail::thread_move_t<T> move(boost::detail::thread_move_t<T> t)
{
return t;
}
#endif //#if !defined BOOST_THREAD_USES_MOVE
}
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
#define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE)
#define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE)
#define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG
#define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END
#define BOOST_THREAD_RV(V) V
#define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE
#define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE)
#define BOOST_THREAD_DCL_MOVABLE(TYPE)
#define BOOST_THREAD_DCL_MOVABLE_BEG(T) \
namespace detail { \
template <typename T> \
struct enable_move_utility_emulation_dummy_specialization<
#define BOOST_THREAD_DCL_MOVABLE_END > \
: integral_constant<bool, false> \
{}; \
}
#elif ! defined BOOST_NO_CXX11_RVALUE_REFERENCES && defined BOOST_MSVC
#define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE)
#define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE)
#define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG
#define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END
#define BOOST_THREAD_RV(V) V
#define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE
#define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE)
#define BOOST_THREAD_DCL_MOVABLE(TYPE)
#define BOOST_THREAD_DCL_MOVABLE_BEG(T) \
namespace detail { \
template <typename T> \
struct enable_move_utility_emulation_dummy_specialization<
#define BOOST_THREAD_DCL_MOVABLE_END > \
: integral_constant<bool, false> \
{}; \
}
#else
#if defined BOOST_THREAD_USES_MOVE
#define BOOST_THREAD_RV_REF(TYPE) BOOST_RV_REF(TYPE)
#define BOOST_THREAD_RV_REF_2_TEMPL_ARGS(TYPE) BOOST_RV_REF_2_TEMPL_ARGS(TYPE)
#define BOOST_THREAD_RV_REF_BEG BOOST_RV_REF_BEG
#define BOOST_THREAD_RV_REF_END BOOST_RV_REF_END
#define BOOST_THREAD_RV(V) V
#define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE)
#define BOOST_THREAD_DCL_MOVABLE(TYPE)
#define BOOST_THREAD_DCL_MOVABLE_BEG(T) \
namespace detail { \
template <typename T> \
struct enable_move_utility_emulation_dummy_specialization<
#define BOOST_THREAD_DCL_MOVABLE_END > \
: integral_constant<bool, false> \
{}; \
}
#else
#define BOOST_THREAD_RV_REF(TYPE) boost::detail::thread_move_t< TYPE >
#define BOOST_THREAD_RV_REF_BEG boost::detail::thread_move_t<
#define BOOST_THREAD_RV_REF_END >
#define BOOST_THREAD_RV(V) (*V)
#define BOOST_THREAD_FWD_REF(TYPE) BOOST_FWD_REF(TYPE)
#define BOOST_THREAD_DCL_MOVABLE(TYPE) \
template <> \
struct enable_move_utility_emulation< TYPE > \
{ \
static const bool value = false; \
};
#define BOOST_THREAD_DCL_MOVABLE_BEG(T) \
template <typename T> \
struct enable_move_utility_emulation<
#define BOOST_THREAD_DCL_MOVABLE_END > \
{ \
static const bool value = false; \
};
#endif
namespace boost
{
namespace detail
{
template <typename T>
BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type)
make_rv_ref(T v) BOOST_NOEXCEPT
{
return (BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v);
}
// template <typename T>
// BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type)
// make_rv_ref(T &v) BOOST_NOEXCEPT
// {
// return (BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v);
// }
// template <typename T>
// const BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type)
// make_rv_ref(T const&v) BOOST_NOEXCEPT
// {
// return (const BOOST_THREAD_RV_REF(typename ::boost::remove_cv<typename ::boost::remove_reference<T>::type>::type))(v);
// }
}
}
#define BOOST_THREAD_MAKE_RV_REF(RVALUE) RVALUE.move()
//#define BOOST_THREAD_MAKE_RV_REF(RVALUE) boost::detail::make_rv_ref(RVALUE)
#endif
#if ! defined BOOST_NO_CXX11_RVALUE_REFERENCES
#define BOOST_THREAD_MOVABLE(TYPE)
#else
#if defined BOOST_THREAD_USES_MOVE
#define BOOST_THREAD_MOVABLE(TYPE) \
::boost::rv<TYPE>& move() BOOST_NOEXCEPT \
{ \
return *static_cast< ::boost::rv<TYPE>* >(this); \
} \
const ::boost::rv<TYPE>& move() const BOOST_NOEXCEPT \
{ \
return *static_cast<const ::boost::rv<TYPE>* >(this); \
} \
operator ::boost::rv<TYPE>&() \
{ \
return *static_cast< ::boost::rv<TYPE>* >(this); \
} \
operator const ::boost::rv<TYPE>&() const \
{ \
return *static_cast<const ::boost::rv<TYPE>* >(this); \
}\
#else
#define BOOST_THREAD_MOVABLE(TYPE) \
operator ::boost::detail::thread_move_t<TYPE>() BOOST_NOEXCEPT \
{ \
return move(); \
} \
::boost::detail::thread_move_t<TYPE> move() BOOST_NOEXCEPT \
{ \
::boost::detail::thread_move_t<TYPE> x(*this); \
return x; \
} \
#endif
#endif
#define BOOST_THREAD_MOVABLE_ONLY(TYPE) \
BOOST_THREAD_NO_COPYABLE(TYPE) \
BOOST_THREAD_MOVABLE(TYPE) \
#define BOOST_THREAD_COPYABLE_AND_MOVABLE(TYPE) \
BOOST_THREAD_MOVABLE(TYPE) \
namespace boost
{
namespace thread_detail
{
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class Tp>
struct remove_reference : boost::remove_reference<Tp> {};
template <class Tp>
struct decay : boost::decay<Tp> {};
#else
template <class Tp>
struct remove_reference
{
typedef Tp type;
};
template <class Tp>
struct remove_reference<Tp&>
{
typedef Tp type;
};
template <class Tp>
struct remove_reference< rv<Tp> > {
typedef Tp type;
};
template <class Tp>
struct decay
{
private:
typedef typename boost::move_detail::remove_rvalue_reference<Tp>::type Up0;
typedef typename boost::remove_reference<Up0>::type Up;
public:
typedef typename conditional
<
is_array<Up>::value,
typename remove_extent<Up>::type*,
typename conditional
<
is_function<Up>::value,
typename add_pointer<Up>::type,
typename remove_cv<Up>::type
>::type
>::type type;
};
#endif
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
typename decay<T>::type
decay_copy(T&& t)
{
return boost::forward<T>(t);
}
#else
template <class T>
typename decay<T>::type
decay_copy(BOOST_THREAD_FWD_REF(T) t)
{
return boost::forward<T>(t);
}
#endif
}
}
#include <boost/config/abi_suffix.hpp>
#endif
|
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_REMOVE_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_REMOVE_HPP_INCLUDED
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/detail/range_return.hpp>
#include <algorithm>
namespace boost
{
namespace range
{
/// \brief template function remove
///
/// range-based version of the remove std algorithm
///
/// \pre ForwardRange is a model of the ForwardRangeConcept
template< class ForwardRange, class Value >
inline BOOST_DEDUCED_TYPENAME range_iterator<ForwardRange>::type
remove(ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return std::remove(boost::begin(rng),boost::end(rng),val);
}
/// \overload
template< class ForwardRange, class Value >
inline BOOST_DEDUCED_TYPENAME range_iterator<const ForwardRange>::type
remove(const ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return std::remove(boost::begin(rng),boost::end(rng),val);
}
// range_return overloads
/// \overload
template< range_return_value re, class ForwardRange, class Value >
inline BOOST_DEDUCED_TYPENAME range_return<ForwardRange,re>::type
remove(ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return range_return<ForwardRange,re>::pack(
std::remove(boost::begin(rng), boost::end(rng), val),
rng);
}
/// \overload
template< range_return_value re, class ForwardRange, class Value >
inline BOOST_DEDUCED_TYPENAME range_return<const ForwardRange,re>::type
remove(const ForwardRange& rng, const Value& val)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return range_return<const ForwardRange,re>::pack(
std::remove(boost::begin(rng), boost::end(rng), val),
rng);
}
} // namespace range
using range::remove;
} // namespace boost
#endif // include guard
|
// -*- C++ -*-
// Copyright (C) 2005-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, 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
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file cc_hash_table_map_/debug_store_hash_fn_imps.hpp
* Contains implementations of cc_ht_map_'s debug-mode functions.
*/
#ifdef _GLIBCXX_DEBUG
PB_DS_CLASS_T_DEC
void
PB_DS_CLASS_C_DEC::
assert_entry_pointer_valid(const entry_pointer p_e, true_type,
const char* __file, int __line) const
{
debug_base::check_key_exists(PB_DS_V2F(p_e->m_value), __file, __line);
comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(PB_DS_V2F(p_e->m_value));
PB_DS_DEBUG_VERIFY(p_e->m_hash == pos_hash_pair.second);
}
#endif
|
import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import datetime_safe
from django.utils.importlib import import_module
class BaseDatabaseWrapper(local):
"""
Represents a database connection.
"""
ops = None
vendor = 'unknown'
def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):
# `settings_dict` should be a dictionary containing keys such as
# NAME, USER, etc. It's called `settings_dict` instead of `settings`
# to disambiguate it from Django settings modules.
self.connection = None
self.queries = []
self.settings_dict = settings_dict
self.alias = alias
self.use_debug_cursor = None
# Transaction related attributes
self.transaction_state = []
self.savepoint_state = 0
self._dirty = None
def __eq__(self, other):
return self.alias == other.alias
def __ne__(self, other):
return not self == other
def _commit(self):
if self.connection is not None:
return self.connection.commit()
def _rollback(self):
if self.connection is not None:
return self.connection.rollback()
def _enter_transaction_management(self, managed):
"""
A hook for backend-specific changes required when entering manual
transaction handling.
"""
pass
def _leave_transaction_management(self, managed):
"""
A hook for backend-specific changes required when leaving manual
transaction handling. Will usually be implemented only when
_enter_transaction_management() is also required.
"""
pass
def _savepoint(self, sid):
if not self.features.uses_savepoints:
return
self.cursor().execute(self.ops.savepoint_create_sql(sid))
def _savepoint_rollback(self, sid):
if not self.features.uses_savepoints:
return
self.cursor().execute(self.ops.savepoint_rollback_sql(sid))
def _savepoint_commit(self, sid):
if not self.features.uses_savepoints:
return
self.cursor().execute(self.ops.savepoint_commit_sql(sid))
def enter_transaction_management(self, managed=True):
"""
Enters transaction management for a running thread. It must be balanced with
the appropriate leave_transaction_management call, since the actual state is
managed as a stack.
The state and dirty flag are carried over from the surrounding block or
from the settings, if there is no surrounding block (dirty is always false
when no current block is running).
"""
if self.transaction_state:
self.transaction_state.append(self.transaction_state[-1])
else:
self.transaction_state.append(settings.TRANSACTIONS_MANAGED)
if self._dirty is None:
self._dirty = False
self._enter_transaction_management(managed)
def leave_transaction_management(self):
"""
Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.)
"""
self._leave_transaction_management(self.is_managed())
if self.transaction_state:
del self.transaction_state[-1]
else:
raise TransactionManagementError("This code isn't under transaction "
"management")
if self._dirty:
self.rollback()
raise TransactionManagementError("Transaction managed block ended with "
"pending COMMIT/ROLLBACK")
self._dirty = False
def is_dirty(self):
"""
Returns True if the current transaction requires a commit for changes to
happen.
"""
return self._dirty
def set_dirty(self):
"""
Sets a dirty flag for the current thread and code streak. This can be used
to decide in a managed block of code to decide whether there are open
changes waiting for commit.
"""
if self._dirty is not None:
self._dirty = True
else:
raise TransactionManagementError("This code isn't under transaction "
"management")
def set_clean(self):
"""
Resets a dirty flag for the current thread and code streak. This can be used
to decide in a managed block of code to decide whether a commit or rollback
should happen.
"""
if self._dirty is not None:
self._dirty = False
else:
raise TransactionManagementError("This code isn't under transaction management")
self.clean_savepoints()
def clean_savepoints(self):
self.savepoint_state = 0
def is_managed(self):
"""
Checks whether the transaction manager is in manual or in auto state.
"""
if self.transaction_state:
return self.transaction_state[-1]
return settings.TRANSACTIONS_MANAGED
def managed(self, flag=True):
"""
Puts the transaction manager into a manual state: managed transactions have
to be committed explicitly by the user. If you switch off transaction
management and there is a pending commit/rollback, the data will be
commited.
"""
top = self.transaction_state
if top:
top[-1] = flag
if not flag and self.is_dirty():
self._commit()
self.set_clean()
else:
raise TransactionManagementError("This code isn't under transaction "
"management")
def commit_unless_managed(self):
"""
Commits changes if the system is not in managed transaction mode.
"""
if not self.is_managed():
self._commit()
self.clean_savepoints()
else:
self.set_dirty()
def rollback_unless_managed(self):
"""
Rolls back changes if the system is not in managed transaction mode.
"""
if not self.is_managed():
self._rollback()
else:
self.set_dirty()
def commit(self):
"""
Does the commit itself and resets the dirty flag.
"""
self._commit()
self.set_clean()
def rollback(self):
"""
This function does the rollback itself and resets the dirty flag.
"""
self._rollback()
self.set_clean()
def savepoint(self):
"""
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
"""
thread_ident = thread.get_ident()
self.savepoint_state += 1
tid = str(thread_ident).replace('-', '')
sid = "s%s_x%d" % (tid, self.savepoint_state)
self._savepoint(sid)
return sid
def savepoint_rollback(self, sid):
"""
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
if self.savepoint_state:
self._savepoint_rollback(sid)
def savepoint_commit(self, sid):
"""
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
if self.savepoint_state:
self._savepoint_commit(sid)
def close(self):
if self.connection is not None:
self.connection.close()
self.connection = None
def cursor(self):
if (self.use_debug_cursor or
(self.use_debug_cursor is None and settings.DEBUG)):
cursor = self.make_debug_cursor(self._cursor())
else:
cursor = util.CursorWrapper(self._cursor(), self)
return cursor
def make_debug_cursor(self, cursor):
return util.CursorDebugWrapper(cursor, self)
class BaseDatabaseFeatures(object):
allows_group_by_pk = False
# True if django.db.backend.utils.typecast_timestamp is used on values
# returned from dates() calls.
needs_datetime_string_cast = True
empty_fetchmany_value = []
update_can_self_select = True
# Does the backend distinguish between '' and None?
interprets_empty_strings_as_nulls = False
# Does the backend allow inserting duplicate rows when a unique_together
# constraint exists, but one of the unique_together columns is NULL?
ignores_nulls_in_unique_constraints = True
can_use_chunked_reads = True
can_return_id_from_insert = False
uses_autocommit = False
uses_savepoints = False
# If True, don't use integer foreign keys referring to, e.g., positive
# integer primary keys.
related_fields_match_type = False
allow_sliced_subqueries = True
supports_joins = True
distinguishes_insert_from_update = True
supports_deleting_related_objects = True
supports_select_related = True
# Does the default test database allow multiple connections?
# Usually an indication that the test database is in-memory
test_db_allows_multiple_connections = True
# Can an object be saved without an explicit primary key?
supports_unspecified_pk = False
# Can a fixture contain forward references? i.e., are
# FK constraints checked at the end of transaction, or
# at the end of each save operation?
supports_forward_references = True
# Does a dirty transaction need to be rolled back
# before the cursor can be used again?
requires_rollback_on_dirty_transaction = False
# Does the backend allow very long model names without error?
supports_long_model_names = True
# Is there a REAL datatype in addition to floats/doubles?
has_real_datatype = False
supports_subqueries_in_group_by = True
supports_bitwise_or = True
# Do time/datetime fields have microsecond precision?
supports_microsecond_precision = True
# Does the __regex lookup support backreferencing and grouping?
supports_regex_backreferencing = True
# Can date/datetime lookups be performed using a string?
supports_date_lookup_using_string = True
# Can datetimes with timezones be used?
supports_timezones = True
# When performing a GROUP BY, is an ORDER BY NULL required
# to remove any ordering?
requires_explicit_null_ordering_when_grouping = False
# Is there a 1000 item limit on query parameters?
supports_1000_query_parameters = True
# Can an object have a primary key of 0? MySQL says No.
allows_primary_key_0 = True
# Do we need to NULL a ForeignKey out, or can the constraint check be
# deferred
can_defer_constraint_checks = False
# date_interval_sql can properly handle mixed Date/DateTime fields and timedeltas
supports_mixed_date_datetime_comparisons = True
# Features that need to be confirmed at runtime
# Cache whether the confirmation has been performed.
_confirmed = False
supports_transactions = None
supports_stddev = None
can_introspect_foreign_keys = None
def __init__(self, connection):
self.connection = connection
def confirm(self):
"Perform manual checks of any database features that might vary between installs"
self._confirmed = True
self.supports_transactions = self._supports_transactions()
self.supports_stddev = self._supports_stddev()
self.can_introspect_foreign_keys = self._can_introspect_foreign_keys()
def _supports_transactions(self):
"Confirm support for transactions"
cursor = self.connection.cursor()
cursor.execute('CREATE TABLE ROLLBACK_TEST (X INT)')
self.connection._commit()
cursor.execute('INSERT INTO ROLLBACK_TEST (X) VALUES (8)')
self.connection._rollback()
cursor.execute('SELECT COUNT(X) FROM ROLLBACK_TEST')
count, = cursor.fetchone()
cursor.execute('DROP TABLE ROLLBACK_TEST')
self.connection._commit()
return count == 0
def _supports_stddev(self):
"Confirm support for STDDEV and related stats functions"
class StdDevPop(object):
sql_function = 'STDDEV_POP'
try:
self.connection.ops.check_aggregate_support(StdDevPop())
except NotImplementedError:
self.supports_stddev = False
def _can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
# Every database can do this reliably, except MySQL,
# which can't do it for MyISAM tables
return True
class BaseDatabaseOperations(object):
"""
This class encapsulates all backend-specific differences, such as the way
a backend performs ordering or calculates the ID of a recently-inserted
row.
"""
compiler_module = "django.db.models.sql.compiler"
def __init__(self):
self._cache = None
def autoinc_sql(self, table, column):
"""
Returns any SQL needed to support auto-incrementing primary keys, or
None if no SQL is necessary.
This SQL is executed when a table is created.
"""
return None
def date_extract_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
extracts a value from the given date field field_name.
"""
raise NotImplementedError()
def date_interval_sql(self, sql, connector, timedelta):
"""
Implements the date interval functionality for expressions
"""
raise NotImplementedError()
def date_trunc_sql(self, lookup_type, field_name):
"""
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
truncates the given date field field_name to a DATE object with only
the given specificity.
"""
raise NotImplementedError()
def datetime_cast_sql(self):
"""
Returns the SQL necessary to cast a datetime value so that it will be
retrieved as a Python datetime object instead of a string.
This SQL should include a '%s' in place of the field's name.
"""
return "%s"
def deferrable_sql(self):
"""
Returns the SQL necessary to make a constraint "initially deferred"
during a CREATE TABLE statement.
"""
return ''
def drop_foreignkey_sql(self):
"""
Returns the SQL command that drops a foreign key.
"""
return "DROP CONSTRAINT"
def drop_sequence_sql(self, table):
"""
Returns any SQL necessary to drop the sequence for the given table.
Returns None if no SQL is necessary.
"""
return None
def fetch_returned_insert_id(self, cursor):
"""
Given a cursor object that has just performed an INSERT...RETURNING
statement into a table that has an auto-incrementing ID, returns the
newly created ID.
"""
return cursor.fetchone()[0]
def field_cast_sql(self, db_type):
"""
Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary
to cast it before using it in a WHERE statement. Note that the
resulting string should contain a '%s' placeholder for the column being
searched against.
"""
return '%s'
def force_no_ordering(self):
"""
Returns a list used in the "ORDER BY" clause to force no ordering at
all. Returning an empty list means that nothing will be included in the
ordering.
"""
return []
def fulltext_search_sql(self, field_name):
"""
Returns the SQL WHERE clause to use in order to perform a full-text
search of the given field_name. Note that the resulting string should
contain a '%s' placeholder for the value being searched against.
"""
raise NotImplementedError('Full-text search is not implemented for this database backend')
def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
from django.utils.encoding import smart_unicode, force_unicode
# Convert params to contain Unicode values.
to_unicode = lambda s: force_unicode(s, strings_only=True, errors='replace')
if isinstance(params, (list, tuple)):
u_params = tuple([to_unicode(val) for val in params])
else:
u_params = dict([(to_unicode(k), to_unicode(v)) for k, v in params.items()])
return smart_unicode(sql) % u_params
def last_insert_id(self, cursor, table_name, pk_name):
"""
Given a cursor object that has just performed an INSERT statement into
a table that has an auto-incrementing ID, returns the newly created ID.
This method also receives the table name and the name of the primary-key
column.
"""
return cursor.lastrowid
def lookup_cast(self, lookup_type):
"""
Returns the string to use in a query when performing lookups
("contains", "like", etc). The resulting string should contain a '%s'
placeholder for the column being searched against.
"""
return "%s"
def max_in_list_size(self):
"""
Returns the maximum number of items that can be passed in a single 'IN'
list condition, or None if the backend does not impose a limit.
"""
return None
def max_name_length(self):
"""
Returns the maximum length of table and column names, or None if there
is no limit.
"""
return None
def no_limit_value(self):
"""
Returns the value to use for the LIMIT when we are wanting "LIMIT
infinity". Returns None if the limit clause can be omitted in this case.
"""
raise NotImplementedError
def pk_default_value(self):
"""
Returns the value to use during an INSERT statement to specify that
the field should use its default value.
"""
return 'DEFAULT'
def process_clob(self, value):
"""
Returns the value of a CLOB column, for backends that return a locator
object that requires additional processing.
"""
return value
def return_insert_id(self):
"""
For backends that support returning the last insert ID as part
of an insert query, this method returns the SQL and params to
append to the INSERT query. The returned fragment should
contain a format string to hold the appropriate column.
"""
pass
def compiler(self, compiler_name):
"""
Returns the SQLCompiler class corresponding to the given name,
in the namespace corresponding to the `compiler_module` attribute
on this backend.
"""
if self._cache is None:
self._cache = import_module(self.compiler_module)
return getattr(self._cache, compiler_name)
def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
raise NotImplementedError()
def random_function_sql(self):
"""
Returns a SQL expression that returns a random value.
"""
return 'RANDOM()'
def regex_lookup(self, lookup_type):
"""
Returns the string to use in a query when performing regular expression
lookups (using "regex" or "iregex"). The resulting string should
contain a '%s' placeholder for the column being searched against.
If the feature is not supported (or part of it is not supported), a
NotImplementedError exception can be raised.
"""
raise NotImplementedError
def savepoint_create_sql(self, sid):
"""
Returns the SQL for starting a new savepoint. Only required if the
"uses_savepoints" feature is True. The "sid" parameter is a string
for the savepoint id.
"""
raise NotImplementedError
def savepoint_commit_sql(self, sid):
"""
Returns the SQL for committing the given savepoint.
"""
raise NotImplementedError
def savepoint_rollback_sql(self, sid):
"""
Returns the SQL for rolling back the given savepoint.
"""
raise NotImplementedError
def sql_flush(self, style, tables, sequences):
"""
Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.
"""
raise NotImplementedError()
def sequence_reset_sql(self, style, model_list):
"""
Returns a list of the SQL statements required to reset sequences for
the given models.
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color.
"""
return [] # No sequence reset required by default.
def start_transaction_sql(self):
"""
Returns the SQL statement required to start a transaction.
"""
return "BEGIN;"
def end_transaction_sql(self, success=True):
if not success:
return "ROLLBACK;"
return "COMMIT;"
def tablespace_sql(self, tablespace, inline=False):
"""
Returns the SQL that will be appended to tables or rows to define
a tablespace. Returns '' if the backend doesn't use tablespaces.
"""
return ''
def prep_for_like_query(self, x):
"""Prepares a value for use in a LIKE query."""
from django.utils.encoding import smart_unicode
return smart_unicode(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_")
# Same as prep_for_like_query(), but called for "iexact" matches, which
# need not necessarily be implemented using "LIKE" in the backend.
prep_for_iexact_query = prep_for_like_query
def value_to_db_auto(self, value):
"""
Transform a value to an object compatible with the auto field required
by the backend driver for auto columns.
"""
if value is None:
return None
return int(value)
def value_to_db_date(self, value):
"""
Transform a date value to an object compatible with what is expected
by the backend driver for date columns.
"""
if value is None:
return None
return datetime_safe.new_date(value).strftime('%Y-%m-%d')
def value_to_db_datetime(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
return unicode(value)
def value_to_db_time(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
return unicode(value)
def value_to_db_decimal(self, value, max_digits, decimal_places):
"""
Transform a decimal.Decimal value to an object compatible with what is
expected by the backend driver for decimal (numeric) columns.
"""
if value is None:
return None
return util.format_number(value, max_digits, decimal_places)
def year_lookup_bounds(self, value):
"""
Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a field value using a year lookup
`value` is an int, containing the looked-up year.
"""
first = '%s-01-01 00:00:00'
second = '%s-12-31 23:59:59.999999'
return [first % value, second % value]
def year_lookup_bounds_for_date_field(self, value):
"""
Returns a two-elements list with the lower and upper bound to be used
with a BETWEEN operator to query a DateField value using a year lookup
`value` is an int, containing the looked-up year.
By default, it just calls `self.year_lookup_bounds`. Some backends need
this hook because on their DB date fields can't be compared to values
which include a time part.
"""
return self.year_lookup_bounds(value)
def convert_values(self, value, field):
"""Coerce the value returned by the database backend into a consistent type that
is compatible with the field type.
"""
internal_type = field.get_internal_type()
if internal_type == 'DecimalField':
return value
elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
return int(value)
elif internal_type in ('DateField', 'DateTimeField', 'TimeField'):
return value
# No field, or the field isn't known to be a decimal or integer
# Default to a float
return float(value)
def check_aggregate_support(self, aggregate_func):
"""Check that the backend supports the provided aggregate
This is used on specific backends to rule out known aggregates
that are known to have faulty implementations. If the named
aggregate function has a known problem, the backend should
raise NotImplemented.
"""
pass
def combine_expression(self, connector, sub_expressions):
"""Combine a list of subexpressions into a single expression, using
the provided connecting operator. This is required because operators
can vary between backends (e.g., Oracle with %% and &) and between
subexpression types (e.g., date expressions)
"""
conn = ' %s ' % connector
return conn.join(sub_expressions)
class BaseDatabaseIntrospection(object):
"""
This class encapsulates all backend-specific introspection utilities
"""
data_types_reverse = {}
def __init__(self, connection):
self.connection = connection
def get_field_type(self, data_type, description):
"""Hook for a database backend to use the cursor description to
match a Django field type to a database column.
For Oracle, the column data_type on its own is insufficient to
distinguish between a FloatField and IntegerField, for example."""
return self.data_types_reverse[data_type]
def table_name_converter(self, name):
"""Apply a conversion to the name for the purposes of comparison.
The default table name converter is for case sensitive comparison.
"""
return name
def table_names(self):
"Returns a list of names of all tables that exist in the database."
cursor = self.connection.cursor()
return self.get_table_list(cursor)
def django_table_names(self, only_existing=False):
"""
Returns a list of all table names that have associated Django models and
are in INSTALLED_APPS.
If only_existing is True, the resulting list will only include the tables
that actually exist in the database.
"""
from django.db import models, router
tables = set()
for app in models.get_apps():
for model in models.get_models(app):
if not model._meta.managed:
continue
if not router.allow_syncdb(self.connection.alias, model):
continue
tables.add(model._meta.db_table)
tables.update([f.m2m_db_table() for f in model._meta.local_many_to_many])
if only_existing:
existing_tables = self.table_names()
tables = [
t
for t in tables
if self.table_name_converter(t) in existing_tables
]
return tables
def installed_models(self, tables):
"Returns a set of all models represented by the provided list of table names."
from django.db import models, router
all_models = []
for app in models.get_apps():
for model in models.get_models(app):
if router.allow_syncdb(self.connection.alias, model):
all_models.append(model)
tables = map(self.table_name_converter, tables)
return set([
m for m in all_models
if self.table_name_converter(m._meta.db_table) in tables
])
def sequence_list(self):
"Returns a list of information about all DB sequences for all models in all apps."
from django.db import models, router
apps = models.get_apps()
sequence_list = []
for app in apps:
for model in models.get_models(app):
if not model._meta.managed:
continue
if not router.allow_syncdb(self.connection.alias, model):
continue
for f in model._meta.local_fields:
if isinstance(f, models.AutoField):
sequence_list.append({'table': model._meta.db_table, 'column': f.column})
break # Only one AutoField is allowed per model, so don't bother continuing.
for f in model._meta.local_many_to_many:
# If this is an m2m using an intermediate table,
# we don't need to reset the sequence.
if f.rel.through is None:
sequence_list.append({'table': f.m2m_db_table(), 'column': None})
return sequence_list
class BaseDatabaseClient(object):
"""
This class encapsulates all backend-specific methods for opening a
client shell.
"""
# This should be a string representing the name of the executable
# (e.g., "psql"). Subclasses must override this.
executable_name = None
def __init__(self, connection):
# connection is an instance of BaseDatabaseWrapper.
self.connection = connection
def runshell(self):
raise NotImplementedError()
class BaseDatabaseValidation(object):
"""
This class encapsualtes all backend-specific model validation.
"""
def __init__(self, connection):
self.connection = connection
def validate_field(self, errors, opts, f):
"By default, there is no backend-specific validation"
pass
|
/**
* @license Highmaps JS v5.0.1 (2016-10-26)
*
* (c) 2011-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = root.document ?
factory(root) :
factory;
} else {
root.Highcharts = factory(root);
}
}(typeof window !== 'undefined' ? window : this, function(win) {
var Highcharts = (function() {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/* global window */
var win = window,
doc = win.document;
var SVG_NS = 'http://www.w3.org/2000/svg',
userAgent = (win.navigator && win.navigator.userAgent) || '',
svg = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
isMS = /(edge|msie|trident)/i.test(userAgent) && !window.opera,
vml = !svg,
isFirefox = /Firefox/.test(userAgent),
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4; // issue #38
var Highcharts = win.Highcharts ? win.Highcharts.error(16, true) : {
product: 'Highmaps',
version: '5.0.1',
deg2rad: Math.PI * 2 / 360,
doc: doc,
hasBidiBug: hasBidiBug,
hasTouch: doc && doc.documentElement.ontouchstart !== undefined,
isMS: isMS,
isWebKit: /AppleWebKit/.test(userAgent),
isFirefox: isFirefox,
isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS: SVG_NS,
idCounter: 0,
chartCount: 0,
seriesTypes: {},
symbolSizes: {},
svg: svg,
vml: vml,
win: win,
charts: [],
marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
noop: function() {
return undefined;
}
};
return Highcharts;
}());
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var timers = [];
var charts = H.charts,
doc = H.doc,
win = H.win;
/**
* Provide error messages for debugging, with links to online explanation
*/
H.error = function(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw new Error(msg);
}
// else ...
if (win.console) {
console.log(msg); // eslint-disable-line no-console
}
};
/**
* An animator object. One instance applies to one property (attribute or style prop)
* on one element.
*
* @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper.
* @param {object} options Animation options, including duration, easing, step and complete.
* @param {object} prop The property to animate.
*/
H.Fx = function(elem, options, prop) {
this.options = options;
this.elem = elem;
this.prop = prop;
};
H.Fx.prototype = {
/**
* Animating a path definition on SVGElement
* @returns {undefined}
*/
dSetter: function() {
var start = this.paths[0],
end = this.paths[1],
ret = [],
now = this.now,
i = start.length,
startVal;
if (now === 1) { // land on the final path without adjustment points appended in the ends
ret = this.toD;
} else if (i === end.length && now < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
now * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
this.elem.attr('d', ret);
},
/**
* Update the element with the current animation step
* @returns {undefined}
*/
update: function() {
var elem = this.elem,
prop = this.prop, // if destroyed, it is null
now = this.now,
step = this.options.step;
// Animation setter defined from outside
if (this[prop + 'Setter']) {
this[prop + 'Setter']();
// Other animations on SVGElement
} else if (elem.attr) {
if (elem.element) {
elem.attr(prop, now);
}
// HTML styles, raw HTML content like container size
} else {
elem.style[prop] = now + this.unit;
}
if (step) {
step.call(elem, now, this);
}
},
/**
* Run an animation
*/
run: function(from, to, unit) {
var self = this,
timer = function(gotoEnd) {
return timer.stopped ? false : self.step(gotoEnd);
},
i;
this.startTime = +new Date();
this.start = from;
this.end = to;
this.unit = unit;
this.now = this.start;
this.pos = 0;
timer.elem = this.elem;
if (timer() && timers.push(timer) === 1) {
timer.timerId = setInterval(function() {
for (i = 0; i < timers.length; i++) {
if (!timers[i]()) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
clearInterval(timer.timerId);
}
}, 13);
}
},
/**
* Run a single step in the animation
* @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort
* @returns {Boolean} True if animation continues
*/
step: function(gotoEnd) {
var t = +new Date(),
ret,
done,
options = this.options,
elem = this.elem,
complete = options.complete,
duration = options.duration,
curAnim = options.curAnim,
i;
if (elem.attr && !elem.element) { // #2616, element including flag is destroyed
ret = false;
} else if (gotoEnd || t >= duration + this.startTime) {
this.now = this.end;
this.pos = 1;
this.update();
curAnim[this.prop] = true;
done = true;
for (i in curAnim) {
if (curAnim[i] !== true) {
done = false;
}
}
if (done && complete) {
complete.call(elem);
}
ret = false;
} else {
this.pos = options.easing((t - this.startTime) / duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
ret = true;
}
return ret;
},
/**
* Prepare start and end values so that the path can be animated one to one
*/
initPath: function(elem, fromD, toD) {
fromD = fromD || '';
var shift,
startX = elem.startX,
endX = elem.endX,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
fullLength,
slice,
i,
start = fromD.split(' '),
end = toD.slice(), // copy
isArea = elem.isArea,
positionFactor = isArea ? 2 : 1,
reverse;
/**
* In splines make move points have six parameters like bezier curves
*/
function sixify(arr) {
i = arr.length;
while (i--) {
if (arr[i] === 'M' || arr[i] === 'L') {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
}
/**
* Insert an array at the given position of another array
*/
function insertSlice(arr, subArr, index) {
[].splice.apply(
arr, [index, 0].concat(subArr)
);
}
/**
* If shifting points, prepend a dummy point to the end path.
*/
function prepend(arr, other) {
while (arr.length < fullLength) {
// Move to, line to or curve to?
arr[0] = other[fullLength - arr.length];
// Prepend a copy of the first point
insertSlice(arr, arr.slice(0, numParams), 0);
// For areas, the bottom path goes back again to the left, so we need
// to append a copy of the last point.
if (isArea) {
insertSlice(arr, arr.slice(arr.length - numParams), arr.length);
i--;
}
}
arr[0] = 'M';
}
/**
* Copy and append last point until the length matches the end length
*/
function append(arr, other) {
var i = (fullLength - arr.length) / numParams;
while (i > 0 && i--) {
// Pull out the slice that is going to be appended or inserted. In a line graph,
// the positionFactor is 1, and the last point is sliced out. In an area graph,
// the positionFactor is 2, causing the middle two points to be sliced out, since
// an area path starts at left, follows the upper path then turns and follows the
// bottom back.
slice = arr.slice().splice(
(arr.length / positionFactor) - numParams,
numParams * positionFactor
);
// Move to, line to or curve to?
slice[0] = other[fullLength - numParams - (i * numParams)];
// Disable first control point
if (bezier) {
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
// Now insert the slice, either in the middle (for areas) or at the end (for lines)
insertSlice(arr, slice, arr.length / positionFactor);
if (isArea) {
i--;
}
}
}
if (bezier) {
sixify(start);
sixify(end);
}
// For sideways animation, find out how much we need to shift to get the start path Xs
// to match the end path Xs.
if (startX && endX) {
for (i = 0; i < startX.length; i++) {
if (startX[i] === endX[0]) { // Moving left, new points coming in on right
shift = i;
break;
} else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right
shift = i;
reverse = true;
break;
}
}
if (shift === undefined) {
start = [];
}
}
if (start.length && H.isNumber(shift)) {
// The common target length for the start and end array, where both
// arrays are padded in opposite ends
fullLength = end.length + shift * positionFactor * numParams;
if (!reverse) {
prepend(end, start);
append(start, end);
} else {
prepend(start, end);
append(end, start);
}
}
return [start, end];
}
}; // End of Fx prototype
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
H.extend = function(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
};
/**
* Deep merge two or more objects and return a third object. If the first argument is
* true, the contents of the second object is copied into the first object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
H.merge = function() {
var i,
args = arguments,
len,
ret = {},
doCopy = function(copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (H.isObject(value, true) &&
key !== 'renderTo' && typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// If first argument is true, copy into the existing object. Used in setOptions.
if (args[0] === true) {
ret = args[1];
args = Array.prototype.slice.call(args, 2);
}
// For each argument, extend the return
len = args.length;
for (i = 0; i < len; i++) {
ret = doCopy(ret, args[i]);
}
return ret;
};
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
H.pInt = function(s, mag) {
return parseInt(s, mag || 10);
};
/**
* Check for string
* @param {Object} s
*/
H.isString = function(s) {
return typeof s === 'string';
};
/**
* Check for object
* @param {Object} obj
* @param {Boolean} strict Also checks that the object is not an array
*/
H.isArray = function(obj) {
var str = Object.prototype.toString.call(obj);
return str === '[object Array]' || str === '[object Array Iterator]';
};
/**
* Check for array
* @param {Object} obj
*/
H.isObject = function(obj, strict) {
return obj && typeof obj === 'object' && (!strict || !H.isArray(obj));
};
/**
* Check for number
* @param {Object} n
*/
H.isNumber = function(n) {
return typeof n === 'number' && !isNaN(n);
};
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
H.erase = function(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
};
/**
* Returns true if the object is not null or undefined.
* @param {Object} obj
*/
H.defined = function(obj) {
return obj !== undefined && obj !== null;
};
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
H.attr = function(elem, prop, value) {
var key,
ret;
// if the prop is a string
if (H.isString(prop)) {
// set the value
if (H.defined(value)) {
elem.setAttribute(prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (H.defined(prop) && H.isObject(prop)) {
for (key in prop) {
elem.setAttribute(key, prop[key]);
}
}
return ret;
};
/**
* Check if an element is an array, and if not, make it into an array.
*/
H.splat = function(obj) {
return H.isArray(obj) ? obj : [obj];
};
/**
* Set a timeout if the delay is given, otherwise perform the function synchronously
* @param {Function} fn The function to perform
* @param {Number} delay Delay in milliseconds
* @param {Ojbect} context The context
* @returns {Nubmer} An identifier for the timeout
*/
H.syncTimeout = function(fn, delay, context) {
if (delay) {
return setTimeout(fn, delay, context);
}
fn.call(0, context);
};
/**
* Return the first value that is defined.
*/
H.pick = function() {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (arg !== undefined && arg !== null) {
return arg;
}
}
};
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
H.css = function(el, styles) {
if (H.isMS && !H.svg) { // #2686
if (styles && styles.opacity !== undefined) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
H.extend(el.style, styles);
};
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
H.createElement = function(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag),
css = H.css;
if (attribs) {
H.extend(el, attribs);
}
if (nopad) {
css(el, {
padding: 0,
border: 'none',
margin: 0
});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
};
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
H.extendClass = function(Parent, members) {
var object = function() {};
object.prototype = new Parent();
H.extend(object.prototype, members);
return object;
};
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
H.pad = function(number, length, padder) {
return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number;
};
/**
* Return a length based on either the integer value, or a percentage of a base.
*/
H.relativeLength = function(value, base) {
return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value);
};
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
H.wrap = function(obj, method, func) {
var proceed = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
};
H.getTZOffset = function(timestamp) {
var d = H.Date;
return ((d.hcGetTimezoneOffset && d.hcGetTimezoneOffset(timestamp)) || d.hcTimezoneOffset || 0) * 60000;
};
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
H.dateFormat = function(format, timestamp, capitalize) {
if (!H.defined(timestamp) || isNaN(timestamp)) {
return H.defaultOptions.lang.invalidDate || '';
}
format = H.pick(format, '%Y-%m-%d %H:%M:%S');
var D = H.Date,
date = new D(timestamp - H.getTZOffset(timestamp)),
key, // used in for constuct below
// get the basic time values
hours = date[D.hcGetHours](),
day = date[D.hcGetDay](),
dayOfMonth = date[D.hcGetDate](),
month = date[D.hcGetMonth](),
fullYear = date[D.hcGetFullYear](),
lang = H.defaultOptions.lang,
langWeekdays = lang.weekdays,
shortWeekdays = lang.shortWeekdays,
pad = H.pad,
// List all format keys. Custom formats can be added from the outside.
replacements = H.extend({
// Day
'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31
'w': day,
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'k': hours, // Hours in 24h format, 0 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[D.hcGetMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(Math.round(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, H.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace(
'%' + key,
typeof replacements[key] === 'function' ?
replacements[key](timestamp) :
replacements[key]
);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
H.formatSingle = function(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = H.defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = H.numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = H.dateFormat(format, val);
}
return val;
};
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
H.format = function(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while (str) {
index = str.indexOf(splitter);
if (index === -1) {
break;
}
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = H.formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
};
/**
* Get the magnitude of a number
*/
H.getMagnitude = function(num) {
return Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
};
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
H.normalizeTickInterval = function(interval, multiples, magnitude, allowDecimals, preventExceed) {
var normalized,
i,
retInterval = interval;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = H.pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
retInterval = multiples[i];
if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
(!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
break;
}
}
// multiply back to the correct magnitude
retInterval *= magnitude;
return retInterval;
};
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
H.stableSort = function(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].safeI = i; // stable sort index
}
arr.sort(function(a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.safeI - b.safeI : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].safeI; // stable sort index
}
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMin = function(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMax = function(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
};
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
H.destroyObjectProperties = function(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
};
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
H.discardElement = function(element) {
var garbageBin = H.garbageBin;
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = H.createElement('div');
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
};
/**
* Fix JS round off float errors
* @param {Number} num
*/
H.correctFloat = function(num, prec) {
return parseFloat(
num.toPrecision(prec || 14)
);
};
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
H.setAnimation = function(animation, chart) {
chart.renderer.globalAnimation = H.pick(animation, chart.options.chart.animation, true);
};
/**
* Get the animation in object form, where a disabled animation is always
* returned with duration: 0
*/
H.animObject = function(animation) {
return H.isObject(animation) ? H.merge(animation) : {
duration: animation ? 500 : 0
};
};
/**
* The time unit lookup
*/
H.timeUnits = {
millisecond: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 24 * 3600000,
week: 7 * 24 * 3600000,
month: 28 * 24 * 3600000,
year: 364 * 24 * 3600000
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decimalPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
H.numberFormat = function(number, decimals, decimalPoint, thousandsSep) {
number = +number || 0;
decimals = +decimals;
var lang = H.defaultOptions.lang,
origDec = (number.toString().split('.')[1] || '').length,
decimalComponent,
strinteger,
thousands,
absNumber = Math.abs(number),
ret;
if (decimals === -1) {
decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
} else if (!H.isNumber(decimals)) {
decimals = 2;
}
// A string containing the positive integer component of the number
strinteger = String(H.pInt(absNumber.toFixed(decimals)));
// Leftover after grouping into thousands. Can be 0, 1 or 3.
thousands = strinteger.length > 3 ? strinteger.length % 3 : 0;
// Language
decimalPoint = H.pick(decimalPoint, lang.decimalPoint);
thousandsSep = H.pick(thousandsSep, lang.thousandsSep);
// Start building the return
ret = number < 0 ? '-' : '';
// Add the leftover after grouping into thousands. For example, in the number 42 000 000,
// this line adds 42.
ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
// Add the remaining thousands groups, joined by the thousands separator
ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep);
// Add the decimal point and the decimal component
if (decimals) {
// Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
}
return ret;
};
/**
* Easing definition
* @param {Number} pos Current position, ranging from 0 to 1
*/
Math.easeInOutSine = function(pos) {
return -0.5 * (Math.cos(Math.PI * pos) - 1);
};
/**
* Internal method to return CSS value for given element and property
*/
H.getStyle = function(el, prop) {
var style;
// For width and height, return the actual inner pixel size (#4913)
if (prop === 'width') {
return Math.min(el.offsetWidth, el.scrollWidth) -
H.getStyle(el, 'padding-left') -
H.getStyle(el, 'padding-right');
} else if (prop === 'height') {
return Math.min(el.offsetHeight, el.scrollHeight) -
H.getStyle(el, 'padding-top') -
H.getStyle(el, 'padding-bottom');
}
// Otherwise, get the computed style
style = win.getComputedStyle(el, undefined);
return style && H.pInt(style.getPropertyValue(prop));
};
/**
* Return the index of an item in an array, or -1 if not found
*/
H.inArray = function(item, arr) {
return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item);
};
/**
* Filter an array
*/
H.grep = function(elements, callback) {
return [].filter.call(elements, callback);
};
/**
* Map an array
*/
H.map = function(arr, fn) {
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
};
/**
* Get the element's offset position, corrected by overflow:auto.
*/
H.offset = function(el) {
var docElem = doc.documentElement,
box = el.getBoundingClientRect();
return {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
};
};
/**
* Stop running animation.
* A possible extension to this would be to stop a single property, when
* we want to continue animating others. Then assign the prop to the timer
* in the Fx.run method, and check for the prop here. This would be an improvement
* in all cases where we stop the animation from .attr. Instead of stopping
* everything, we can just stop the actual attributes we're setting.
*/
H.stop = function(el) {
var i = timers.length;
// Remove timers related to this element (#4519)
while (i--) {
if (timers[i].elem === el) {
timers[i].stopped = true; // #4667
}
}
};
/**
* Utility for iterating over an array.
* @param {Array} arr
* @param {Function} fn
*/
H.each = function(arr, fn, ctx) { // modern browsers
return Array.prototype.forEach.call(arr, fn, ctx);
};
/**
* Add an event listener
*/
H.addEvent = function(el, type, fn) {
var events = el.hcEvents = el.hcEvents || {};
function wrappedFn(e) {
e.target = e.srcElement || win; // #2820
fn.call(el, e);
}
// Handle DOM events in modern browsers
if (el.addEventListener) {
el.addEventListener(type, fn, false);
// Handle old IE implementation
} else if (el.attachEvent) {
if (!el.hcEventsIE) {
el.hcEventsIE = {};
}
// Link wrapped fn with original fn, so we can get this in removeEvent
el.hcEventsIE[fn.toString()] = wrappedFn;
el.attachEvent('on' + type, wrappedFn);
}
if (!events[type]) {
events[type] = [];
}
events[type].push(fn);
};
/**
* Remove event added with addEvent
*/
H.removeEvent = function(el, type, fn) {
var events,
hcEvents = el.hcEvents,
index;
function removeOneEvent(type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, false);
} else if (el.attachEvent) {
fn = el.hcEventsIE[fn.toString()];
el.detachEvent('on' + type, fn);
}
}
function removeAllEvents() {
var types,
len,
n;
if (!el.nodeName) {
return; // break on non-DOM events
}
if (type) {
types = {};
types[type] = true;
} else {
types = hcEvents;
}
for (n in types) {
if (hcEvents[n]) {
len = hcEvents[n].length;
while (len--) {
removeOneEvent(n, hcEvents[n][len]);
}
}
}
}
if (hcEvents) {
if (type) {
events = hcEvents[type] || [];
if (fn) {
index = H.inArray(fn, events);
if (index > -1) {
events.splice(index, 1);
hcEvents[type] = events;
}
removeOneEvent(type, fn);
} else {
removeAllEvents();
hcEvents[type] = [];
}
} else {
removeAllEvents();
el.hcEvents = {};
}
}
};
/**
* Fire an event on a custom object
*/
H.fireEvent = function(el, type, eventArguments, defaultFunction) {
var e,
hcEvents = el.hcEvents,
events,
len,
i,
fn;
eventArguments = eventArguments || {};
if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) {
e = doc.createEvent('Events');
e.initEvent(type, true, true);
//e.target = el;
H.extend(e, eventArguments);
if (el.dispatchEvent) {
el.dispatchEvent(e);
} else {
el.fireEvent(type, e);
}
} else if (hcEvents) {
events = hcEvents[type] || [];
len = events.length;
if (!eventArguments.target) { // We're running a custom event
H.extend(eventArguments, {
// Attach a simple preventDefault function to skip default handler if called.
// The built-in defaultPrevented property is not overwritable (#5112)
preventDefault: function() {
eventArguments.defaultPrevented = true;
},
// Setting target to native events fails with clicking the zoom-out button in Chrome.
target: el,
// If the type is not set, we're running a custom event (#2297). If it is set,
// we're running a browser event, and setting it will cause en error in
// IE8 (#2465).
type: type
});
}
for (i = 0; i < len; i++) {
fn = events[i];
// If the event handler return false, prevent the default handler from executing
if (fn && fn.call(el, eventArguments) === false) {
eventArguments.preventDefault();
}
}
}
// Run the default if not prevented
if (defaultFunction && !eventArguments.defaultPrevented) {
defaultFunction(eventArguments);
}
};
/**
* The global animate method, which uses Fx to create individual animators.
*/
H.animate = function(el, params, opt) {
var start,
unit = '',
end,
fx,
args,
prop;
if (!H.isObject(opt)) { // Number or undefined/null
args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (!H.isNumber(opt.duration)) {
opt.duration = 400;
}
opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine);
opt.curAnim = H.merge(params);
for (prop in params) {
fx = new H.Fx(el, opt, prop);
end = null;
if (prop === 'd') {
fx.paths = fx.initPath(
el,
el.d,
params.d
);
fx.toD = params.d;
start = 0;
end = 1;
} else if (el.attr) {
start = el.attr(prop);
} else {
start = parseFloat(H.getStyle(el, prop)) || 0;
if (prop !== 'opacity') {
unit = 'px';
}
}
if (!end) {
end = params[prop];
}
if (end.match && end.match('px')) {
end = end.replace(/px/g, ''); // #4351
}
fx.run(start, end, unit);
}
};
/**
* The series type factory.
*
* @param {string} type The series type name.
* @param {string} parent The parent series type name.
* @param {object} options The additional default options that is merged with the parent's options.
* @param {object} props The properties (functions and primitives) to set on the new prototype.
* @param {object} pointProps Members for a series-specific Point prototype if needed.
*/
H.seriesType = function(type, parent, options, props, pointProps) { // docs: add to API + extending Highcharts
var defaultOptions = H.getOptions(),
seriesTypes = H.seriesTypes;
// Merge the options
defaultOptions.plotOptions[type] = H.merge(
defaultOptions.plotOptions[parent],
options
);
// Create the class
seriesTypes[type] = H.extendClass(seriesTypes[parent] || function() {}, props);
seriesTypes[type].prototype.type = type;
// Create the point class if needed
if (pointProps) {
seriesTypes[type].prototype.pointClass = H.extendClass(H.Point, pointProps);
}
return seriesTypes[type];
};
/**
* Register Highcharts as a plugin in jQuery
*/
if (win.jQuery) {
win.jQuery.fn.highcharts = function() {
var args = [].slice.call(arguments);
if (this[0]) { // this[0] is the renderTo div
// Create the chart
if (args[0]) {
new H[ // eslint-disable-line no-new
H.isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart
](this[0], args[0], args[1]);
return this;
}
// When called without parameters or with the return argument, return an existing chart
return charts[H.attr(this[0], 'data-highcharts-chart')];
}
};
}
/**
* Compatibility section to add support for legacy IE. This can be removed if old IE
* support is not needed.
*/
if (doc && !doc.defaultView) {
H.getStyle = function(el, prop) {
var val,
alias = {
width: 'clientWidth',
height: 'clientHeight'
}[prop];
if (el.style[prop]) {
return H.pInt(el.style[prop]);
}
if (prop === 'opacity') {
prop = 'filter';
}
// Getting the rendered width and height
if (alias) {
el.style.zoom = 1;
return Math.max(el[alias] - 2 * H.getStyle(el, 'padding'), 0);
}
val = el.currentStyle[prop.replace(/\-(\w)/g, function(a, b) {
return b.toUpperCase();
})];
if (prop === 'filter') {
val = val.replace(
/alpha\(opacity=([0-9]+)\)/,
function(a, b) {
return b / 100;
}
);
}
return val === '' ? 1 : H.pInt(val);
};
}
if (!Array.prototype.forEach) {
H.each = function(arr, fn, ctx) { // legacy
var i = 0,
len = arr.length;
for (; i < len; i++) {
if (fn.call(ctx, arr[i], i, arr) === false) {
return i;
}
}
};
}
if (!Array.prototype.indexOf) {
H.inArray = function(item, arr) {
var len,
i = 0;
if (arr) {
len = arr.length;
for (; i < len; i++) {
if (arr[i] === item) {
return i;
}
}
}
return -1;
};
}
if (!Array.prototype.filter) {
H.grep = function(elements, fn) {
var ret = [],
i = 0,
length = elements.length;
for (; i < length; i++) {
if (fn(elements[i], i)) {
ret.push(elements[i]);
}
}
return ret;
};
}
//--- End compatibility section ---
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var each = H.each,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pInt = H.pInt;
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
H.Color = function(input) {
// Backwards compatibility, allow instanciation without new
if (!(this instanceof H.Color)) {
return new H.Color(input);
}
// Initialize
this.init(input);
};
H.Color.prototype = {
// Collection of parsers. This can be extended from the outside by pushing parsers
// to Highcharts.Color.prototype.parsers.
parsers: [{
// RGBA color
regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
}
}, {
// HEX color
regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
parse: function(result) {
return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
}
}, {
// RGB color
regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}],
// Collection of named colors. Can be extended from the outside by adding colors
// to Highcharts.Color.prototype.names.
names: {
white: '#ffffff',
black: '#000000'
},
/**
* Parse the input color to rgba array
* @param {String} input
*/
init: function(input) {
var result,
rgba,
i,
parser;
this.input = input = this.names[input] || input;
// Gradients
if (input && input.stops) {
this.stops = map(input.stops, function(stop) {
return new H.Color(stop[1]);
});
// Solid colors
} else {
i = this.parsers.length;
while (i-- && !rgba) {
parser = this.parsers[i];
result = parser.regex.exec(input);
if (result) {
rgba = parser.parse(result);
}
}
}
this.rgba = rgba || [];
},
/**
* Return the color a specified format
* @param {String} format
*/
get: function(format) {
var input = this.input,
rgba = this.rgba,
ret;
if (this.stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(this.stops, function(stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && isNumber(rgba[0])) {
if (format === 'rgb' || (!format && rgba[3] === 1)) {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
},
/**
* Brighten the color
* @param {Number} alpha
*/
brighten: function(alpha) {
var i,
rgba = this.rgba;
if (this.stops) {
each(this.stops, function(stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
},
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
setOpacity: function(alpha) {
this.rgba[3] = alpha;
return this;
}
};
H.color = function(input) {
return new H.Color(input);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
each = H.each,
getTZOffset = H.getTZOffset,
isTouchDevice = H.isTouchDevice,
merge = H.merge,
pick = H.pick,
svg = H.svg,
win = H.win;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
H.defaultOptions = {
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
// invalidDate: '',
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ' '
},
global: {
useUTC: true,
//timezoneOffset: 0
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderRadius: 0,
colorCount: 10,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
},
width: null,
height: null
},
defs: {
dropShadow: { // used by tooltip
tagName: 'filter',
id: 'drop-shadow',
opacity: 0.5,
children: [{
tagName: 'feGaussianBlur',
in: 'SourceAlpha',
stdDeviation: 1
}, {
tagName: 'feOffset',
dx: 1,
dy: 1
}, {
tagName: 'feComponentTransfer',
children: [{
tagName: 'feFuncA',
type: 'linear',
slope: 0.3
}]
}, {
tagName: 'feMerge',
children: [{
tagName: 'feMergeNode'
}, {
tagName: 'feMergeNode',
in: 'SourceGraphic'
}]
}]
},
style: {
tagName: 'style',
textContent: '.highcharts-tooltip{' +
'filter:url(#drop-shadow)' +
'}'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
plotOptions: {},
labels: {
//items: [],
style: {
//font: defaultFont,
position: 'absolute',
color: '#333333'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function() {
return this.name;
},
//borderWidth: 0,
borderColor: '#999999',
borderRadius: 0,
navigation: {
// animation: true,
// arrowSize: 12
// style: {} // text styles
},
// margin: 20,
// reversed: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemCheckboxStyle: {
position: 'absolute',
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
squareSymbol: true,
// symbolRadius: 0,
// symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null
}
},
loading: {
// hideDuration: 100,
// showDuration: 0
},
tooltip: {
enabled: true,
animation: svg,
//crosshairs: null,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
footerFormat: '',
//formatter: defaultFormatter,
/* todo: em font-size when finished comparing against HC4
headerFormat: '<span style="font-size: 0.85em">{point.key}</span><br/>',
*/
padding: 8,
//shape: 'callout',
//shared: false,
snap: isTouchDevice ? 25 : 10,
headerFormat: '<span class="highcharts-header">{point.key}</span><br/>',
pointFormat: '<span class="highcharts-color-{point.colorIndex}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
text: 'Highcharts.com'
}
};
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var globalOptions = H.defaultOptions.global,
Date,
useUTC = globalOptions.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
H.Date = Date = globalOptions.Date || win.Date; // Allow using a different Date class
Date.hcTimezoneOffset = useUTC && globalOptions.timezoneOffset;
Date.hcGetTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
Date.hcMakeTime = function(year, month, date, hours, minutes, seconds) {
var d;
if (useUTC) {
d = Date.UTC.apply(0, arguments);
d += getTZOffset(d);
} else {
d = new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;
};
each(['Minutes', 'Hours', 'Day', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcGet' + s] = GET + s;
});
each(['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcSet' + s] = SET + s;
});
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
H.setOptions = function(options) {
// Copy in the default options
H.defaultOptions = merge(true, H.defaultOptions, options);
// Apply UTC
setTimeMethods();
return H.defaultOptions;
};
/**
* Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
* wasn't enough because the setOptions method created a new object.
*/
H.getOptions = function() {
return H.defaultOptions;
};
// Series defaults
H.defaultPlotOptions = H.defaultOptions.plotOptions;
// set the default time methods
setTimeMethods();
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var SVGElement,
SVGRenderer,
addEvent = H.addEvent,
animate = H.animate,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
createElement = H.createElement,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
doc = H.doc,
each = H.each,
extend = H.extend,
erase = H.erase,
grep = H.grep,
hasTouch = H.hasTouch,
isArray = H.isArray,
isFirefox = H.isFirefox,
isMS = H.isMS,
isObject = H.isObject,
isString = H.isString,
isWebKit = H.isWebKit,
merge = H.merge,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
splat = H.splat,
stop = H.stop,
svg = H.svg,
SVG_NS = H.SVG_NS,
symbolSizes = H.symbolSizes,
win = H.win;
/**
* A wrapper object for SVG elements
*/
SVGElement = H.SVGElement = function() {
return this;
};
SVGElement.prototype = {
// Default base for animation
opacity: 1,
SVG_NS: SVG_NS,
// For labels, these CSS properties are applied to the <text> node directly
textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'
],
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function(renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(wrapper.SVG_NS, nodeName);
wrapper.renderer = renderer;
},
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options Options include duration, easing, step and complete
* @param {Function} complete Function to perform at the end of animation
*/
animate: function(params, options, complete) {
var animOptions = pick(options, this.renderer.globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params, null, complete);
}
return this;
},
/**
* Build an SVG gradient out of a common JavaScript configuration object
*/
colorGradient: function(color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
radAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [],
value;
// Apply linear or radial gradients
if (color.linearGradient) {
gradName = 'linearGradient';
} else if (color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
radAttr = gradAttr; // Save the radial attributes for updating
gradAttr = merge(gradAttr,
renderer.getRadialAttr(radialReference, radAttr), {
gradientUnits: 'userSpaceOnUse'
}
);
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = 'highcharts-' + H.idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
gradientObject.radAttr = radAttr;
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function(stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
value = 'url(' + renderer.url + '#' + id + ')';
elem.setAttribute(prop, value);
elem.gradient = key;
// Allow the color to be concatenated into tooltips formatters etc. (#2995)
color.toString = function() {
return value;
};
}
},
/**
* Apply a polyfill to the text-stroke CSS property, by copying the text element
* and apply strokes to the copy.
*
* Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/
*/
applyTextShadow: function(textShadow) {
var elem = this.element,
tspans,
hasContrast = textShadow.indexOf('contrast') !== -1,
styles = {},
forExport = this.renderer.forExport,
// IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
// this again with new IE release. In exports, the rendering is passed to PhantomJS.
supports = this.renderer.forExport || (elem.style.textShadow !== undefined && !isMS);
// When the text shadow is set to contrast, use dark stroke for light text and vice versa
if (hasContrast) {
styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
}
// Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this,
// it removes the text shadows.
if (isWebKit || forExport) {
styles.textRendering = 'geometricPrecision';
}
/* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
if (elem.textContent.indexOf('2.') === 0) {
elem.style['text-shadow'] = 'none';
supports = false;
}
// */
// No reason to polyfill, we've got native support
if (supports) {
this.css(styles); // Apply altered textShadow or textRendering workaround
} else {
this.fakeTS = true; // Fake text shadow
// In order to get the right y position of the clones,
// copy over the y setter
this.ySetter = this.xSetter;
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
each(textShadow.split(/\s?,\s?/g), function(textShadow) {
var firstChild = elem.firstChild,
color,
strokeWidth;
textShadow = textShadow.split(' ');
color = textShadow[textShadow.length - 1];
// Approximately tune the settings to the text-shadow behaviour
strokeWidth = textShadow[textShadow.length - 2];
if (strokeWidth) {
each(tspans, function(tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply shadow properties
clone = tspan.cloneNode(1);
attr(clone, {
'class': 'highcharts-text-shadow',
'fill': color,
'stroke': color,
'stroke-opacity': 1 / Math.max(pInt(strokeWidth), 3),
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstChild);
});
}
});
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function(hash, val, complete) {
var key,
value,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr,
setter;
// single key-value pair
if (typeof hash === 'string' && val !== undefined) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = this[key + 'Setter'] || this._defaultSetter;
setter.call(this, value, key, element);
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
// In accordance with animate, run a complete callback
if (complete) {
complete();
}
return ret;
},
/**
* Add a class name to an element
*/
addClass: function(className, replace) {
var currentClassName = this.attr('class') || '';
if (currentClassName.indexOf(className) === -1) {
if (!replace) {
className = (currentClassName + (currentClassName ? ' ' : '') + className).replace(' ', ' ');
}
this.attr('class', className);
}
return this;
},
hasClass: function(className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function(className) {
attr(this.element, 'class', (attr(this.element, 'class') || '').replace(className, ''));
return this;
},
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function(hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function(key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function(clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : 'none');
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function(rect, strokeWidth) {
var wrapper = this,
key,
attribs = {},
normalizer;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
normalizer = Math.round(strokeWidth) % 2 / 2; // Math.round because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor((rect.width || wrapper.width || 0) - 2 * normalizer);
rect.height = Math.floor((rect.height || wrapper.height || 0) - 2 * normalizer);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
for (key in rect) {
if (wrapper[key] !== rect[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = rect[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function(styles) {
var elemWrapper = this,
oldStyles = elemWrapper.styles,
newStyles = {},
elem = elemWrapper.element,
textWidth,
n,
serializedCss = '',
hyphenate,
hasNew = !oldStyles;
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
for (n in styles) {
if (styles[n] !== oldStyles[n]) {
newStyles[n] = styles[n];
hasNew = true;
}
}
}
if (hasNew) {
textWidth = elemWrapper.textWidth =
(styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
elemWrapper.textWidth; // #3501
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// store object
elemWrapper.styles = styles;
if (textWidth && (!svg && elemWrapper.renderer.forExport)) {
delete styles.width;
}
// serialize and set style attribute
if (isMS && !svg) {
css(elemWrapper.element, styles);
} else {
hyphenate = function(a, b) {
return '-' + b.toLowerCase();
};
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// Rebuild text after added
if (elemWrapper.added && textWidth) {
elemWrapper.renderer.buildText(elemWrapper);
}
}
return elemWrapper;
},
/**
* Get a computed style
*/
getStyle: function(prop) {
return win.getComputedStyle(this.element || this, '').getPropertyValue(prop);
},
/**
* Get a computed style in pixel values
*/
strokeWidth: function() {
var val = this.getStyle('stroke-width'),
ret,
dummy;
// Read pixel values directly
if (val.indexOf('px') === val.length - 2) {
ret = pInt(val);
// Other values like em, pt etc need to be measured
} else {
dummy = doc.createElementNS(SVG_NS, 'rect');
attr(dummy, {
'width': val,
'stroke-width': 0
});
this.element.parentNode.appendChild(dummy);
ret = dummy.getBBox().width;
dummy.parentNode.removeChild(dummy);
}
return ret;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function(eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function(e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function(e) {
if (win.navigator.userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function(coordinates) {
var existingGradient = this.renderer.gradients[this.element.gradient];
this.element.radialReference = coordinates;
// On redrawing objects with an existing gradient, the gradient needs
// to be repositioned (#3801)
if (existingGradient && existingGradient.radAttr) {
existingGradient.animate(
this.renderer.getRadialAttr(
coordinates,
existingGradient.radAttr
)
);
}
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function(x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function(inverted) {
var wrapper = this;
wrapper.inverted = inverted;
wrapper.updateTransform();
return wrapper;
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function() {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
element = wrapper.element,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
// Delete bBox memo when the rotation changes
//delete wrapper.bBox;
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function() {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function(alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects,
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += (box.width - (alignOptions.width || 0)) / alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += (box.height - (alignOptions.height || 0)) / vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function(reload, rot) {
var wrapper = this,
bBox, // = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation,
rad,
element = wrapper.element,
styles = wrapper.styles,
fontSize,
textStr = wrapper.textStr,
textShadow,
elemStyle = element.style,
toggleTextShadowShim,
cache = renderer.cache,
cacheKeys = renderer.cacheKeys,
cacheKey;
rotation = pick(rot, wrapper.rotation);
rad = rotation * deg2rad;
fontSize = element && SVGElement.prototype.getStyle.call(element, 'font-size');
if (textStr !== undefined) {
cacheKey =
// Since numbers are monospaced, and numerical labels appear a lot in a chart,
// we assume that a label of n characters has the same bounding box as others
// of the same length.
textStr.toString().replace(/[0-9]/g, '0') +
// Properties that affect bounding box
['', rotation || 0, fontSize, element.style.width].join(',');
}
if (cacheKey && !reload) {
bBox = cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (element.namespaceURI === wrapper.SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
// When the text shadow shim is used, we need to hide the fake shadows
// to get the correct bounding box (#3872)
toggleTextShadowShim = this.fakeTS && function(display) {
each(element.querySelectorAll('.highcharts-text-shadow'), function(tspan) {
tspan.style.display = display;
});
};
// Workaround for #3842, Firefox reporting wrong bounding box for shadows
if (isFirefox && elemStyle.textShadow) {
textShadow = elemStyle.textShadow;
elemStyle.textShadow = '';
} else if (toggleTextShadowShim) {
toggleTextShadowShim('none');
}
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
// #3842
if (textShadow) {
elemStyle.textShadow = textShadow;
} else if (toggleTextShadowShim) {
toggleTextShadowShim('');
}
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = {
width: 0,
height: 0
};
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad));
}
}
// Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the
// bounding box height is 0, so don't cache it (#5620).
if (cacheKey && bBox.height > 0) {
// Rotate (#4681)
while (cacheKeys.length > 250) {
delete cache[cacheKeys.shift()];
}
if (!cache[cacheKey]) {
cacheKeys.push(cacheKey);
}
cache[cacheKey] = bBox;
}
}
return bBox;
},
/**
* Show the element
*/
show: function(inherit) {
return this.attr({
visibility: inherit ? 'inherit' : 'visible'
});
},
/**
* Hide the element
*/
hide: function() {
return this.attr({
visibility: 'hidden'
});
},
fadeOut: function(duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function() {
elemWrapper.attr({
y: -9999
}); // #3088, assuming we're only using this for tooltips
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function(parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function(element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function() {
var wrapper = this,
element = wrapper.element || {},
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
xGetter: function(key) {
if (this.element.nodeName === 'circle') {
if (key === 'x') {
key = 'cx';
} else if (key === 'y') {
key = 'cy';
}
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute, used mainly
* for animation.
*/
_defaultGetter: function(key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
dSetter: function(value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
element.setAttribute(key, value);
this[key] = value;
},
alignSetter: function(value) {
var convert = {
left: 'start',
center: 'middle',
right: 'end'
};
this.element.setAttribute('text-anchor', convert[value]);
},
opacitySetter: function(value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
titleSetter: function(value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(this.SVG_NS, 'title');
this.element.appendChild(titleNode);
}
// Remove text content if it exists
if (titleNode.firstChild) {
titleNode.removeChild(titleNode.firstChild);
}
titleNode.appendChild(
doc.createTextNode(
(String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895
)
);
},
textSetter: function(value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
fillSetter: function(value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.colorGradient(value, key, element);
}
},
visibilitySetter: function(value, key, element) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909)
if (value === 'inherit') {
element.removeAttribute(key);
} else {
element.setAttribute(key, value);
}
},
zIndexSetter: function(value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
run = this.added,
i;
if (defined(value)) {
element.zIndex = value; // So we can read it for other elements in the group
value = +value;
if (this[key] === value) { // Only update when needed (#3865)
run = false;
}
this[key] = value;
}
// Insert according to this and other elements' zIndex. Before .add() is called,
// nothing is done. Then on add, or by later calls to zIndexSetter, the node
// is placed on the right place in the DOM.
if (run) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length && !inserted; i++) {
otherElement = childNodes[i];
otherZIndex = otherElement.zIndex;
if (otherElement !== element && (
// Insert before the first element with a higher zIndex
pInt(otherZIndex) > value ||
// If no zIndex given, insert before the first element with a zIndex
(!defined(value) && defined(otherZIndex)) ||
// Negative zIndex versus no zIndex:
// On all levels except the highest. If the parent is <svg>,
// then we don't want to put items before <desc> or <defs>
(value < 0 && !defined(otherZIndex) && parentNode !== renderer.box)
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
}
}
if (!inserted) {
parentNode.appendChild(element);
}
}
return inserted;
},
_defaultSetter: function(value, key, element) {
element.setAttribute(key, value);
}
};
// Some shared setters and getters
SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function(value, key) {
this[key] = value;
this.doTransform = true;
};
/**
* The default SVG renderer
*/
SVGRenderer = H.SVGRenderer = function() {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
SVG_NS: SVG_NS,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function(container, width, height, style, forExport, allowHTML) {
var renderer = this,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
'version': '1.1',
'class': 'highcharts-root'
});
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', this.SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
win.location.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with Highmaps 5.0.1'));
renderer.defs = this.createElement('defs').add();
renderer.allowHTML = allowHTML;
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function() {
css(container, {
left: 0,
top: 0
});
rect = container.getBoundingClientRect();
css(container, {
left: (Math.ceil(rect.left) - rect.left) + 'px',
top: (Math.ceil(rect.top) - rect.top) + 'px'
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
/**
* General method for adding a definition. Can be used for gradients, fills, filters etc.
*
* @return SVGElement The inserted node
*/
definition: function(def) {
var ren = this;
function recurse(config, parent) {
var ret;
each(splat(config), function(item) {
var node = ren.createElement(item.tagName),
key,
attr = {};
// Set attributes
for (key in item) {
if (key !== 'tagName' && key !== 'children' && key !== 'textContent') {
attr[key] = item[key];
}
}
node.attr(attr);
// Add to the tree
node.add(parent || ren.defs);
// Add text content
if (item.textContent) {
node.element.appendChild(doc.createTextNode(item.textContent));
}
// Recurse
recurse(item.children || [], node);
ret = node;
});
// Return last node added (on top level it's the only one)
return ret;
}
return recurse(def);
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function() {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function() {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function(nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for plugins
*/
draw: noop,
/**
* Get converted radial gradient attributes
*/
getRadialAttr: function(radialReference, gradAttr) {
return {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2]
};
},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function(wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
clsRegex,
styleRegex,
hrefRegex,
wasTooLong,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textShadow = textStyles && textStyles.textShadow,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function(tspan) {
var fontSizeStyle;
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
fontSizeStyle,
tspan
).h;
},
unescapeAngleBrackets = function(inputStr) {
return inputStr.replace(/</g, '<').replace(/>/g, '>');
};
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) {
textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
// Complex strings, add more logic
} else {
clsRegex = /<.*class="([^"]+)".*>/;
styleRegex = /<.*style="([^"]+)".*>/;
hrefRegex = /<.*href="(http[^"]+)".*>/;
if (tempParent) {
tempParent.appendChild(textNode); // attach it to the DOM to read offset width
}
if (hasMarkup) {
lines = textStr
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// Trim empty lines (#5261)
lines = grep(lines, function(line) {
return line !== '';
});
// build the lines
each(lines, function buildTextLines(line, lineNo) {
var spans,
spanNo = 0;
line = line
.replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258)
.replace(/<span/g, '|||<span')
.replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function buildTextSpans(span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(renderer.SVG_NS, 'tspan'),
spanCls,
spanStyle; // #390
if (clsRegex.test(span)) {
spanCls = span.match(clsRegex)[1];
attr(tspan, 'class', spanCls);
}
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, {
cursor: 'pointer'
});
}
span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!svg && forExport) {
css(tspan, {
display: 'block'
});
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
/*if (width) {
renderer.breakText(wrapper, width);
}*/
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
noWrap = textStyles.whiteSpace === 'nowrap',
hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap),
tooLong,
actualWidth,
rest = [],
dy = getLineHeight(tspan),
rotation = wrapper.rotation,
wordStr = span, // for ellipsis
cursor = wordStr.length, // binary search cursor
bBox;
while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
wrapper.rotation = 0; // discard rotation when computing box
bBox = wrapper.getBBox(true);
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!svg && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
// For ellipsis, do a binary search for the correct string length
if (wasTooLong === undefined) {
wasTooLong = tooLong; // First time
}
if (ellipsis && wasTooLong) {
cursor /= 2;
if (wordStr === '' || (!tooLong && cursor < 0.5)) {
words = []; // All ok, break out
} else {
wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * Math.ceil(cursor));
words = [wordStr + (width > 3 ? '\u2026' : '')];
tspan.removeChild(tspan.firstChild);
}
// Looping down, this is the first word sequence that is not too long,
// so we can move on to build the next line.
} else if (!tooLong || words.length === 1) {
words = rest;
rest = [];
if (words.length && !noWrap) {
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
}
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
wrapper.rotation = rotation;
}
spanNo++;
}
}
});
});
if (wasTooLong) {
wrapper.attr('title', wrapper.textStr);
}
if (tempParent) {
tempParent.removeChild(textNode); // attach it to the DOM to read offset width
}
// Apply the text shadow
if (textShadow && wrapper.applyTextShadow) {
wrapper.applyTextShadow(textShadow);
}
}
},
/*
breakText: function (wrapper, width) {
var bBox = wrapper.getBBox(),
node = wrapper.element,
textLength = node.textContent.length,
pos = Math.round(width * textLength / bBox.width), // try this position first, based on average character width
increment = 0,
finalPos;
if (bBox.width > width) {
while (finalPos === undefined) {
textLength = node.getSubStringLength(0, pos);
if (textLength <= width) {
if (increment === -1) {
finalPos = pos;
} else {
increment = 1;
}
} else {
if (increment === 1) {
finalPos = pos - 1;
} else {
increment = -1;
}
}
pos += increment;
}
}
console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos))
},
*/
/**
* Returns white for dark colors and black for bright colors
*/
getContrast: function(rgba) {
rgba = color(rgba).rgba;
return rgba[0] + rgba[1] + rgba[2] > 2 * 255 ? '#000000' : '#FFFFFF';
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function(text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0;
// Default, non-stylable attributes
label.attr(merge({
'padding': 8,
'r': 2
}, normalState));
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function() {
if (curState !== 3) {
label.setState(1);
}
});
addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function() {
if (curState !== 3) {
label.setState(curState);
}
});
label.setState = function(state) {
// Hover state is temporary, don't record it
if (state !== 1) {
label.state = curState = state;
}
// Update visuals
label.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/)
.addClass('highcharts-button-' + ['normal', 'hover', 'pressed', 'disabled'][state || 0]);
};
return label
.on('click', function(e) {
if (curState !== 3) {
callback.call(label, e);
}
});
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function(points, width) {
// points format: ['M', 0, 0, 'L', 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function(path) {
var attribs = {
};
if (isArray(path)) {
attribs.d = path;
} else if (isObject(path)) { // attributes
extend(attribs, path);
}
return this.createElement('path').attr(attribs);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function(x, y, r) {
var attribs = isObject(x) ? x : {
x: x,
y: y,
r: r
},
wrapper = this.createElement('circle');
// Setting x or y translates to cx and cy
wrapper.xSetter = wrapper.ySetter = function(value, key, element) {
element.setAttribute('c' + key, value);
};
return wrapper.attr(attribs);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function(x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function(x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === undefined ? {} : {
x: x,
y: y,
width: Math.max(width, 0),
height: Math.max(height, 0)
};
if (r) {
attribs.r = r;
}
wrapper.rSetter = function(value, key, element) {
attr(element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function(width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper.animate({
width: width,
height: height
}, {
step: function() {
this.attr({
viewBox: '0 0 ' + this.attr('width') + ' ' + this.attr('height')
});
},
duration: pick(animate, true) ? undefined : 0
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function(name) {
var elem = this.createElement('g');
return name ? elem.attr({
'class': 'highcharts-' + name
}) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function(src, x, y, width, height) {
var attribs = {
preserveAspectRatio: 'none'
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function(symbol, x, y, width, height, options) {
var ren = this,
obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = defined(x) && symbolFn && symbolFn(
Math.round(x),
Math.round(y),
width,
height,
options
),
imageRegex = /^url\((.*?)\)$/,
imageSrc,
centerImage;
if (symbolFn) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
imageSrc = symbol.match(imageRegex)[1];
// Create the image synchronously, add attribs async
obj = this.image(imageSrc);
// The image width is not always the same as the symbol width. The
// image may be centered within the symbol, as is the case when
// image shapes are used as label backgrounds, for example in flags.
obj.imgwidth = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].width,
options && options.width
);
obj.imgheight = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].height,
options && options.height
);
/**
* Set the size and position
*/
centerImage = function() {
obj.attr({
width: obj.width,
height: obj.height
});
};
/**
* Width and height setters that take both the image's physical size
* and the label size into consideration, and translates the image
* to center within the label.
*/
each(['width', 'height'], function(key) {
obj[key + 'Setter'] = function(value, key) {
var attribs = {},
imgSize = this['img' + key],
trans = key === 'width' ? 'translateX' : 'translateY';
this[key] = value;
if (defined(imgSize)) {
if (this.element) {
this.element.setAttribute(key, imgSize);
}
if (!this.alignByTranslate) {
attribs[trans] = ((this[key] || 0) - imgSize) / 2;
this.attr(attribs);
}
}
};
});
if (defined(x)) {
obj.attr({
x: x,
y: y
});
}
obj.isImg = true;
if (defined(obj.imgwidth) && defined(obj.imgheight)) {
centerImage();
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
obj.attr({
width: 0,
height: 0
});
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
createElement('img', {
onload: function() {
var chart = charts[ren.chartIndex];
// Special case for SVGs on IE11, the width is not accessible until the image is
// part of the DOM (#2854).
if (this.width === 0) {
css(this, {
position: 'absolute',
top: '-999em'
});
doc.body.appendChild(this);
}
// Center the image
symbolSizes[imageSrc] = { // Cache for next
width: this.width,
height: this.height
};
obj.imgwidth = this.width;
obj.imgheight = this.height;
if (obj.element) {
centerImage();
}
// Clean up after #2854 workaround.
if (this.parentNode) {
this.parentNode.removeChild(this);
}
// Fire the load event when all external images are loaded
ren.imgCount--;
if (!ren.imgCount && chart && chart.onload) {
chart.onload();
}
},
src: imageSrc
});
this.imgCount++;
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function(x, y, w, h) {
var cpw = 0.166 * w;
return [
'M', x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function(x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
longArc = options.end - start < Math.PI ? 0 : 1;
return [
'M',
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? 'M' : 'L',
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
},
/**
* Callout shape used for default tooltips, also used for rounded rectangles in VML
*/
callout: function(x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = Math.min((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function(x, y, width, height) {
var wrapper,
id = 'highcharts-' + H.idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function(str, x, y, useHTML) {
// declare variables
var renderer = this,
fakeSVG = !svg && renderer.forExport,
wrapper,
attribs = {};
if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
return renderer.html(str, x, y);
}
attribs.x = Math.round(x || 0); // X is always needed for line-wrap logic
if (y) {
attribs.y = Math.round(y);
}
if (str || str === 0) {
attribs.text = str;
}
wrapper = renderer.createElement('text')
.attr(attribs);
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: 'absolute'
});
}
if (!useHTML) {
wrapper.xSetter = function(value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function(fontSize, elem) { // eslint-disable-line no-unused-vars
var lineHeight,
baseline;
fontSize = elem && SVGElement.prototype.getStyle.call(elem, 'font-size');
fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2);
baseline = Math.round(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764)
*/
rotCorr: function(baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = Math.max(y * Math.cos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * Math.sin(rotation * deg2rad),
y: y
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function(str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className !== 'button' && 'label'),
text = wrapper.text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
textAlign,
deferredAttr = {},
strokeWidth,
baselineOffset,
hasBGImage = /^url\((.*?)\)$/.test(shape),
needsBox = hasBGImage,
getCrispAdjust,
updateBoxSize,
updateTextPadding,
boxAttr;
if (className) {
wrapper.addClass('highcharts-' + className);
}
needsBox = true; // for styling
getCrispAdjust = function() {
return box.strokeWidth() % 2 / 2;
};
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
updateBoxSize = function() {
var style = text.element.style,
crispAdjust,
attribs = {};
bBox = (width === undefined || height === undefined || textAlign) && defined(text.textStr) &&
text.getBBox(); //#3295 && 3514 box failure when string equals 0
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// Update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
if (needsBox) {
// Create the border box if it is not already present
if (!box) {
wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324)
renderer.symbol(shape) :
renderer.rect();
box.addClass(
(className === 'button' ? '' : 'highcharts-label-box') + // Don't use label className for buttons
(className ? ' highcharts-' + className + '-box' : '')
);
box.add(wrapper);
crispAdjust = getCrispAdjust();
attribs.x = crispAdjust;
attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust;
}
// Apply the box attributes
attribs.width = Math.round(wrapper.width);
attribs.height = Math.round(wrapper.height);
box.attr(extend(attribs, deferredAttr));
deferredAttr = {};
}
};
/**
* This function runs after setting text or padding, but only if padding is changed
*/
updateTextPadding = function() {
var textX = paddingLeft + padding,
textY;
// determin y based on the baseline
textY = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
textX += {
center: 0.5,
right: 1
}[textAlign] * (width - bBox.width);
}
// update if anything changed
if (textX !== text.x || textY !== text.y) {
text.attr('x', textX);
if (textY !== undefined) {
text.attr('y', textY);
}
}
// record current values
text.x = textX;
text.y = textY;
};
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
boxAttr = function(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
};
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
wrapper.onAdd = function() {
text.add(wrapper);
wrapper.attr({
text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function(value) {
width = value;
};
wrapper.heightSetter = function(value) {
height = value;
};
wrapper['text-alignSetter'] = function(value) {
textAlign = value;
};
wrapper.paddingSetter = function(value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function(value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function(value) {
value = {
left: 0,
center: 0.5,
right: 1
}[value];
if (value !== alignFactor) {
alignFactor = value;
if (bBox) { // Bounding box exists, means we're dynamically changing
wrapper.attr({
x: wrapperX
}); // #5134
}
}
};
// apply these to the box and the text alike
wrapper.textSetter = function(value) {
if (value !== undefined) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function(value, key) {
if (value) {
needsBox = true;
}
strokeWidth = this['stroke-width'] = value;
boxAttr(key, value);
};
wrapper.rSetter = function(value, key) {
boxAttr(key, value);
};
wrapper.anchorXSetter = function(value, key) {
anchorX = value;
boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX);
};
wrapper.anchorYSetter = function(value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function(value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + 2 * padding);
}
wrapperX = Math.round(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function(value) {
wrapperY = wrapper.y = Math.round(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function(styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(wrapper.textProps, function(prop) {
if (styles[prop] !== undefined) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function() {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Destroy and release memory.
*/
destroy: function() {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
}
});
}
}; // end SVGRenderer
// general renderer
H.Renderer = SVGRenderer;
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var attr = H.attr,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
isMS = H.isMS,
isWebKit = H.isWebKit,
pInt = H.pInt,
SVGElement = H.SVGElement,
SVGRenderer = H.SVGRenderer,
win = H.win,
wrap = H.wrap;
// extend SvgElement for useHTML option
extend(SVGElement.prototype, {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function(styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function() {
var wrapper = this,
element = wrapper.element;
// faking getBBox in exported SVG in legacy IE
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = 'absolute';
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function() {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = {
left: 0,
center: 0.5,
right: 1
}[align],
styles = wrapper.styles;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function(child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var rotation = wrapper.rotation,
baseline,
textWidth = pInt(wrapper.textWidth),
whiteSpace = styles && styles.whiteSpace,
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
baseline = renderer.fontMetrics(elem.style.fontSize).b;
// Renderer specific handling of span rotation
if (defined(rotation)) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
// Reset multiline/ellipsis in order to read width (#4928, #5417)
css(elem, {
width: '',
whiteSpace: whiteSpace || 'nowrap'
});
// Update textWidth
if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + 'px',
display: 'block',
whiteSpace: whiteSpace || 'normal' // #3331
});
}
wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + 'px',
top: (y + (wrapper.yCorr || 0)) + 'px'
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
baseline = elem.offsetHeight; // assigned to baseline for lint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function(rotation, alignCorrection, baseline) {
var rotationStyle = {},
cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : win.opera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*/
getSpanCorrection: function(width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, {
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function(str, x, y) {
var wrapper = this.createElement('span'),
element = wrapper.element,
renderer = wrapper.renderer,
isSVG = renderer.isSVG,
addSetters = function(element, style) {
// These properties are set as attributes on the SVG group, and as
// identical CSS properties on the div. (#3542)
each(['opacity', 'visibility'], function(prop) {
wrap(element, prop + 'Setter', function(proceed, value, key, elem) {
proceed.call(this, value, key, elem);
style[key] = value;
});
});
};
// Text setter
wrapper.textSetter = function(value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = this.textStr = value;
wrapper.htmlUpdateTransform();
};
// Add setters for the element itself (#4938)
if (isSVG) { // #4938, only for HTML within SVG
addSetters(wrapper, wrapper.element.style);
}
// Various setters which rely on update transform
wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function(value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
};
// Set the default attributes
wrapper
.attr({
text: str,
x: Math.round(x),
y: Math.round(y)
})
.css({
position: 'absolute'
});
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (isSVG) {
wrapper.add = function(svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function(parentGroup) {
var htmlGroupStyle,
cls = attr(parentGroup.element, 'class');
if (cls) {
cls = {
className: cls
};
} // else null
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement('div', cls, {
position: 'absolute',
left: (parentGroup.translateX || 0) + 'px',
top: (parentGroup.translateY || 0) + 'px',
display: parentGroup.display,
opacity: parentGroup.opacity, // #5075
pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup, {
translateXSetter: function(value, key) {
htmlGroupStyle.left = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
},
translateYSetter: function(value, key) {
htmlGroupStyle.top = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
}
});
addSetters(parentGroup, htmlGroupStyle);
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var correctFloat = H.correctFloat,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
isNumber = H.isNumber,
merge = H.merge,
pick = H.pick,
stop = H.stop,
deg2rad = H.deg2rad;
/**
* The Tick class
*/
H.Tick = function(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
};
H.Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function() {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat =
options.dateTimeLabelFormats[
tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName
];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(axis.lin2log(value)) : value
});
// prepare CSS
//css = width && { width: Math.max(1, Math.round(width - 2 * (labelOptions.padding || 10))) + 'px' };
// first call
if (!defined(label)) {
tick.label = label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
.add(axis.labelGroup):
null;
tick.labelLength = label && label.getBBox().width; // Un-rotated length
tick.rotation = 0; // Base value to detect change for new calls to getBBox
// update
} else if (label) {
label.attr({
text: str
});
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function() {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function(xy) {
var axis = this.axis,
pxPos = xy.x,
chartWidth = axis.chart.chartWidth,
spacing = axis.chart.spacing,
leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])),
rightBound = pick(axis.labelRight, Math.max(axis.pos + axis.len, chartWidth - spacing[1])),
label = this.label,
rotation = this.rotation,
factor = {
left: 0,
center: 0.5,
right: 1
}[axis.labelAlign],
labelWidth = label.getBBox().width,
slotWidth = axis.getSlotWidth(),
modifiedSlotWidth = slotWidth,
xCorrection = factor,
goRight = 1,
leftPos,
rightPos,
textWidth,
css = {};
// Check if the label overshoots the chart spacing box. If it does, move it.
// If it now overshoots the slotWidth, add ellipsis.
if (!rotation) {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + (1 - factor) * labelWidth;
if (leftPos < leftBound) {
modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
} else if (rightPos > rightBound) {
modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor;
goRight = -1;
}
modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177
if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection *
(slotWidth - Math.min(labelWidth, modifiedSlotWidth)));
}
// If the label width exceeds the available space, set a text width to be
// picked up below. Also, if a width has been set before, we need to set a new
// one because the reported labelWidth will be limited by the box (#3938).
if (labelWidth > modifiedSlotWidth || (axis.autoRotation && (label.styles || {}).width)) {
textWidth = modifiedSlotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
} else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound);
} else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
textWidth = Math.round((chartWidth - pxPos) / Math.cos(rotation * deg2rad));
}
if (textWidth) {
css.width = textWidth;
if (!(axis.options.labels.style || {}).textOverflow) {
css.textOverflow = 'ellipsis';
}
label.css(css);
}
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function(horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset +
(axis.opposite ?
((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left :
0
),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function(x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
rotCorr = axis.tickRotCorr || {
x: 0,
y: 0
},
yOffset = labelOptions.y,
line;
if (!defined(yOffset)) {
if (axis.side === 0) {
yOffset = label.rotation ? -8 : -label.getBBox().height;
} else if (axis.side === 2) {
yOffset = rotCorr.y + 8;
} else {
// #3140, #3140
yOffset = Math.cos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2);
}
}
x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
if (axis.opposite) {
line = staggerLines - line - 1;
}
y += line * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: Math.round(y)
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function(x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
'M',
x,
y,
'L',
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function(index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
tickPrefix = type ? type + 'Tick' : 'tick',
tickSize = axis.tickSize(tickPrefix),
gridLinePath,
mark = tick.mark,
isNewMark = !mark,
step = labelOptions.step,
attribs = {},
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) ||
(!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// Create the grid line
if (!gridLine) {
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine = renderer.path()
.attr(attribs)
.addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line')
.add(axis.gridGroup);
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLine.strokeWidth() * reverseCrisp, old, true);
if (gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickSize) {
// negate the length
if (axis.opposite) {
tickSize[0] = -tickSize[0];
}
// First time, create it
if (isNewMark) {
tick.mark = mark = renderer.path()
.addClass('highcharts-' + (type ? type + '-' : '') + 'tick')
.add(axis.axisGroup);
}
mark[isNewMark ? 'attr' : 'animate']({
d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, horiz, renderer),
opacity: opacity
});
}
// the label is created on init - now move it into place
if (label && isNumber(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (horiz && !axis.isRadial && !labelOptions.step &&
!labelOptions.rotation && !old && opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && isNumber(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
} else {
stop(label); // #5332
label.attr('y', -9999); // #1338
}
tick.isNew = false;
}
},
/**
* Destructor for the tick prototype
*/
destroy: function() {
destroyObjectProperties(this, this.axis);
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
erase = H.erase,
merge = H.merge,
pick = H.pick;
/*
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
H.PlotLineOrBand = function(axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
};
H.PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function() {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
to = options.to,
from = options.from,
value = options.value,
isBand = defined(from) && defined(to),
isLine = defined(value),
svgElem = plotLine.svgElem,
isNew = !svgElem,
path = [],
addEvent,
eventType,
color = options.color,
zIndex = pick(options.zIndex, 0),
events = options.events,
attribs = {
'class': 'highcharts-plot-' + (isBand ? 'band ' : 'line ') + (options.className || '')
},
groupAttribs = {},
renderer = axis.chart.renderer,
groupName = isBand ? 'bands' : 'lines',
group,
log2lin = axis.log2lin;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// Grouping and zIndex
groupAttribs.zIndex = zIndex;
groupName += '-' + zIndex;
group = axis[groupName];
if (!group) {
axis[groupName] = group = renderer.g('plot-' + groupName)
.attr(groupAttribs).add();
}
// Create the path
if (isNew) {
plotLine.svgElem = svgElem =
renderer
.path()
.attr(attribs).add(group);
}
// Set the path or return
if (isLine) {
path = axis.getPlotLinePath(value, svgElem.strokeWidth());
} else if (isBand) { // plot band
path = axis.getPlotBandPath(from, to, options);
} else {
return;
}
// common for lines and bands
if (isNew && path && path.length) {
svgElem.attr({
d: path
});
// events
if (events) {
addEvent = function(eventType) {
svgElem.on(eventType, function(e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
} else if (svgElem) {
if (path) {
svgElem.show();
svgElem.animate({
d: path
});
} else {
svgElem.hide();
if (label) {
plotLine.label = label = label.destroy();
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length &&
axis.width > 0 && axis.height > 0 && !path.flat) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign: !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
this.renderLabel(optionsLabel, path, isBand, zIndex);
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Render and align label for plot line or band.
*/
renderLabel: function(optionsLabel, path, isBand, zIndex) {
var plotLine = this,
label = plotLine.label,
renderer = plotLine.axis.chart.renderer,
attribs,
xs,
ys,
x,
y;
// add the SVG element
if (!label) {
attribs = {
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation,
'class': 'highcharts-plot-' + (isBand ? 'band' : 'line') + '-label ' + (optionsLabel.className || '')
};
attribs.zIndex = zIndex;
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr(attribs)
.add();
}
// get the bounding box and align the label
// #3000 changed to better handle choice between plotband or plotline
xs = [path[1], path[4], (isBand ? path[6] : path[1])];
ys = [path[2], path[5], (isBand ? path[7] : path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
},
/**
* Remove the plot line or band
*/
destroy: function() {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* Object with members for extending the Axis prototype
* @todo Extend directly instead of adding object to Highcharts first
*/
H.AxisPlotLineOrBandExtension = {
/**
* Create the path for a plot band
*/
getPlotBandPath: function(from, to) {
var toPath = this.getPlotLinePath(to, null, null, true),
path = this.getPlotLinePath(from, null, null, true);
if (path && toPath) {
// Flat paths don't need labels (#3836)
path.flat = path.toString() === toPath.toString();
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
addPlotBand: function(options) {
return this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function(options) {
return this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function(options, coll) {
var obj = new H.PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function(id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function(arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
AxisPlotLineOrBandExtension = H.AxisPlotLineOrBandExtension,
color = H.color,
correctFloat = H.correctFloat,
defaultOptions = H.defaultOptions,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
format = H.format,
getMagnitude = H.getMagnitude,
grep = H.grep,
inArray = H.inArray,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
merge = H.merge,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick,
PlotLineOrBand = H.PlotLineOrBand,
removeEvent = H.removeEvent,
splat = H.splat,
syncTimeout = H.syncTimeout,
Tick = H.Tick;
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
H.Axis = function() {
this.init.apply(this, arguments);
};
H.Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
// reversed: false,
labels: {
enabled: true,
// rotation: 0,
// align: 'center',
// step: null,
x: 0
//y: undefined
/*formatter: function () {
return this.value;
},*/
},
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
//tickInterval: null,
tickLength: 10,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
//x: 0,
//y: 0
},
type: 'linear', // linear, logarithmic or datetime
//visible: true
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8
},
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function() {
return H.numberFormat(this.total, -1);
}
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -15
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 15
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for top axes
*/
defaultTopAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function(chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
axis.chart = chart;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis');
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = userOptions.side || (axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3)); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = undefined,// = options.title.margin,
axis.minPixelPadding = 0;
axis.reversed = options.reversed;
axis.visible = options.visible !== false;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.hasNames = type === 'category' || options.categories === true;
axis.categories = options.categories || axis.hasNames;
axis.names = axis.names || []; // Preserve on update (#3830)
// Elements
//axis.axisGroup = undefined;
//axis.gridGroup = undefined;
//axis.axisTitle = undefined;
//axis.axisLine = undefined;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = undefined;
// Tick positions
//axis.tickPositions = undefined; // array containing predefined positions
// Tick intervals
//axis.tickInterval = undefined;
//axis.minorTickInterval = undefined;
// Major ticks
axis.ticks = {};
axis.labelEdge = [];
// Minor ticks
axis.minorTicks = {};
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = undefined;
//axis.top = undefined;
//axis.width = undefined;
//axis.height = undefined;
//axis.bottom = undefined;
//axis.right = undefined;
//axis.transA = undefined;
//axis.transB = undefined;
//axis.oldTransA = undefined;
axis.len = 0;
//axis.oldMin = undefined;
//axis.oldMax = undefined;
//axis.oldUserMin = undefined;
//axis.oldUserMax = undefined;
//axis.oldAxisLength = undefined;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
axis.stacksTouched = 0;
// Min and max in the data
//axis.dataMin = undefined,
//axis.dataMax = undefined,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = undefined,
//axis.userMax = undefined,
// Crosshair options
axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
if (isXAxis) { // #2713
chart.axes.splice(chart.xAxis.length, 0, axis);
} else {
chart.axes.push(axis);
}
chart[axis.coll].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === undefined) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = axis.log2lin;
axis.lin2val = axis.lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function(userOptions) {
this.options = merge(
this.defaultOptions,
this.coll === 'yAxis' && this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions
][this.side],
merge(
defaultOptions[this.coll], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function() {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = H.dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === undefined) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480
ret = H.numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === undefined) {
if (Math.abs(value) >= 10000) { // add thousands separators
ret = H.numberFormat(value, -1);
} else { // small numbers
ret = H.numberFormat(value, -1, undefined, ''); // #2466
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function() {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// Reset properties in case we're redrawing (#3353)
axis.dataMin = axis.dataMax = axis.threshold = null;
axis.softThreshold = !axis.isXAxis;
if (axis.buildStacks) {
axis.buildStacks();
}
// loop through this axis' series
each(axis.series, function(series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
// If xData contains values which is not numbers, then filter them out.
// To prevent performance hit, we only do this after we have already
// found seriesDataMin because in most cases all data is valid. #5234.
seriesDataMin = arrayMin(xData);
if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010
xData = grep(xData, function(x) {
return isNumber(x);
});
seriesDataMin = arrayMin(xData); // Do it again with valid data
}
axis.dataMin = Math.min(pick(axis.dataMin, xData[0]), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = Math.min(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
axis.threshold = threshold;
}
// If any series has a hard threshold, it takes precedence
if (!seriesOptions.softThreshold || axis.isLog) {
axis.softThreshold = false;
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function(val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this.linkedParent || this, // #1417
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (doPostTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (doPostTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function(value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function(pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function(value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB,
/**
* Check if x is between a and b. If not, either move to a/b or skip,
* depending on the force parameter.
*/
between = function(x, a, b) {
if (x < a || x > b) {
if (force) {
x = Math.min(Math.max(a, x), b);
} else {
skip = true;
}
}
return x;
};
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = Math.round(translatedValue + transB);
y1 = y2 = Math.round(cHeight - translatedValue - transB);
if (!isNumber(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
y1 = y2 = between(y1, axisTop, axisTop + axis.height);
}
return skip && !force ?
null :
chart.renderer.crispLine(['M', x1, y1, 'L', x2, y2], lineWidth || 1);
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function(tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(Math.floor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(Math.ceil(max / tickInterval) * tickInterval),
tickPositions = [];
// For single points, add a tick regardless of the relative position (#2662)
if (min === max && isNumber(min)) {
return [min];
}
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function() {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
pointRangePadding = axis.pointRangePadding || 0,
min = axis.min - pointRangePadding, // #1498
max = axis.max + pointRangePadding, // #1498
range = max - min,
len;
// If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
if (range && range / minorTickInterval < axis.len / 3) { // #3875
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
min,
max,
options.startOfWeek
)
);
} else {
for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
}
if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks
axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498
}
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function() {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs,
minRange;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === undefined && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function(series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === undefined || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = Math.min(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Find the closestPointRange across all series
*/
getClosest: function() {
var ret;
if (this.categories) {
ret = 1;
} else {
each(this.series, function(series) {
var seriesClosest = series.closestPointRange;
if (!series.noSharedTooltip && defined(seriesClosest)) {
ret = defined(ret) ?
Math.min(ret, seriesClosest) :
seriesClosest;
}
});
}
return ret;
},
/**
* When a point name is given and no x, search for the name in the existing categories,
* or if categories aren't provided, search names or create a new category (#2522).
*/
nameToX: function(point) {
var explicitCategories = isArray(this.categories),
names = explicitCategories ? this.categories : this.names,
nameX = point.options.x,
x;
point.series.requireSorting = false;
if (!defined(nameX)) {
nameX = this.options.uniqueNames === false ?
point.series.autoIncrement() :
inArray(point.name, names);
}
if (nameX === -1) { // The name is not found in currenct categories
if (!explicitCategories) {
x = names.length;
}
} else {
x = nameX;
}
// Write the last point's name to the names array
this.names[x] = point.name;
return x;
},
/**
* When changes have been done to series data, update the axis.names.
*/
updateNames: function() {
var axis = this;
if (this.names.length > 0) {
this.names.length = 0;
this.minRange = undefined;
each(this.series || [], function(series) {
// When adding a series, points are not yet generated
if (!series.points || series.isDirtyData) {
series.processData();
series.generatePoints();
}
each(series.points, function(point, i) {
var x;
if (point.options && point.options.x === undefined) {
x = axis.nameToX(point);
if (x !== point.x) {
point.x = x;
series.xData[i] = x;
}
}
});
});
}
},
/**
* Update translation information
*/
setAxisTranslation: function(saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = axis.axisPointRange || 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
hasCategories = !!axis.categories,
transA = axis.transA,
isXAxis = axis.isXAxis;
// Adjust translation for padding. Y axis with categories need to go through the same (#1784).
if (isXAxis || hasCategories || pointRange) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
// Get the closest points
closestPointRange = axis.getClosest();
each(axis.series, function(series) {
var seriesPointRange = hasCategories ?
1 :
(isXAxis ?
pick(series.options.pointRange, closestPointRange, 0) :
(axis.axisPointRange || 0)), // #2806
pointPlacement = series.options.pointPlacement;
pointRange = Math.max(pointRange, seriesPointRange);
if (!axis.single) {
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = Math.max(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = Math.max(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = Math.min(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
if (isXAxis) {
axis.closestPointRange = closestPointRange;
}
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
minFromRange: function() {
return this.max - this.range;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickInterval: function(secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
log2lin = axis.log2lin,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
categories = axis.categories,
threshold = axis.threshold,
softThreshold = axis.softThreshold,
thresholdMin,
thresholdMax,
hardMin,
hardMax;
if (!isDatetimeAxis && !categories && !isLinked) {
this.getTickAmount();
}
// Min or max set either by zooming/setExtremes or initial options
hardMin = pick(axis.userMin, options.min);
hardMax = pick(axis.userMax, options.max);
// Linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[axis.coll][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
// Initial min and max from the extreme data values
} else {
// Adjust to hard threshold
if (!softThreshold && defined(threshold)) {
if (axis.dataMin >= threshold) {
thresholdMin = threshold;
minPadding = 0;
} else if (axis.dataMax <= threshold) {
thresholdMax = threshold;
maxPadding = 0;
}
}
axis.min = pick(hardMin, thresholdMin, axis.dataMin);
axis.max = pick(hardMax, thresholdMax, axis.dataMax);
}
if (isLog) {
if (!secondPass && Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
// The correctFloat cures #934, float errors on full tens. But it
// was too aggressive for #4360 because of conversion back to lin,
// therefore use precision 15.
axis.min = correctFloat(log2lin(axis.min), 15);
axis.max = correctFloat(log2lin(axis.max), 15);
}
// handle zoomed range
if (axis.range && defined(axis.max)) {
axis.userMin = axis.min = hardMin = Math.max(axis.min, axis.minFromRange()); // #618
axis.userMax = hardMax = axis.max;
axis.range = null; // don't use it when running setExtremes
}
// Hook for Highstock Scroller. Consider combining with beforePadding.
fireEvent(axis, 'foundExtremes');
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(hardMin) && minPadding) {
axis.min -= length * minPadding;
}
if (!defined(hardMax) && maxPadding) {
axis.max += length * maxPadding;
}
}
}
// Handle options for floor, ceiling, softMin and softMax
if (isNumber(options.floor)) {
axis.min = Math.max(axis.min, options.floor);
} else if (isNumber(options.softMin)) {
axis.min = Math.min(axis.min, options.softMin);
}
if (isNumber(options.ceiling)) {
axis.max = Math.min(axis.max, options.ceiling);
} else if (isNumber(options.softMax)) {
axis.max = Math.max(axis.max, options.softMax);
}
// When the threshold is soft, adjust the extreme value only if
// the data extreme and the padded extreme land on either side of the threshold. For example,
// a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the
// default minPadding and startOnTick options. This is prevented by the softThreshold
// option.
if (softThreshold && defined(axis.dataMin)) {
threshold = threshold || 0;
if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) {
axis.min = threshold;
} else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) {
axis.max = threshold;
}
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
this.tickAmount ? ((axis.max - axis.min) / Math.max(this.tickAmount - 1, 1)) : undefined,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / Math.max(axis.len, tickPixelIntervalOption)
);
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function(series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943, #4184)
if (axis.pointRange && !tickIntervalOption) {
axis.tickInterval = Math.max(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
axis.tickInterval = minTickInterval;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog && !tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(
axis.tickInterval,
null,
getMagnitude(axis.tickInterval),
// If the tick interval is between 0.5 and 5 and the axis max is in the order of
// thousands, chances are we are dealing with years. Don't allow decimals. #3363.
pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount
);
}
// Prevent ticks from getting so close that we can't draw the labels
if (!this.tickAmount) {
axis.tickInterval = axis.unsquish();
}
this.setTickPositions();
},
/**
* Now we have computed the normalized tickInterval, get the tick positions
*/
setTickPositions: function() {
var options = this.options,
tickPositions,
tickPositionsOption = options.tickPositions,
tickPositioner = options.tickPositioner,
startOnTick = options.startOnTick,
endOnTick = options.endOnTick,
single;
// Set the tickmarkOffset
this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
this.tickInterval === 1) ? 0.5 : 0; // #3202
// get minorTickInterval
this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
this.tickInterval / 5 : options.minorTickInterval;
// Find the tick positions
this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565)
if (!tickPositions) {
if (this.isDatetimeAxis) {
tickPositions = this.getTimeTicks(
this.normalizeTimeTickInterval(this.tickInterval, options.units),
this.min,
this.max,
options.startOfWeek,
this.ordinalPositions,
this.closestPointRange,
true
);
} else if (this.isLog) {
tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
} else {
tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
}
// Too dense ticks, keep only the first and last (#4477)
if (tickPositions.length > this.len) {
tickPositions = [tickPositions[0], tickPositions.pop()];
}
this.tickPositions = tickPositions;
// Run the tick positioner callback, that allows modifying auto tick positions.
if (tickPositioner) {
tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
if (tickPositioner) {
this.tickPositions = tickPositions = tickPositioner;
}
}
}
if (!this.isLinked) {
// reset min/max or remove extremes based on start/end on tick
this.trimTicks(tickPositions, startOnTick, endOnTick);
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (this.min === this.max && defined(this.min) && !this.tickAmount) {
// Substract half a unit (#2619, #2846, #2515, #3390)
single = true;
this.min -= 0.5;
this.max += 0.5;
}
this.single = single;
if (!tickPositionsOption && !tickPositioner) {
this.adjustTickAmount();
}
}
},
/**
* Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
*/
trimTicks: function(tickPositions, startOnTick, endOnTick) {
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = this.minPointOffset || 0;
if (startOnTick) {
this.min = roundedMin;
} else {
while (this.min - minPointOffset > tickPositions[0]) {
tickPositions.shift();
}
}
if (endOnTick) {
this.max = roundedMax;
} else {
while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) {
tickPositions.pop();
}
}
// If no tick are left, set one tick in the middle (#3195)
if (tickPositions.length === 0 && defined(roundedMin)) {
tickPositions.push((roundedMax + roundedMin) / 2);
}
},
/**
* Check if there are multiple axes in the same pane
* @returns {Boolean} There are other axes
*/
alignToOthers: function() {
var others = {}, // Whether there is another axis to pair with this one
hasOther,
options = this.options;
if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
each(this.chart[this.coll], function(axis) {
var otherOptions = axis.options,
horiz = axis.horiz,
key = [
horiz ? otherOptions.left : otherOptions.top,
otherOptions.width,
otherOptions.height,
otherOptions.pane
].join(',');
if (axis.series.length) { // #4442
if (others[key]) {
hasOther = true; // #4201
} else {
others[key] = 1;
}
}
});
}
return hasOther;
},
/**
* Set the max ticks of either the x and y axis collection
*/
getTickAmount: function() {
var options = this.options,
tickAmount = options.tickAmount,
tickPixelInterval = options.tickPixelInterval;
if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
!this.isLog && options.startOnTick && options.endOnTick) {
tickAmount = 2;
}
if (!tickAmount && this.alignToOthers()) {
// Add 1 because 4 tick intervals require 5 ticks (including first and last)
tickAmount = Math.ceil(this.len / tickPixelInterval) + 1;
}
// For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
// prevents the axis from adding ticks that are too far away from the data extremes.
if (tickAmount < 4) {
this.finalTickAmt = tickAmount;
tickAmount = 5;
}
this.tickAmount = tickAmount;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function() {
var tickInterval = this.tickInterval,
tickPositions = this.tickPositions,
tickAmount = this.tickAmount,
finalTickAmt = this.finalTickAmt,
currentTickAmount = tickPositions && tickPositions.length,
i,
len;
if (currentTickAmount < tickAmount) {
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + tickInterval
));
}
this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
this.max = tickPositions[tickPositions.length - 1];
// We have too many ticks, run second pass to try to reduce ticks
} else if (currentTickAmount > tickAmount) {
this.tickInterval *= 2;
this.setTickPositions();
}
// The finalTickAmt property is set in getTickAmount
if (defined(finalTickAmt)) {
i = len = tickPositions.length;
while (i--) {
if (
(finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
(finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
) {
tickPositions.splice(i, 1);
}
}
this.finalTickAmt = undefined;
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function() {
var axis = this,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function(series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) {
if (axis.resetStacks) {
axis.resetStacks();
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickInterval();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (axis.cleanStacks) {
axis.cleanStacks();
}
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function(newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
each(axis.series, function(serie) {
delete serie.kdTree;
});
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function() { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function(newMin, newMax) {
var dataMin = this.dataMin,
dataMax = this.dataMax,
options = this.options,
min = Math.min(dataMin, pick(options.min, dataMin)),
max = Math.max(dataMax, pick(options.max, dataMax));
if (newMin !== this.min || newMax !== this.max) { // #5790
// Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
if (!this.allowZoomOutside) {
if (defined(dataMin) && newMin <= min) {
newMin = min;
}
if (defined(dataMax) && newMax >= max) {
newMax = max;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== undefined || newMax !== undefined;
// Do it
this.setExtremes(
newMin,
newMax,
false,
undefined, {
trigger: 'zoom'
}
);
}
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function() {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
height = pick(options.height, chart.plotHeight),
top = pick(options.top, chart.plotTop),
left = pick(options.left, chart.plotLeft + offsetLeft),
percentRegex = /%$/;
// Check for percentage based input values. Rounding fixes problems with
// column overflow and plot line filtering (#4898, #4899)
if (percentRegex.test(height)) {
height = Math.round(parseFloat(height) / 100 * chart.plotHeight);
}
if (percentRegex.test(top)) {
top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop);
}
// Expose basic values to use in Series object and navigator
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = Math.max(horiz ? width : height, 0); // Math.max fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function() {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function(threshold) {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log,
realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (threshold === null) {
threshold = realMin;
} else if (realMin > threshold) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function(rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Get the tick length and width for the axis.
* @param {String} prefix 'tick' or 'minorTick'
* @returns {Array} An array of tickLength and tickWidth
*/
tickSize: function(prefix) {
var options = this.options,
tickLength = options[prefix + 'Length'],
tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1
if (tickWidth && tickLength) {
// Negate the length
if (options[prefix + 'Position'] === 'inside') {
tickLength = -tickLength;
}
return [tickLength, tickWidth];
}
},
/**
* Return the size of the labels
*/
labelMetrics: function() {
return this.chart.renderer.fontMetrics(
this.options.labels.style && this.options.labels.style.fontSize,
this.ticks[0] && this.ticks[0].label
);
},
/**
* Prevent the ticks from getting so close we can't draw the labels. On a horizontal
* axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
* On a vertical axis remove ticks and add ellipsis.
*/
unsquish: function() {
var labelOptions = this.options.labels,
horiz = this.horiz,
tickInterval = this.tickInterval,
newTickInterval = tickInterval,
slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
rotation,
rotationOption = labelOptions.rotation,
labelMetrics = this.labelMetrics(),
step,
bestScore = Number.MAX_VALUE,
autoRotation,
// Return the multiple of tickInterval that is needed to avoid collision
getStep = function(spaceNeeded) {
var step = spaceNeeded / (slotSize || 1);
step = step > 1 ? Math.ceil(step) : 1;
return step * tickInterval;
};
if (horiz) {
autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971
defined(rotationOption) ? [rotationOption] :
slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation
);
if (autoRotation) {
// Loop over the given autoRotation options, and determine which gives the best score. The
// best score is that with the lowest number of steps and a rotation closest to horizontal.
each(autoRotation, function(rot) {
var score;
if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
step = getStep(Math.abs(labelMetrics.h / Math.sin(deg2rad * rot)));
score = step + Math.abs(rot / 360);
if (score < bestScore) {
bestScore = score;
rotation = rot;
newTickInterval = step;
}
}
});
}
} else if (!labelOptions.step) { // #4411
newTickInterval = getStep(labelMetrics.h);
}
this.autoRotation = autoRotation;
this.labelRotation = pick(rotation, rotationOption);
return newTickInterval;
},
/**
* Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset)
* and the final tick rendering and placement (#5086).
*/
getSlotWidth: function() {
var chart = this.chart,
horiz = this.horiz,
labelOptions = this.options.labels,
slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1),
marginLeft = chart.margin[3];
return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415
((this.staggerLines || 1) * chart.plotWidth) / slotCount) ||
(!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931
},
/**
* Render the axis labels and determine whether ellipsis or rotation need to be applied
*/
renderUnsquish: function() {
var chart = this.chart,
renderer = chart.renderer,
tickPositions = this.tickPositions,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
slotWidth = this.getSlotWidth(),
innerWidth = Math.max(1, Math.round(slotWidth - 2 * (labelOptions.padding || 5))),
attr = {},
labelMetrics = this.labelMetrics(),
textOverflowOption = labelOptions.style && labelOptions.style.textOverflow,
css,
maxLabelLength = 0,
label,
i,
pos;
// Set rotation option unless it is "auto", like in gauges
if (!isString(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation || 0; // #4443
}
// Get the longest label length
each(tickPositions, function(tick) {
tick = ticks[tick];
if (tick && tick.labelLength > maxLabelLength) {
maxLabelLength = tick.labelLength;
}
});
this.maxLabelLength = maxLabelLength;
// Handle auto rotation on horizontal axis
if (this.autoRotation) {
// Apply rotation only if the label is too wide for the slot, and
// the label is wider than its height.
if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) {
attr.rotation = this.labelRotation;
} else {
this.labelRotation = 0;
}
// Handle word-wrap or ellipsis on vertical axis
} else if (slotWidth) {
// For word-wrap or ellipsis
css = {
width: innerWidth + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'clip';
// On vertical axis, only allow word wrap if there is room for more lines.
i = tickPositions.length;
while (!horiz && i--) {
pos = tickPositions[i];
label = ticks[pos].label;
if (label) {
// Reset ellipsis in order to get the correct bounding box (#4070)
if (label.styles && label.styles.textOverflow === 'ellipsis') {
label.css({
textOverflow: 'clip'
});
// Set the correct width in order to read the bounding box height (#4678, #5034)
} else if (ticks[pos].labelLength > slotWidth) {
label.css({
width: slotWidth + 'px'
});
}
if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
label.specCss = {
textOverflow: 'ellipsis'
};
}
}
}
}
}
// Add ellipsis if the label length is significantly longer than ideal
if (attr.rotation) {
css = {
width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'ellipsis';
}
}
// Set the explicit or automatic label alignment
this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation);
if (this.labelAlign) {
attr.align = this.labelAlign;
}
// Apply general and specific CSS
each(tickPositions, function(pos) {
var tick = ticks[pos],
label = tick && tick.label;
if (label) {
label.attr(attr); // This needs to go before the CSS in old IE (#4502)
if (css) {
label.css(merge(css, label.specCss));
}
delete label.specCss;
tick.rotation = attr.rotation;
}
});
// Note: Why is this not part of getLabelPosition?
this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0);
},
/**
* Return true if the axis has associated data
*/
hasData: function() {
return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions);
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
labelOffsetPadded,
opposite = axis.opposite,
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
clip,
directionFactor = [-1, 1, 1, -1][side],
n,
className = options.className,
textAlign,
axisParent = axis.axisParent, // Used in color axis
lineHeightCorrection,
tickSize = this.tickSize('tick');
// For reuse in Axis.render
hasData = axis.hasData();
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({
zIndex: options.gridZIndex || 1
})
.addClass('highcharts-' + this.coll.toLowerCase() + '-grid ' + (className || ''))
.add(axisParent);
axis.axisGroup = renderer.g('axis')
.attr({
zIndex: options.zIndex || 2
})
.addClass('highcharts-' + this.coll.toLowerCase() + ' ' + (className || ''))
.add(axisParent);
axis.labelGroup = renderer.g('axis-labels')
.attr({
zIndex: labelOptions.zIndex || 7
})
.addClass('highcharts-' + axis.coll.toLowerCase() + '-labels ' + (className || ''))
.add(axisParent);
}
if (hasData || axis.isLinked) {
// Generate ticks
each(tickPositions, function(pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
axis.renderUnsquish();
// Left side must be align: right and right side must have align: left for labels
if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || {
1: 'left',
3: 'right'
}[side] === axis.labelAlign || axis.labelAlign === 'center')) {
each(tickPositions, function(pos) {
// get the highest offset
labelOffset = Math.max(
ticks[pos].getLabelSize(),
labelOffset
);
});
}
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1);
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
textAlign = axisTitleOptions.textAlign;
if (!textAlign) {
textAlign = (horiz ? {
low: 'left',
middle: 'center',
high: 'right'
} : {
low: opposite ? 'right' : 'left',
middle: 'center',
high: opposite ? 'left' : 'right'
})[axisTitleOptions.align];
}
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align: textAlign
})
.addClass('highcharts-axis-title')
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleOffsetOption = axisTitleOptions.offset;
titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide'](true);
}
// Render the axis line
axis.renderLine();
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.tickRotCorr = axis.tickRotCorr || {
x: 0,
y: 0
}; // polar
if (side === 0) {
lineHeightCorrection = -axis.labelMetrics().h;
} else if (side === 2) {
lineHeightCorrection = axis.tickRotCorr.y;
} else {
lineHeightCorrection = 0;
}
// Find the padded label offset
labelOffsetPadded = Math.abs(labelOffset) + titleMargin;
if (labelOffset) {
labelOffsetPadded -= lineHeightCorrection;
labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x);
}
axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
axisOffset[side] = Math.max(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
labelOffsetPadded, // #3027
hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866
);
// Decide the clipping needed to keep the graph inside the plot area and axis lines
clip = options.offset ? 0 : Math.floor(axis.axisLine.strokeWidth() / 2) * 2; // #4308, #4371
clipOffset[invertedSide] = Math.max(clipOffset[invertedSide], clip);
},
/**
* Get the path for the axis line
*/
getLinePath: function(lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer
.crispLine([
'M',
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
'L',
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Render the axis line
* @returns {[type]} [description]
*/
renderLine: function() {
if (!this.axisLine) {
this.axisLine = this.chart.renderer.path()
.addClass('highcharts-axis-line')
.add(this.axisGroup);
}
},
/**
* Position the title
*/
getTitlePosition: function() {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
xOption = axisTitleOptions.x || 0,
yOption = axisTitleOptions.y || 0,
fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style && axisTitleOptions.style.fontSize, this.axisTitle).f,
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption,
y: horiz ?
offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption
};
},
/**
* Render the axis
*/
render: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
lin2log = axis.lin2log,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
axisLine = axis.axisLine,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && isNumber(axis.oldMin),
showAxis = axis.showAxis,
animation = animObject(renderer.globalAnimation),
from,
to;
// Reset
axis.labelEdge.length = 0;
//axis.justifyToPlot = overflow === 'justify';
axis.overlap = false;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function(coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (axis.hasData() || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function(pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions, function(pos, i) {
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true, 0.1);
}
ticks[pos].render(i);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && (axis.min === 0 || axis.single)) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function(pos, i) {
to = tickPositions[i + 1] !== undefined ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset;
if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660
if (!alternateBands[pos]) {
alternateBands[pos] = new PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function(plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function(coll) {
var pos,
i,
forDestruction = [],
delay = animation.duration,
destroyInactiveItems = function() {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
syncTimeout(
destroyInactiveItems,
coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay
);
});
// Set the axis line path
if (axisLine) {
axisLine[axisLine.isPlaced ? 'animate' : 'attr']({
d: this.getLinePath(axisLine.strokeWidth())
});
axisLine.isPlaced = true;
// Show or hide the line depending on options.showEmpty
axisLine[showAxis ? 'show' : 'hide'](true);
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
axis.renderStackTotals();
}
// End stacked totals
axis.isDirty = false;
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function() {
if (this.visible) {
// render the axis
this.render();
// move plot lines and bands
each(this.plotLinesAndBands, function(plotLine) {
plotLine.render();
});
}
// mark associated series as dirty and ready for redraw
each(this.series, function(series) {
series.isDirty = true;
});
},
/**
* Destroys an Axis instance.
*/
destroy: function(keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i,
n,
keepProps;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function(coll) {
destroyObjectProperties(coll);
});
if (plotLinesAndBands) {
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function(prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
// Delete all properties and fall back to the prototype.
// Preserve some properties, needed for Axis.update (#4317, #5773).
keepProps = ['extKey', 'hcEvents', 'names', 'series', 'userMax', 'userMin'];
for (n in axis) {
if (axis.hasOwnProperty(n) && inArray(n, keepProps) === -1) {
delete axis[n];
}
}
},
/**
* Draw the crosshair
*
* @param {Object} e The event arguments from the modified pointer event
* @param {Object} point The Point object
*/
drawCrosshair: function(e, point) {
var path,
options = this.crosshair,
snap = pick(options.snap, true),
pos,
categorized,
graphic = this.cross;
// Use last available event when updating non-snapped crosshairs without
// mouse interaction (#5287)
if (!e) {
e = this.cross && this.cross.e;
}
if (
// Disabled in options
!this.crosshair ||
// Snap
((defined(point) || !snap) === false)
) {
this.hideCrosshair();
} else {
// Get the path
if (!snap) {
pos = e && (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
}
if (defined(pos)) {
path = this.getPlotLinePath(
// First argument, value, only used on radial
point && (this.isXAxis ? point.x : pick(point.stackY, point.y)),
null,
null,
null,
pos // Translated position
) || null; // #3189
}
if (!defined(path)) {
this.hideCrosshair();
return;
}
categorized = this.categories && !this.isRadial;
// Draw the cross
if (!graphic) {
this.cross = graphic = this.chart.renderer
.path()
.addClass('highcharts-crosshair highcharts-crosshair-' +
(categorized ? 'category ' : 'thin ') + options.className)
.attr({
zIndex: pick(options.zIndex, 2)
})
.add();
}
graphic.show().attr({
d: path
});
if (categorized && !options.width) {
graphic.attr({
'stroke-width': this.transA
});
}
this.cross.e = e;
}
},
/**
* Hide the crosshair.
*/
hideCrosshair: function() {
if (this.cross) {
this.cross.hide();
}
}
}; // end Axis
extend(H.Axis.prototype, AxisPlotLineOrBandExtension);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
getMagnitude = H.getMagnitude,
map = H.map,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick;
/**
* Methods defined on the Axis prototype
*/
/**
* Set the tick positions of a logarithmic axis
*/
Axis.prototype.getLogTickPositions = function(interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
lin2log = axis.lin2log,
log2lin = axis.log2lin,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = Math.round(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = Math.floor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max) && lastPos !== undefined) { // #1670, lastPos is #3113
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};
Axis.prototype.log2lin = function(num) {
return Math.log(num) / Math.LN10;
};
Axis.prototype.lin2log = function(num) {
return Math.pow(10, num);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var dateFormat = H.dateFormat,
each = H.each,
extend = H.extend,
format = H.format,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pick = H.pick,
splat = H.splat,
stop = H.stop,
syncTimeout = H.syncTimeout,
timeUnits = H.timeUnits;
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
H.Tooltip = function() {
this.init.apply(this, arguments);
};
H.Tooltip.prototype = {
init: function(chart, options) {
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = undefined;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = {
x: 0,
y: 0
};
// The tooltip is initially hidden
this.isHidden = true;
// Public property for getting the shared state.
this.split = options.split && !chart.inverted;
this.shared = options.shared || this.split;
},
/**
* Destroy the single tooltips in a split tooltip.
* If the tooltip is active then it is not destroyed, unless forced to.
* @param {boolean} force Force destroy all tooltips.
* @return {undefined}
*/
cleanSplit: function(force) {
each(this.chart.series, function(series) {
var tt = series && series.tt;
if (tt) {
if (!tt.isActive || force) {
series.tt = tt.destroy();
} else {
tt.isActive = false;
}
}
});
},
/**
* Create the Tooltip label element if it doesn't exist, then return the
* label.
*/
getLabel: function() {
var renderer = this.chart.renderer,
options = this.options;
if (!this.label) {
// Create the label
if (this.split) {
this.label = renderer.g('tooltip');
} else {
this.label = renderer.label(
'',
0,
0,
options.shape || 'callout',
null,
null,
options.useHTML,
null,
'tooltip'
)
.attr({
padding: options.padding,
r: options.borderRadius
});
}
this.label
.attr({
zIndex: 8
})
.add();
}
return this.label;
},
update: function(options) {
this.destroy();
this.init(this.chart, merge(true, this.options, options));
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function() {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
if (this.split && this.tt) {
this.cleanSplit(this.chart, true);
this.tt = this.tt.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function(x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden &&
// When we get close to the target position, abort animation and land on the right place (#3056)
(Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1),
skipAnchor = tooltip.followPointer || tooltip.len > 1;
// Get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// Move to the intermediate value
tooltip.getLabel().attr(now);
// Run on next tick of the mouse tracker
if (animate) {
// Never allow two timeouts
clearTimeout(this.tooltipTimeout);
// Set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function() {
// The interval function may still be running during destroy,
// so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function(delay) {
var tooltip = this;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
delay = pick(delay, this.options.hideDelay, 500);
if (!this.isHidden) {
this.hideTimer = syncTimeout(function() {
tooltip.getLabel()[delay ? 'fadeOut' : 'hide']();
tooltip.isHidden = true;
}, delay);
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function(points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
plotX = 0,
plotY = 0,
yAxis,
xAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === undefined) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function(point) {
yAxis = point.series.yAxis;
xAxis = point.series.xAxis;
plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, Math.round);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function(boxWidth, boxHeight, point) {
var chart = this.chart,
distance = this.distance,
ret = {},
h = point.h || 0, // #4117
swapped,
first = ['y', chart.chartHeight, boxHeight,
point.plotY + chart.plotTop, chart.plotTop,
chart.plotTop + chart.plotHeight
],
second = ['x', chart.chartWidth, boxWidth,
point.plotX + chart.plotLeft, chart.plotLeft,
chart.plotLeft + chart.plotWidth
],
// The far side is right or bottom
preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984
/**
* Handle the preferred dimension. When the preferred dimension is tooltip
* on top or bottom of the point, it will look for space there.
*/
firstDimension = function(dim, outerSize, innerSize, point, min, max) {
var roomLeft = innerSize < point - distance,
roomRight = point + distance + innerSize < outerSize,
alignedLeft = point - distance - innerSize,
alignedRight = point + distance;
if (preferFarSide && roomRight) {
ret[dim] = alignedRight;
} else if (!preferFarSide && roomLeft) {
ret[dim] = alignedLeft;
} else if (roomLeft) {
ret[dim] = Math.min(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h);
} else if (roomRight) {
ret[dim] = Math.max(
min,
alignedRight + h + innerSize > outerSize ?
alignedRight :
alignedRight + h
);
} else {
return false;
}
},
/**
* Handle the secondary dimension. If the preferred dimension is tooltip
* on top or bottom of the point, the second dimension is to align the tooltip
* above the point, trying to align center but allowing left or right
* align within the chart box.
*/
secondDimension = function(dim, outerSize, innerSize, point) {
var retVal;
// Too close to the edge, return false and swap dimensions
if (point < distance || point > outerSize - distance) {
retVal = false;
// Align left/top
} else if (point < innerSize / 2) {
ret[dim] = 1;
// Align right/bottom
} else if (point > outerSize - innerSize / 2) {
ret[dim] = outerSize - innerSize - 2;
// Align center
} else {
ret[dim] = point - innerSize / 2;
}
return retVal;
},
/**
* Swap the dimensions
*/
swap = function(count) {
var temp = first;
first = second;
second = temp;
swapped = count;
},
run = function() {
if (firstDimension.apply(0, first) !== false) {
if (secondDimension.apply(0, second) === false && !swapped) {
swap(true);
run();
}
} else if (!swapped) {
swap(true);
run();
} else {
ret.x = ret.y = 0;
}
};
// Under these conditions, prefer the tooltip on the side of the point
if (chart.inverted || this.len > 1) {
swap();
}
run();
return ret;
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*
* @returns {String|Array<String>}
*/
defaultFormatter: function(tooltip) {
var items = this.points || splat(this),
s;
// Build the header
s = [tooltip.tooltipFooterHeaderFormatter(items[0])];
// build the values
s = s.concat(tooltip.bodyFormatter(items));
// footer
s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true));
return s;
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function(point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.getLabel(),
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(point, function(item) {
item.setState('hover');
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
this.len = pointConfig.length;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
this.distance = pick(currentSeries.tooltipOptions.distance, 16);
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr({
opacity: 1
}).show();
}
// update text
if (tooltip.split) {
this.renderSplit(text, chart.hoverPoints);
} else {
label.attr({
text: text.join ? text.join('') : text
});
// Set the stroke color of the box to reflect the point
label.removeClass(/highcharts-color-[\d]+/g)
.addClass('highcharts-color-' + pick(point.colorIndex, currentSeries.colorIndex));
tooltip.updatePosition({
plotX: x,
plotY: y,
negative: point.negative,
ttBelow: point.ttBelow,
h: anchor[2] || 0
});
}
this.isHidden = false;
}
},
/**
* Render the split tooltip. Loops over each point's text and adds
* a label next to the point, then uses the distribute function to
* find best non-overlapping positions.
*/
renderSplit: function(labels, points) {
var tooltip = this,
boxes = [],
chart = this.chart,
ren = chart.renderer,
rightAligned = true,
options = this.options,
headerHeight,
tooltipLabel = this.getLabel();
// Create the individual labels
each(labels.slice(0, labels.length - 1), function(str, i) {
var point = points[i - 1] ||
// Item 0 is the header. Instead of this, we could also use the crosshair label
{
isHeader: true,
plotX: points[0].plotX
},
owner = point.series || tooltip,
tt = owner.tt,
series = point.series || {},
colorClass = 'highcharts-color-' + pick(point.colorIndex, series.colorIndex, 'none'),
target,
x,
bBox,
boxWidth;
// Store the tooltip referance on the series
if (!tt) {
owner.tt = tt = ren.label(null, null, null, point.isHeader && 'callout')
.addClass('highcharts-tooltip-box ' + colorClass)
.attr({
'padding': options.padding,
'r': options.borderRadius
})
.add(tooltipLabel);
// Add a connector back to the point
if (point.series) {
tt.connector = ren.path()
.addClass('highcharts-tooltip-connector ' + colorClass)
// Add it inside the label group so we will get hide and
// destroy for free
.add(tt);
}
}
tt.isActive = true;
tt.attr({
text: str
});
// Get X position now, so we can move all to the other side in case of overflow
bBox = tt.getBBox();
boxWidth = bBox.width + tt.strokeWidth();
if (point.isHeader) {
headerHeight = bBox.height;
x = Math.max(
0, // No left overflow
Math.min(
point.plotX + chart.plotLeft - boxWidth / 2,
chart.chartWidth - boxWidth // No right overflow (#5794)
)
);
} else {
x = point.plotX + chart.plotLeft - pick(options.distance, 16) -
boxWidth;
}
// If overflow left, we don't use this x in the next loop
if (x < 0) {
rightAligned = false;
}
// Prepare for distribution
target = (point.series && point.series.yAxis && point.series.yAxis.pos) + (point.plotY || 0);
target -= chart.plotTop;
boxes.push({
target: point.isHeader ? chart.plotHeight + headerHeight : target,
rank: point.isHeader ? 1 : 0,
size: owner.tt.getBBox().height + 1,
point: point,
x: x,
tt: tt
});
});
// Clean previous run (for missing points)
this.cleanSplit();
// Distribute and put in place
H.distribute(boxes, chart.plotHeight + headerHeight);
each(boxes, function(box) {
var point = box.point,
tt = box.tt,
attr;
// Put the label in place
attr = {
visibility: box.pos === undefined ? 'hidden' : 'inherit',
x: (rightAligned || point.isHeader ? box.x : point.plotX + chart.plotLeft + pick(options.distance, 16)),
y: box.pos + chart.plotTop
};
if (point.isHeader) {
attr.anchorX = point.plotX + chart.plotLeft;
attr.anchorY = attr.y - 100;
}
tt.attr(attr);
// Draw the connector to the point
if (!point.isHeader) {
tt.connector.attr({
d: [
'M',
point.plotX + chart.plotLeft - attr.x,
point.plotY + point.series.yAxis.pos - attr.y,
'L',
(rightAligned ? -1 : 1) * pick(options.distance, 16) +
point.plotX + chart.plotLeft - attr.x,
box.pos + chart.plotTop + tt.getBBox().height / 2 -
attr.y
]
});
}
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function(point) {
var chart = this.chart,
label = this.getLabel(),
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
Math.round(pos.x),
Math.round(pos.y || 0), // can be undefined (#3977)
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
},
/**
* Get the best X date format based on the closest point range on the axis.
*/
getXDateFormat: function(point, options, xAxis) {
var xDateFormat,
dateTimeLabelFormats = options.dateTimeLabelFormats,
closestPointRange = xAxis && xAxis.closestPointRange,
n,
blank = '01-01 00:00:00.000',
strpos = {
millisecond: 15,
second: 12,
minute: 9,
hour: 6,
day: 3
},
date,
lastN = 'millisecond'; // for sub-millisecond data, #4223
if (closestPointRange) {
date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
for (n in timeUnits) {
// If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
date.substr(6) === blank.substr(6)) {
n = 'week';
break;
}
// The first format that is too great for the range
if (timeUnits[n] > closestPointRange) {
n = lastN;
break;
}
// If the point is placed every day at 23:59, we need to show
// the minutes as well. #2637.
if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
break;
}
// Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
if (n !== 'week') {
lastN = n;
}
}
if (n) {
xDateFormat = dateTimeLabelFormats[n];
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
},
/**
* Format the footer/header of the tooltip
* #3397: abstraction to enable formatting of footer and header
*/
tooltipFooterHeaderFormatter: function(labelConfig, isFooter) {
var footOrHead = isFooter ? 'footer' : 'header',
series = labelConfig.series,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key),
formatString = tooltipOptions[footOrHead + 'Format'];
// Guess the best date format based on the closest point distance (#568, #3418)
if (isDateTime && !xDateFormat) {
xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis);
}
// Insert the footer date format if any
if (isDateTime && xDateFormat) {
formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(formatString, {
point: labelConfig,
series: series
});
},
/**
* Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
* abstracting this functionality allows to easily overwrite and extend it.
*/
bodyFormatter: function(items) {
return map(items, function(item) {
var tooltipOptions = item.series.tooltipOptions;
return (tooltipOptions.pointFormatter || item.point.tooltipFormatter)
.call(item.point, tooltipOptions.pointFormat);
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
defined = H.defined,
doc = H.doc,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
offset = H.offset,
pick = H.pick,
removeEvent = H.removeEvent,
splat = H.splat,
Tooltip = H.Tooltip,
win = H.win;
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
H.Pointer = function(chart, options) {
this.init(chart, options);
};
H.Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function(chart, options) {
// Store references
this.options = options;
this.chart = chart;
// Do we need to handle click on a touch device?
this.runChartClick = options.chart.events && !!options.chart.events.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (Tooltip && options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
this.followTouchMove = pick(options.tooltip.followTouchMove, true);
}
this.setDOMEvents();
},
/**
* Resolve the zoomType option
*/
zoomOption: function() {
var chart = this.chart,
zoomType = chart.options.chart.zoomType,
zoomX = /x/.test(zoomType),
zoomY = /y/.test(zoomType),
inverted = chart.inverted;
this.zoomX = zoomX;
this.zoomY = zoomY;
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
this.hasZoom = zoomX || zoomY;
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function(e, chartPosition) {
var chartX,
chartY,
ePos;
// IE normalizing
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// iOS (#2757)
ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === undefined) { // IE < 9. #886.
chartX = Math.max(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: Math.round(chartX),
chartY: Math.round(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function(e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function(axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function(e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
shared = tooltip ? tooltip.shared : false,
followPointer,
updatePosition = true,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
anchor,
noSharedTooltip,
stickToHoverSeries,
directTouch,
kdpoints = [],
kdpointT;
// For hovering over the empty parts of the plot area (hoverSeries is undefined).
// If there is one series with point tracking (combo chart), don't go to nearest neighbour.
if (!shared && !hoverSeries) {
for (i = 0; i < series.length; i++) {
if (series[i].directTouch || !series[i].options.stickyTracking) {
series = [];
}
}
}
// If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on
// a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise,
// search the k-d tree.
stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch);
if (stickToHoverSeries && hoverPoint) {
kdpoints = [hoverPoint];
// Handle shared tooltip or cases where a series is not yet hovered
} else {
// When we have non-shared tooltip and sticky tracking is disabled,
// search for the closest point only on hovered series: #5533, #5476
if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) {
series = [hoverSeries];
}
// Find nearest points on all series
each(series, function(s) {
// Skip hidden series
noSharedTooltip = s.noSharedTooltip && shared;
directTouch = !shared && s.directTouch;
if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821
kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828
if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197)
kdpoints.push(kdpointT);
}
}
});
// Sort kdpoints by distance to mouse pointer
kdpoints.sort(function(p1, p2) {
var isCloserX = p1.distX - p2.distX,
isCloser = p1.dist - p2.dist,
isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1;
// We have two points which are not in the same place on xAxis and shared tooltip:
if (isCloserX !== 0 && shared) { // #5721
return isCloserX;
}
// Points are not exactly in the same place on x/yAxis:
if (isCloser !== 0) {
return isCloser;
}
// The same xAxis and yAxis position, sort by z-index:
return isAbove;
});
}
// Remove points with different x-positions, required for shared tooltip and crosshairs (#4645):
if (shared) {
i = kdpoints.length;
while (i--) {
if (kdpoints[i].x !== kdpoints[0].x || kdpoints[i].series.noSharedTooltip) {
kdpoints.splice(i, 1);
}
}
}
// Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200
if (kdpoints[0] && (kdpoints[0] !== this.prevKDPoint || (tooltip && tooltip.isHidden))) {
// Draw tooltip if necessary
if (shared && !kdpoints[0].series.noSharedTooltip) {
// Do mouseover on all points (#3919, #3985, #4410, #5622)
for (i = 0; i < kdpoints.length; i++) {
kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0]));
}
if (kdpoints.length && tooltip) {
// Keep the order of series in tooltip:
tooltip.refresh(kdpoints.sort(function(p1, p2) {
return p1.series.index - p2.series.index;
}), e);
}
} else {
if (tooltip) {
tooltip.refresh(kdpoints[0], e);
}
if (!hoverSeries || !hoverSeries.directTouch) { // #4448
kdpoints[0].onMouseOver(e);
}
}
this.prevKDPoint = kdpoints[0];
updatePosition = false;
}
// Update positions (regardless of kdpoint or hoverPoint)
if (updatePosition) {
followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
if (tooltip && followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({
plotX: anchor[0],
plotY: anchor[1]
});
}
}
// Start the event listener to pick up the tooltip and crosshairs
if (!pointer._onDocumentMouseMove) {
pointer._onDocumentMouseMove = function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.onDocumentMouseMove(e);
}
};
addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
}
// Crosshair. For each hover point, loop over axes and draw cross if that point
// belongs to the axis (#4927).
each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269
each(chart.axes, function drawAxisCrosshair(axis) {
// In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066)
if (!point || point.series && point.series[axis.coll] === axis) { // #5658
axis.drawCrosshair(e, point);
}
});
});
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function(allowMove, delay) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
hoverPoints = chart.hoverPoints,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint;
// Check if the points have moved outside the plot area (#1003, #4736, #5101)
if (allowMove && tooltipPoints) {
each(splat(tooltipPoints), function(point) {
if (point.series.isCartesian && point.plotX === undefined) {
allowMove = false;
}
});
}
// Just move the tooltip, #349
if (allowMove) {
if (tooltip && tooltipPoints) {
tooltip.refresh(tooltipPoints);
if (hoverPoint) { // #2500
hoverPoint.setState(hoverPoint.state, true);
each(chart.axes, function(axis) {
if (axis.crosshair) {
axis.drawCrosshair(null, hoverPoint);
}
});
}
}
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide(delay);
}
if (pointer._onDocumentMouseMove) {
removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
pointer._onDocumentMouseMove = null;
}
// Remove crosshairs
each(chart.axes, function(axis) {
axis.hideCrosshair();
});
pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function(attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function(series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled && series.group) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Start a drag operation
*/
dragStart: function(e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function(e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
selectionMarker = this.selectionMarker,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY,
panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
// If the device supports both touch and mouse (like IE11), and we are touch-dragging
// inside the plot area, don't handle the mouse event. #4339.
if (selectionMarker && selectionMarker.touch) {
return;
}
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
if (!selectionMarker) {
this.selectionMarker = selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
'class': 'highcharts-selection-marker',
'zIndex': 7
})
.add();
}
}
// adjust the width of the selection marker
if (selectionMarker && zoomHor) {
size = chartX - mouseDownX;
selectionMarker.attr({
width: Math.abs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (selectionMarker && zoomVert) {
size = chartY - mouseDownY;
selectionMarker.attr({
height: Math.abs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function(e) {
var pointer = this,
chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
originalEvent: e, // #4890
xAxis: [],
yAxis: []
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function(axis) {
if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{
xAxis: 'zoomX',
yAxis: 'zoomY'
}[axis.coll]])) { // #859, #3569
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
selectionData[axis.coll].push({
axis: axis,
min: Math.min(selectionMin, selectionMax), // for reversed axes
max: Math.max(selectionMin, selectionMax)
});
runZoom = true;
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function(args) {
chart.zoom(extend(args, hasPinched ? {
animation: false
} : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, {
cursor: chart._cursor
});
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function(e) {
e = this.normalize(e);
this.zoomOption();
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function(e) {
var chart = this.chart,
chartPosition = this.chartPosition;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function(e) {
var chart = charts[H.hoverChartIndex];
if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function(e) {
var chart = this.chart;
if (!defined(H.hoverChartIndex) || !charts[H.hoverChartIndex] || !charts[H.hoverChartIndex].mouseIsDown) {
H.hoverChartIndex = chart.index;
}
e = this.normalize(e);
e.returnValue = false; // #2251, #3224
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function(element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
}
if (elemClassName.indexOf('highcharts-container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function(e) {
var series = this.chart.hoverSeries,
relatedTarget = e.relatedTarget || e.toElement;
if (series && relatedTarget && !series.options.stickyTracking &&
!this.inClass(relatedTarget, 'highcharts-tooltip') &&
(!this.inClass(relatedTarget, 'highcharts-series-' + series.index) || // #2499, #4465
!this.inClass(relatedTarget, 'highcharts-tracker') // #5553
)
) {
series.onMouseOut();
}
},
onContainerClick: function(e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop;
e = this.normalize(e);
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, 'highcharts-tracker')) {
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function() {
var pointer = this,
container = pointer.chart.container;
container.onmousedown = function(e) {
pointer.onContainerMouseDown(e);
};
container.onmousemove = function(e) {
pointer.onContainerMouseMove(e);
};
container.onclick = function(e) {
pointer.onContainerClick(e);
};
addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
if (H.chartCount === 1) {
addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
}
if (H.hasTouch) {
container.ontouchstart = function(e) {
pointer.onContainerTouchStart(e);
};
container.ontouchmove = function(e) {
pointer.onContainerTouchMove(e);
};
if (H.chartCount === 1) {
addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
}
}
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function() {
var prop;
removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
if (!H.chartCount) {
removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
}
// memory and CPU leak
clearInterval(this.tooltipTimeout);
for (prop in this) {
this[prop] = null;
}
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var charts = H.charts,
each = H.each,
extend = H.extend,
map = H.map,
noop = H.noop,
pick = H.pick,
Pointer = H.Pointer;
/* Support for touch devices */
extend(Pointer.prototype, {
/**
* Run translation operations
*/
pinchTranslate: function(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function(horiz, pinchDown, touches, transform,
selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function() {
// Don't zoom if fingers are too close on this axis
if (!singleTouch && Math.abs(touch0Start - touch1Start) > 20) {
scale = forcedScale || Math.abs(touch0Now - touch1Now) / Math.abs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) {
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function(e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
hasZoom = self.hasZoom,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, 'highcharts-tracker') &&
chart.runTrackerClick) || self.runChartClick),
clip = {};
// Don't initiate panning until the user has pinched. This prevents us from
// blocking page scrolling as users scroll down a long page (#4210).
if (touchesLength > 1) {
self.initiated = true;
}
// On touch devices, only proceed to trigger click if a handler is defined
if (hasZoom && self.initiated && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function(e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function(e, i) {
pinchDown[i] = {
chartX: e.chartX,
chartY: e.chartY
};
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function(axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
absMin = Math.min(min, max),
absMax = Math.max(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = Math.min(axis.pos, absMin - minPixelPadding);
bounds.max = Math.max(axis.pos + axis.len, absMax + minPixelPadding);
}
});
self.res = true; // reset on next move
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop,
touch: true
}, chart.plotBox);
}
self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && self.followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
} else if (self.res) {
self.res = false;
this.reset(false, 0);
}
}
},
/**
* General touch handler shared by touchstart and touchmove.
*/
touch: function(e, start) {
var chart = this.chart,
hasMoved,
pinchDown;
H.hoverChartIndex = chart.index;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
// Run mouse events and display tooltip etc
if (start) {
this.runPointActions(e);
}
// Android fires touchmove events after the touchstart even if the
// finger hasn't moved, or moved only a pixel or two. In iOS however,
// the touchmove doesn't fire unless the finger moves more than ~4px.
// So we emulate this behaviour in Android by checking how much it
// moved, and cancelling on small distances. #3450.
if (e.type === 'touchmove') {
pinchDown = this.pinchDown;
hasMoved = pinchDown[0] ? Math.sqrt( // #5266
Math.pow(pinchDown[0].chartX - e.chartX, 2) +
Math.pow(pinchDown[0].chartY - e.chartY, 2)
) >= 4 : false;
}
if (pick(hasMoved, true)) {
this.pinch(e);
}
} else if (start) {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchStart: function(e) {
this.zoomOption();
this.touch(e, true);
},
onContainerTouchMove: function(e) {
this.touch(e);
},
onDocumentTouchEnd: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
charts = H.charts,
css = H.css,
doc = H.doc,
extend = H.extend,
noop = H.noop,
Pointer = H.Pointer,
removeEvent = H.removeEvent,
win = H.win,
wrap = H.wrap;
if (win.PointerEvent || win.MSPointerEvent) {
// The touches object keeps track of the points being touched at all times
var touches = {},
hasPointerEvent = !!win.PointerEvent,
getWebkitTouches = function() {
var key,
fake = [];
fake.item = function(i) {
return this[i];
};
for (key in touches) {
if (touches.hasOwnProperty(key)) {
fake.push({
pageX: touches[key].pageX,
pageY: touches[key].pageY,
target: touches[key].target
});
}
}
return fake;
},
translateMSPointer = function(e, method, wktype, func) {
var p;
if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[H.hoverChartIndex]) {
func(e);
p = charts[H.hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
};
/**
* Extend the Pointer prototype with methods for each event handler and more
*/
extend(Pointer.prototype, {
onContainerPointerDown: function(e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY,
target: e.currentTarget
};
});
},
onContainerPointerMove: function(e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY
};
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
},
onDocumentPointerUp: function(e) {
translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function(e) {
delete touches[e.pointerId];
});
},
/**
* Add or remove the MS Pointer specific events
*/
batchMSEvents: function(fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
}
});
// Disable default IE actions for pinch and such on chart element
wrap(Pointer.prototype, 'init', function(proceed, chart, options) {
proceed.call(this, chart, options);
if (this.hasZoom) { // #4014
css(chart.container, {
'-ms-touch-action': 'none',
'touch-action': 'none'
});
}
});
// Add IE specific touch events to chart
wrap(Pointer.prototype, 'setDOMEvents', function(proceed) {
proceed.apply(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
});
// Destroy MS events also
wrap(Pointer.prototype, 'destroy', function(proceed) {
this.batchMSEvents(removeEvent);
proceed.call(this);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Legend,
addEvent = H.addEvent,
css = H.css,
discardElement = H.discardElement,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
marginNames = H.marginNames,
merge = H.merge,
pick = H.pick,
setAnimation = H.setAnimation,
stableSort = H.stableSort,
win = H.win,
wrap = H.wrap;
/**
* The overview of the chart's series
*/
Legend = H.Legend = function(chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function(chart, options) {
this.chart = chart;
this.setOptions(options);
if (options.enabled) {
// Render it
this.render();
// move checkboxes
addEvent(this.chart, 'endResize', function() {
this.legend.positionCheckboxes();
});
}
},
setOptions: function(options) {
var padding = pick(options.padding, 8);
this.options = options;
this.itemMarginTop = options.itemMarginTop || 0;
this.padding = padding;
this.initialItemX = padding;
this.initialItemY = padding - 5; // 5 is the number of pixels above the text
this.maxItemWidth = 0;
this.itemHeight = 0;
this.symbolWidth = pick(options.symbolWidth, 16);
this.pages = [];
},
/**
* Update the legend with new options. Equivalent to running chart.update with a legend
* configuration option.
* @param {Object} options Legend options
* @param {Boolean} redraw Whether to redraw the chart, defaults to true.
*/
update: function(options, redraw) {
var chart = this.chart;
this.setOptions(merge(true, this.options, options));
this.destroy();
chart.isDirtyLegend = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function(item, visible) {
item.legendGroup[visible ? 'removeClass' : 'addClass']('highcharts-legend-item-hidden');
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function(item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox,
legendGroup = item.legendGroup;
if (legendGroup && legendGroup.element) {
legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function(item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function() {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
// Destroy items
each(this.getAllItems(), function(item) {
each(['legendItem', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
});
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function(scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight,
titleHeight = this.titleHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function(item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3;
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + 'px',
top: top + 'px',
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : 'none'
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function() {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({
zIndex: 1
})
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({
translateY: titleHeight
});
}
this.titleHeight = titleHeight;
},
/**
* Set the legend item text
*/
setText: function(item) {
var options = this.options;
item.legendItem.attr({
text: options.labelFormat ? H.format(options.labelFormat, item) : options.labelFormatter.call(item)
});
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function(item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
isSeries = !item.series,
series = !isSeries && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML,
fontSize = 12;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.addClass('highcharts-' + series.type + '-series highcharts-color-' + item.colorIndex + ' ' +
(item.options.className || '') +
(isSeries ? 'highcharts-series-' + item.index : '')
)
.attr({
zIndex: 1
})
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
'',
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.fontMetrics = renderer.fontMetrics(
fontSize,
li
);
legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML);
}
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// Always update the text
legend.setText(item);
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = Math.round(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line (#915, #3976)
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = Math.max(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = Math.max(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || Math.max(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function() {
var allItems = [];
each(this.chart.series, function(series) {
var seriesOptions = series && series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? undefined : false, true)) {
// Use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
}
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function(margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7
if (!options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function(alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = Math.max(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function() {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({
zIndex: 7
})
.add();
legend.contentGroup = renderer.g()
.attr({
zIndex: 1
}) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function(a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function(item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (!box) {
legend.box = box = renderer.rect()
.addClass('highcharts-legend-box')
.attr({
r: options.borderRadius
})
.add(legendGroup);
box.isNew = true;
}
if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({
x: 0,
y: 0,
width: legendWidth,
height: legendHeight
}, box.strokeWidth())
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
// Open for responsiveness
if (legendGroup.getStyle('display') === 'none') {
legendWidth = legendHeight = 0;
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function(item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function(legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
padding = this.padding,
lastY,
allItems = this.allItems,
clipToHeight = function(height) {
clipRect.attr({
height: height
});
// useHTML
if (legend.contentGroup.div) {
legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
}
};
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = Math.min(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && navOptions.enabled !== false) {
this.clipHeight = clipHeight = Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function(item, i) {
var y = item._legendItemPos[1],
h = Math.round(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipToHeight(clipHeight);
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({
zIndex: 1
}).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.addClass('highcharts-legend-navigation')
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipToHeight(chart.chartHeight);
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function(scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== undefined) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: 'visible'
});
this.up.attr({
'class': currentPage === 1 ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
'x': 18 + this.pager.getBBox().width, // adjust to text width
'class': currentPage === pageCount ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
H.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function(legend, item) {
var options = legend.options,
symbolHeight = options.symbolHeight || legend.fontMetrics.f,
square = options.squareSymbol,
symbolWidth = square ? symbolHeight : legend.symbolWidth;
item.legendSymbol = this.chart.renderer.rect(
square ? (legend.symbolWidth - symbolHeight) / 2 : 0,
legend.baseline - symbolHeight + 1, // #3988
symbolWidth,
symbolHeight,
pick(legend.options.symbolRadius, symbolHeight / 2)
)
.addClass('highcharts-point')
.attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function(legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - Math.round(legend.fontMetrics.b * 0.3),
attr = {};
// Draw the line
this.legendLine = renderer.path([
'M',
0,
verticalCenter,
'L',
symbolWidth,
verticalCenter
])
.addClass('highcharts-graph')
.attr(attr)
.add(legendItemGroup);
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = this.symbol.indexOf('url') === 0 ? 0 : markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius,
markerOptions
)
.addClass('highcharts-point')
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(win.navigator.userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function(proceed, item) {
var legend = this,
runPositionItem = function() { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
animObject = H.animObject,
attr = H.attr,
doc = H.doc,
Axis = H.Axis, // @todo add as requirement
createElement = H.createElement,
defaultOptions = H.defaultOptions,
discardElement = H.discardElement,
charts = H.charts,
css = H.css,
defined = H.defined,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
getStyle = H.getStyle,
grep = H.grep,
isNumber = H.isNumber,
isObject = H.isObject,
isString = H.isString,
Legend = H.Legend, // @todo add as requirement
marginNames = H.marginNames,
merge = H.merge,
Pointer = H.Pointer, // @todo add as requirement
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
seriesTypes = H.seriesTypes,
splat = H.splat,
svg = H.svg,
syncTimeout = H.syncTimeout,
win = H.win,
Renderer = H.Renderer;
/**
* The Chart class
* @param {String|Object} renderTo The DOM element to render to, or its id
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
var Chart = H.Chart = function() {
this.getArgs.apply(this, arguments);
};
H.chart = function(a, b, c) {
return new Chart(a, b, c);
};
Chart.prototype = {
/**
* Hook for modules
*/
callbacks: [],
/**
* Handle the arguments passed to the constructor
* @returns {Array} Arguments without renderTo
*/
getArgs: function() {
var args = [].slice.call(arguments);
// Remove the optional first argument, renderTo, and
// set it on this.
if (isString(args[0]) || args[0].nodeName) {
this.renderTo = args.shift();
}
this.init(args[0], args[1]);
},
/**
* Initialize the chart
*/
init: function(userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
this.userOptions = userOptions;
this.respRules = [];
var optionsChart = options.chart;
var chartEvents = optionsChart.events;
this.margin = [];
this.spacing = [];
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = {
h: {},
v: {}
}; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = undefined;
//chartSubtitleOptions = undefined;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = undefined;
//this.inverted = undefined;
//this.loadingShown = undefined;
//this.container = undefined;
//this.chartWidth = undefined;
//this.chartHeight = undefined;
//this.marginRight = undefined;
//this.marginBottom = undefined;
//this.containerWidth = undefined;
//this.containerHeight = undefined;
//this.oldChartWidth = undefined;
//this.oldChartHeight = undefined;
//this.renderTo = undefined;
//this.renderToClone = undefined;
//this.spacingBox = undefined
//this.legend = undefined;
// Elements
//this.chartBackground = undefined;
//this.plotBackground = undefined;
//this.plotBGImage = undefined;
//this.plotBorder = undefined;
//this.loadingDiv = undefined;
//this.loadingSpan = undefined;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
H.chartCount++;
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function(options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
Constr = seriesTypes[type];
// No such series type
if (!Constr) {
error(17, true);
}
series = new Constr();
series.init(this, options);
return series;
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function(plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function(animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
hasCartesianSeries = chart.hasCartesianSeries,
isDirtyBox = chart.isDirtyBox,
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
H.setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// Handle updated data in the series
each(series, function(serie) {
if (serie.isDirty) {
if (serie.options.legendType === 'point') {
if (serie.updateTotals) {
serie.updateTotals();
}
redrawLegend = true;
}
}
if (serie.isDirtyData) {
fireEvent(serie, 'updatedData');
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (hasCartesianSeries) {
// set axes scales
each(axes, function(axis) {
axis.updateNames();
axis.setScale();
});
}
chart.getMargins(); // #3098
if (hasCartesianSeries) {
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function(axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function(axis) {
// Fire 'afterSetExtremes' only if extremes are set
var key = axis.min + ',' + axis.max;
if (axis.extKey !== key) { // #821, #4452
axis.extKey = key;
afterRedraw.push(function() { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function(serie) {
if ((isDirtyBox || serie.isDirty) && serie.visible) {
serie.redraw();
}
});
// move tooltip or reset
if (pointer) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw');
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function(callback) {
callback.call();
});
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function(id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function() {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray;
// make sure the options are arrays and add some members
each(xAxisOptions, function(axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function(axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function(axisOptions) {
new Axis(chart, axisOptions); // eslint-disable-line no-new
});
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function() {
var points = [];
each(this.series, function(serie) {
points = points.concat(grep(serie.points || [], function(point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function() {
return grep(this.series, function(serie) {
return serie.selected;
});
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function(titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function(arr, i) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': 'highcharts-' + name,
zIndex: chartTitleOptions.zIndex || 4
})
.add();
// Update methods, shortcut to Chart.setTitle
chart[name].update = function(o) {
chart.setTitle(!i && o, i && o);
};
}
});
chart.layOutTitles(redraw);
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function(redraw) {
var titleOffset = 0,
requiresDirtyBox,
renderer = this.renderer,
spacingBox = this.spacingBox;
// Lay out the title and the subtitle respectively
each(['title', 'subtitle'], function(key) {
var title = this[key],
titleOptions = this.options[key],
titleSize;
if (title) {
titleSize = renderer.fontMetrics(titleSize, title).b;
title
.css({
width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + 'px'
})
.align(extend({
y: titleOffset + titleSize + (key === 'title' ? -3 : 2)
}, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = Math.ceil(titleOffset + title.getBBox().height);
}
}
}, this);
requiresDirtyBox = this.titleOffset !== titleOffset;
this.titleOffset = titleOffset; // used in getMargins
if (!this.isDirtyBox && requiresDirtyBox) {
this.isDirtyBox = requiresDirtyBox;
// Redraw if necessary (#2719, #2744)
if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
this.redraw();
}
}
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function() {
var chart = this,
optionsChart = chart.options.chart,
widthOption = optionsChart.width,
heightOption = optionsChart.height,
renderTo = chart.renderToClone || chart.renderTo;
// Get inner width and height
if (!defined(widthOption)) {
chart.containerWidth = getStyle(renderTo, 'width');
}
if (!defined(heightOption)) {
chart.containerHeight = getStyle(renderTo, 'height');
}
chart.chartWidth = Math.max(0, widthOption || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = Math.max(0, pick(heightOption,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function(revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
while (clone.childNodes.length) { // #5231
this.renderTo.appendChild(clone.firstChild);
}
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: 'absolute',
top: '-9999px',
display: 'block' // #833
});
if (clone.style.setProperty) { // #2631
clone.style.setProperty('display', 'block', 'important');
}
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Setter for the chart class name
*/
setClassName: function(className) {
this.container.className = 'highcharts-container ' + (className || '');
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function() {
var chart = this,
container,
options = chart.options,
optionsChart = options.chart,
chartWidth,
chartHeight,
renderTo = chart.renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
Ren,
containerId = 'highcharts-' + H.idCounter++,
containerStyle,
key;
if (!renderTo) {
chart.renderTo = renderTo = optionsChart.renderTo;
}
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it. The check for hasRendered is there
// because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
// attribute and the SVG contents, but not an interactive chart. So in this case,
// charts[oldChartIndex] will point to the wrong chart if any (#2609).
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly. The allowClone option is used in sparklines as a micro optimization,
// saving about 1-2 ms each chart.
if (!optionsChart.skipClone && !renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// Create the inner container
chart.container = container = createElement(
'div', {
id: containerId
},
containerStyle,
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
// Initialize the renderer
Ren = H[optionsChart.renderer] || Renderer;
chart.renderer = new Ren(
container,
chartWidth,
chartHeight,
null,
optionsChart.forExport,
options.exporting && options.exporting.allowHTML
);
chart.setClassName(optionsChart.className);
// Initialize definitions
for (key in options.defs) {
this.renderer.definition(options.defs[key]);
}
// Add a reference to the charts index
chart.renderer.chartIndex = chart.index;
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function(skipAxes) {
var chart = this,
spacing = chart.spacing,
margin = chart.margin,
titleOffset = chart.titleOffset;
chart.resetMargins();
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = Math.max(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
if (chart.legend.display) {
chart.legend.adjustMargins(margin, spacing);
}
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
if (!skipAxes) {
this.getAxisMargins();
}
},
getAxisMargins: function() {
var chart = this,
axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
margin = chart.margin;
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function(axis) {
if (axis.visible) {
axis.getOffset();
}
});
}
// Add the axis offsets
each(marginNames, function(m, side) {
if (!defined(margin[side])) {
chart[m] += axisOffset[side];
}
});
chart.setChartSize();
},
/**
* Resize the chart to its container if size is not explicitly set
*/
reflow: function(e) {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
hasUserWidth = defined(optionsChart.width),
width = optionsChart.width || getStyle(renderTo, 'width'),
height = optionsChart.height || getStyle(renderTo, 'height'),
target = e ? e.target : win;
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(chart.reflowTimeout);
// When called from window.resize, e is set, else it's called directly (#2224)
chart.reflowTimeout = syncTimeout(function() {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(undefined, undefined, false);
}
}, e ? 100 : 0);
}
chart.containerWidth = width;
chart.containerHeight = height;
}
},
/**
* Add the event handlers necessary for auto resizing
*/
initReflow: function() {
var chart = this,
reflow = function(e) {
chart.reflow(e);
};
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function() {
removeEvent(win, 'resize', reflow);
});
// The following will add listeners to re-fit the chart before and after
// printing (#2284). However it only works in WebKit. Should have worked
// in Firefox, but not supported in IE.
/*
if (win.matchMedia) {
win.matchMedia('print').addListener(function reflow() {
chart.reflow();
});
}
*/
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function(width, height, animation) {
var chart = this,
renderer = chart.renderer,
globalAnimation;
// Handle the isResizing counter
chart.isResizing += 1;
// set the animation for the current process
H.setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (width !== undefined) {
chart.options.chart.width = width;
}
if (height !== undefined) {
chart.options.chart.height = height;
}
chart.getChartSize();
// Resize the container with the global animation applied if enabled (#2503)
chart.setChartSize(true);
renderer.setSize(chart.chartWidth, chart.chartHeight, animation);
// handle axes
each(chart.axes, function(axis) {
axis.isDirty = true;
axis.setScale();
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
if (chart.setResponsive) {
chart.setResponsive(false);
}
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// Fire endResize and set isResizing back. If animation is disabled, fire without delay
syncTimeout(function() {
if (chart) {
fireEvent(chart, 'endResize', null, function() {
chart.isResizing -= 1;
});
}
}, animObject(globalAnimation).duration);
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function(skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = Math.round(chart.plotLeft);
chart.plotTop = plotTop = Math.round(chart.plotTop);
chart.plotWidth = plotWidth = Math.max(0, Math.round(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = Math.max(0, Math.round(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * Math.floor(chart.plotBorderWidth / 2);
clipX = Math.ceil(Math.max(plotBorderWidth, clipOffset[3]) / 2);
clipY = Math.ceil(Math.max(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: Math.floor(chart.plotSizeX - Math.max(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: Math.max(0, Math.floor(chart.plotSizeY - Math.max(plotBorderWidth, clipOffset[2]) / 2 - clipY))
};
if (!skipAxes) {
each(chart.axes, function(axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function() {
var chart = this,
chartOptions = chart.options.chart;
// Create margin and spacing array
each(['margin', 'spacing'], function splashArrays(target) {
var value = chartOptions[target],
values = isObject(value) ? value : [value, value, value, value];
each(['Top', 'Right', 'Bottom', 'Left'], function(sideName, side) {
chart[target][side] = pick(chartOptions[target + sideName], values[side]);
});
});
// Set margin names like chart.plotTop, chart.plotLeft, chart.marginRight, chart.marginBottom.
each(marginNames, function(m, side) {
chart[m] = pick(chart.margin[side], chart.spacing[side]);
});
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function() {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
chartBorderWidth,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox,
verb = 'animate';
// Chart area
if (!chartBackground) {
chart.chartBackground = chartBackground = renderer.rect()
.addClass('highcharts-background')
.add();
verb = 'attr';
}
chartBorderWidth = mgn = chartBackground.strokeWidth();
chartBackground[verb]({
x: mgn / 2,
y: mgn / 2,
width: chartWidth - mgn - chartBorderWidth % 2,
height: chartHeight - mgn - chartBorderWidth % 2,
r: optionsChart.borderRadius
});
// Plot background
verb = 'animate';
if (!plotBackground) {
verb = 'attr';
chart.plotBackground = plotBackground = renderer.rect()
.addClass('highcharts-plot-background')
.add();
}
plotBackground[verb](plotBox);
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
verb = 'animate';
if (!plotBorder) {
verb = 'attr';
chart.plotBorder = plotBorder = renderer.rect()
.addClass('highcharts-plot-border')
.attr({
zIndex: 1 // Above the grid
})
.add();
}
plotBorder[verb](plotBorder.crisp({
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
}, -plotBorder.strokeWidth())); //#3282 plotBorder should be negative;
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.inverted property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function() {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function(key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value =
optionsChart[key] || // It is set in the options
(klass && klass.prototype[key]); // The default series class requires it
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function() {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function(series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function(series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
}
}
});
},
/**
* Render series for the chart
*/
renderSeries: function() {
each(this.series, function(serie) {
serie.translate();
serie.render();
});
},
/**
* Render labels for the chart
*/
renderLabels: function() {
var chart = this,
labels = chart.options.labels;
if (labels.items) {
each(labels.items, function(label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
chart.renderer.text(
label.html,
x,
y
)
.attr({
zIndex: 2
})
.css(style)
.add();
});
}
},
/**
* Render all graphics for the chart
*/
render: function() {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options,
tempWidth,
tempHeight,
redoHorizontal,
redoVertical;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
// Get stacks
if (chart.getStacks) {
chart.getStacks();
}
// Get chart margins
chart.getMargins(true);
chart.setChartSize();
// Record preliminary dimensions for later comparison
tempWidth = chart.plotWidth;
tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels
// Get margins by pre-rendering axes
each(axes, function(axis) {
axis.setScale();
});
chart.getAxisMargins();
// If the plot area size has changed significantly, calculate tick positions again
redoHorizontal = tempWidth / chart.plotWidth > 1.1;
redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive
if (redoHorizontal || redoVertical) {
each(axes, function(axis) {
if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
axis.setTickInterval(true); // update to reflect the new margins
}
});
chart.getMargins(); // second pass to check for new labels
}
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function(axis) {
if (axis.visible) {
axis.render();
}
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({
zIndex: 3
})
.add();
}
chart.renderSeries();
// Labels
chart.renderLabels();
// Credits
chart.addCredits();
// Handle responsiveness
if (chart.setResponsive) {
chart.setResponsive();
}
// Set flag
chart.hasRendered = true;
},
/**
* Show chart credits based on config options
*/
addCredits: function(credits) {
var chart = this;
credits = merge(true, this.options.credits, credits);
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text + (this.mapCredits || ''),
0,
0
)
.addClass('highcharts-credits')
.on('click', function() {
if (credits.href) {
win.location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.add()
.align(credits.position);
// Dynamically update
this.credits.update = function(options) {
chart.credits = chart.credits.destroy();
chart.addCredits(options);
};
}
},
/**
* Clean up memory usage
*/
destroy: function() {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = undefined;
H.chartCount--;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy scroller & scroller series before destroying base series
if (this.scroller && this.scroller.destroy) {
this.scroller.destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'
], function(name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function() {
var chart = this;
// Note: win == win.top is required
if ((!svg && (win == win.top && doc.readyState !== 'complete'))) { // eslint-disable-line eqeqeq
doc.attachEvent('onreadystatechange', function() {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function() {
var chart = this,
options = chart.options;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function(serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
if (Pointer) {
chart.pointer = new Pointer(chart, options);
}
chart.render();
// add canvas
chart.renderer.draw();
// Fire the load event if there are no external images
if (!chart.renderer.imgCount && chart.onload) {
chart.onload();
}
// If the chart was rendered outside the top container, put it back in (#3679)
chart.cloneRenderTo(true);
},
/**
* On chart load
*/
onload: function() {
// Run callbacks
each([this.callback].concat(this.callbacks), function(fn) {
if (fn && this.index !== undefined) { // Chart destroyed in its own callback (#3600)
fn.apply(this, [this]);
}
}, this);
fireEvent(this, 'load');
// Set up auto resize
if (this.options.chart.reflow !== false) {
this.initReflow();
}
// Don't run again
this.onload = null;
}
}; // end Chart
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Point,
each = H.each,
extend = H.extend,
erase = H.erase,
fireEvent = H.fireEvent,
format = H.format,
isArray = H.isArray,
isNumber = H.isNumber,
pick = H.pick,
removeEvent = H.removeEvent;
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
Point = H.Point = function() {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function(series, options, x) {
var point = this,
colors,
colorCount = series.chart.options.chart.colorCount,
colorIndex;
point.series = series;
point.applyOptions(options, x);
if (series.options.colorByPoint) {
colorIndex = series.colorCounter;
series.colorCounter++;
// loop back to zero
if (series.colorCounter === colorCount) {
series.colorCounter = 0;
}
} else {
colorIndex = series.colorIndex;
}
point.colorIndex = pick(point.colorIndex, colorIndex);
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function(options, x) {
var point = this,
series = point.series,
pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// Since options are copied into the Point instance, some accidental options must be shielded (#5681)
if (options.group) {
delete point.group;
}
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
point.isNull = pick(
point.isValid && !point.isValid(),
point.x === null || !isNumber(point.y, true)
); // #3571, check for NaN
// The point is initially selected by options (#5777)
if (point.selected) {
point.state = 'select';
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) {
point.x = series.xAxis.nameToX(point);
}
if (point.x === undefined && series) {
if (x === undefined) {
point.x = series.autoIncrement(point);
} else {
point.x = x;
}
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function(options) {
var ret = {},
series = this.series,
keys = series.options.keys,
pointArrayMap = keys || series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (isNumber(options) || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (!keys && options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
if (!keys || options[i] !== undefined) { // Skip undefined positions for keys
ret[pointArrayMap[j]] = options[i];
}
i++;
j++;
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Get the CSS class names for individual points
* @returns {String} The class name
*/
getClassName: function() {
return 'highcharts-point' +
(this.selected ? ' highcharts-point-select' : '') +
(this.negative ? ' highcharts-negative' : '') +
(this.isNull ? ' highcharts-null-point' : '') +
(this.colorIndex !== undefined ? ' highcharts-color-' + this.colorIndex : '') +
(this.options.className ? ' ' + this.options.className : '');
},
/**
* Return the zone that the point belongs to
*/
getZone: function() {
var series = this.series,
zones = series.zones,
zoneAxis = series.zoneAxis || 'y',
i = 0,
zone;
zone = zones[i];
while (this[zoneAxis] >= zone.value) {
zone = zones[++i];
}
if (zone && zone.color && !this.options.color) {
this.color = zone.color;
}
return zone;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function() {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function() {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function() {
return {
x: this.category,
y: this.y,
color: this.color,
key: this.name || this.category,
series: this.series,
point: this,
percentage: this.percentage,
total: this.total || this.stackTotal
};
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function(pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function(key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Fire an event on the Point object.
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function(eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function(event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
if (point.select) { // Could be destroyed by prior event handlers (#2911)
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
}
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
},
visible: true
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
correctFloat = H.correctFloat,
Date = H.Date,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
defined = H.defined,
each = H.each,
erase = H.erase,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
grep = H.grep,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
LegendSymbolMixin = H.LegendSymbolMixin, // @todo add as a requirement
merge = H.merge,
pick = H.pick,
Point = H.Point, // @todo add as a requirement
removeEvent = H.removeEvent,
splat = H.splat,
stableSort = H.stableSort,
SVGElement = H.SVGElement,
syncTimeout = H.syncTimeout,
win = H.win;
/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
H.Series = H.seriesType('line', null, { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//clip: true,
//connectNulls: false,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
// stacking: null,
marker: {
//enabled: true,
//symbol: null,
radius: 4,
states: { // states for a single point
hover: {
animation: {
duration: 50
},
enabled: true,
radiusPlus: 2
}
}
},
point: {
events: {}
},
dataLabels: {
align: 'center',
// defer: true,
// enabled: false,
formatter: function() {
return this.y === null ? '' : H.numberFormat(this.y, -1);
},
/*style: {
color: 'contrast',
textShadow: '0 0 6px contrast, 0 0 3px contrast'
},*/
verticalAlign: 'bottom', // above singular point
x: 0,
y: 0,
// borderRadius: undefined,
padding: 5
},
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
softThreshold: true,
states: { // states for the entire series
hover: {
//enabled: false,
lineWidthPlus: 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
},
halo: {
size: 10
}
},
select: {
marker: {}
}
},
stickyTracking: true,
//tooltip: {
//pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
turboThreshold: 1000
// zIndex: null
// Prototype properties
}, {
isCartesian: true,
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
directTouch: false,
axisTypes: ['xAxis', 'yAxis'],
colorCounter: 0,
parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
coll: 'series',
init: function(chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function(a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: '',
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function(key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function(series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function() {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function(AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function(axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== undefined && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === undefined && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
},
/**
* For simple series types like line and column, the data values are held in arrays like
* xData and yData for quick lookup to find extremes and more. For multidimensional series
* like bubble and map, this can be extended with arrays like zData and valueData by
* adding to the series.parallelArrays array.
*/
updateParallelArrays: function(point, i) {
var series = point.series,
args = arguments,
fn = isNumber(i) ?
// Insert the value in the given position
function(key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function(key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function() {
var options = this.options,
xIncrement = this.xIncrement,
date,
pointInterval,
pointIntervalUnit = options.pointIntervalUnit;
xIncrement = pick(xIncrement, options.pointStart, 0);
this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
// Added code for pointInterval strings
if (pointIntervalUnit) {
date = new Date(xIncrement);
if (pointIntervalUnit === 'day') {
date = +date[Date.hcSetDate](date[Date.hcGetDate]() + pointInterval);
} else if (pointIntervalUnit === 'month') {
date = +date[Date.hcSetMonth](date[Date.hcGetMonth]() + pointInterval);
} else if (pointIntervalUnit === 'year') {
date = +date[Date.hcSetFullYear](date[Date.hcGetFullYear]() + pointInterval);
}
pointInterval = date - xIncrement;
}
this.xIncrement = xIncrement + pointInterval;
return xIncrement;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function(itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
userOptions = chart.userOptions || {},
userPlotOptions = userOptions.plotOptions || {},
typeOptions = plotOptions[this.type],
options,
zones;
this.userOptions = itemOptions;
// General series options take precedence over type options because otherwise, default
// type options like column.animation would be overwritten by the general option.
// But issues have been raised here (#3881), and the solution may be to distinguish
// between default option and userOptions like in the tooltip below.
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// The tooltip options are merged between global and series specific options
this.tooltipOptions = merge(
defaultOptions.tooltip,
defaultOptions.plotOptions[this.type].tooltip,
userOptions.tooltip,
userPlotOptions.series && userPlotOptions.series.tooltip,
userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
itemOptions.tooltip
);
// Delete marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
// Handle color zones
this.zoneAxis = options.zoneAxis;
zones = this.zones = (options.zones || []).slice();
if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
zones.push({
value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
className: 'highcharts-negative'
});
}
if (zones.length) { // Push one extra zone for the rest
if (defined(zones[zones.length - 1].value)) {
zones.push({
});
}
}
return options;
},
getCyclic: function(prop, value, defaults) {
var i,
userOptions = this.userOptions,
indexName = prop + 'Index',
counterName = prop + 'Counter',
len = defaults ? defaults.length : pick(this.chart.options.chart[prop + 'Count'], this.chart[prop + 'Count']),
setting;
if (!value) {
// Pick up either the colorIndex option, or the _colorIndex after Series.update()
setting = pick(userOptions[indexName], userOptions['_' + indexName]);
if (defined(setting)) { // after Series.update()
i = setting;
} else {
userOptions['_' + indexName] = i = this.chart[counterName] % len;
this.chart[counterName] += 1;
}
if (defaults) {
value = defaults[i];
}
}
// Set the colorIndex
if (i !== undefined) {
this[indexName] = i;
}
this[prop] = value;
},
/**
* Get the series' color
*/
getColor: function() {
this.getCyclic('color');
},
/**
* Get the series' symbol
*/
getSymbol: function() {
var seriesMarkerOption = this.options.marker;
this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
},
drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function(data, redraw, animation, updatePoints) {
var series = this,
oldData = series.points,
oldDataLength = (oldData && oldData.length) || 0,
dataLength,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
i,
turboThreshold = options.turboThreshold,
pt,
xData = this.xData,
yData = this.yData,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length;
data = data || [];
dataLength = data.length;
redraw = pick(redraw, true);
// If the point count is the same as is was, just run Point.update which is
// cheaper, allows animation, and keeps references to points.
if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
each(data, function(point, i) {
// .update doesn't exist on a linked, hidden series (#3709)
if (oldData[i].update && point !== options.data[i]) {
oldData[i].update(point, false, null, false);
}
});
} else {
// Reset properties
series.xIncrement = null;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// Update parallel arrays
each(this.parallelArrays, function(key) {
series[key + 'Data'].length = 0;
});
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
for (i = 0; i < dataLength; i++) {
xData[i] = this.autoIncrement();
yData[i] = data[i];
}
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== undefined) { // stray commas in oldIE
pt = {
series: series
};
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
series.updateParallelArrays(pt, i);
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = series.userOptions.data = data;
// destroy old points
i = oldDataLength;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = chart.isDirtyBox = true;
series.isDirtyData = !!oldData;
animation = false;
}
// Typically for pie series, points need to be processed and generated
// prior to rendering the legend
if (options.legendType === 'point') {
this.processData();
this.generatePoints();
}
if (redraw) {
chart.redraw(animation);
}
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function(force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599
isCartesian = series.isCartesian,
xExtremes,
val2lin = xAxis && xAxis.val2lin,
isLog = xAxis && xAxis.isLog,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
i = processedXData.length || 1;
while (--i) {
distance = isLog ?
val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) :
processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === undefined || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function(xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i,
j;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = Math.max(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (j = i; j < dataLength; j++) {
if (xData[j] > max) {
cropEnd = j + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function() {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
PointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== undefined) { // #970
data[cursor] = point = (new PointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new PointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
points[i].dataGroup = series.groupMap[i];
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = undefined; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function(yData) {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yDataLength,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
x,
y,
i,
j;
yData = yData || this.stackedYData || this.processedYData || [];
yDataLength = yData.length;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = arrayMin(activeYData);
this.dataMax = arrayMax(activeYData);
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function() {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold,
stackThreshold = options.startFromThreshold ? threshold : 0,
plotX,
plotY,
lastPlotX,
stackIndicator,
closestPointRangePx = Number.MAX_VALUE;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes (#3434)
if (yAxis.isLog && yValue !== null && yValue <= 0) {
point.isNull = true;
}
// Get the plotX translation
point.plotX = plotX = correctFloat( // #5236
Math.min(Math.max(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923
);
// Calculate the bottom y value for stacked series
if (stacking && series.visible && !point.isNull && stack && stack[xValue]) {
stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index);
pointStack = stack[xValue];
stackValues = pointStack.points[stackIndicator.key];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = pointStack.total && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
Math.min(Math.max(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
undefined;
point.isInside = plotY !== undefined && plotY >= 0 && plotY <= yAxis.len && // #3519
plotX >= 0 && plotX <= xAxis.len;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== undefined ?
categories[point.x] : point.x;
// Determine auto enabling of markers (#3635, #5099)
if (!point.isNull) {
if (lastPlotX !== undefined) {
closestPointRangePx = Math.min(closestPointRangePx, Math.abs(plotX - lastPlotX));
}
lastPlotX = plotX;
}
}
series.closestPointRangePx = closestPointRangePx;
},
/**
* Return the series points with null points filtered out
*/
getValidPoints: function(points, insideOnly) {
var chart = this.chart;
return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029
if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085
return false;
}
return !point.isNull;
});
},
/**
* Set the clipping for the series. For animated series it is called twice, first to initiate
* animating the clip then the second time without the animation to set the final clip.
*/
setClip: function(animation) {
var chart = this.chart,
options = this.options,
renderer = chart.renderer,
inverted = chart.inverted,
seriesClipBox = this.clipBox,
clipBox = seriesClipBox || chart.clipBox,
sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526
clipRect = chart[sharedClipKey],
markerClipRect = chart[sharedClipKey + 'm'];
// If a clipping rectangle with the same properties is currently present in the chart, use that.
if (!clipRect) {
// When animation is set, prepare the initial positions
if (animation) {
clipBox.width = 0;
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
// Create hashmap for series indexes
clipRect.count = {
length: 0
};
}
if (animation) {
if (!clipRect.count[this.index]) {
clipRect.count[this.index] = true;
clipRect.count.length += 1;
}
}
if (options.clip !== false) {
this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
this.markerGroup.clip(markerClipRect);
this.sharedClipKey = sharedClipKey;
}
// Remove the shared clipping rectangle when all series are shown
if (!animation) {
if (clipRect.count[this.index]) {
delete clipRect.count[this.index];
clipRect.count.length -= 1;
}
if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) {
if (!seriesClipBox) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}
}
},
/**
* Animate in the series
*/
animate: function(init) {
var series = this,
chart = series.chart,
clipRect,
animation = animObject(series.options.animation),
sharedClipKey;
// Initialize the animation. Set up the clipping rectangle.
if (init) {
series.setClip(animation);
// Run the animation
} else {
sharedClipKey = this.sharedClipKey;
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function() {
this.setClip();
fireEvent(this, 'afterAnimate');
},
/**
* Draw the markers
*/
drawPoints: function() {
var series = this,
points = series.points,
chart = series.chart,
plotY,
i,
point,
symbol,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
pointMarkerOptions,
hasPointMarker,
enabled,
isInside,
markerGroup = series.markerGroup,
xAxis = series.xAxis,
markerAttribs,
globallyEnabled = pick(
seriesMarkerOptions.enabled,
xAxis.isRadial ? true : null,
series.closestPointRangePx > 2 * seriesMarkerOptions.radius
);
if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
hasPointMarker = !!point.marker;
enabled = (globallyEnabled && pointMarkerOptions.enabled === undefined) || pointMarkerOptions.enabled;
isInside = point.isInside;
// only draw the point if y is defined
if (enabled && isNumber(plotY) && point.y !== null) {
// Shortcuts
symbol = pick(pointMarkerOptions.symbol, series.symbol);
point.hasImage = symbol.indexOf('url') === 0;
markerAttribs = series.markerAttribs(
point,
point.selected && 'select'
);
if (graphic) { // update
graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
.animate(markerAttribs);
} else if (isInside && (markerAttribs.width > 0 || point.hasImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height,
hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
)
.add(markerGroup);
}
if (graphic) {
graphic.addClass(point.getClassName(), true);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Get non-presentational attributes for the point.
*/
markerAttribs: function(point, state) {
var seriesMarkerOptions = this.options.marker,
seriesStateOptions,
pointOptions = point && point.options,
pointMarkerOptions = (pointOptions && pointOptions.marker) || {},
pointStateOptions,
radius = pick(
pointMarkerOptions.radius,
seriesMarkerOptions.radius
),
attribs;
// Handle hover and select states
if (state) {
seriesStateOptions = seriesMarkerOptions.states[state];
pointStateOptions = pointMarkerOptions.states &&
pointMarkerOptions.states[state];
radius = pick(
pointStateOptions && pointStateOptions.radius,
seriesStateOptions && seriesStateOptions.radius,
radius + (seriesStateOptions && seriesStateOptions.radiusPlus || 0)
);
}
if (point.hasImage) {
radius = 0; // and subsequently width and height is not set
}
attribs = {
x: Math.floor(point.plotX) - radius, // Math.floor for #1843
y: point.plotY - radius
};
if (radius) {
attribs.width = attribs.height = 2 * radius;
}
return attribs;
},
/**
* Clear DOM objects and free up memory
*/
destroy: function() {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(win.navigator.userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(series.axisTypes || [], function(AXIS) {
axis = series[AXIS];
if (axis && axis.series) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// Destroy all SVGElements associated to the series
for (prop in series) {
if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
}
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Get the graph path
*/
getGraphPath: function(points, nullsAsZeroes, connectCliffs) {
var series = this,
options = series.options,
step = options.step,
reversed,
graphPath = [],
xMap = [],
gap;
points = points || series.points;
// Bottom of a stack is reversed
reversed = points.reversed;
if (reversed) {
points.reverse();
}
// Reverse the steps (#5004)
step = {
right: 1,
center: 2
}[step] || (step && 3);
if (step && reversed) {
step = 4 - step;
}
// Remove invalid points, especially in spline (#5015)
if (options.connectNulls && !nullsAsZeroes && !connectCliffs) {
points = this.getValidPoints(points);
}
// Build the line
each(points, function(point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint = points[i - 1],
pathToPoint; // the path to this point from the previous
if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) {
gap = true; // ... and continue
}
// Line series, nullsAsZeroes is not handled
if (point.isNull && !defined(nullsAsZeroes) && i > 0) {
gap = !options.connectNulls;
// Area series, nullsAsZeroes is set
} else if (point.isNull && !nullsAsZeroes) {
gap = true;
} else {
if (i === 0 || gap) {
pathToPoint = ['M', point.plotX, point.plotY];
} else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
pathToPoint = series.getPointSpline(points, point, i);
} else if (step) {
if (step === 1) { // right
pathToPoint = [
'L',
lastPoint.plotX,
plotY
];
} else if (step === 2) { // center
pathToPoint = [
'L',
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
'L',
(lastPoint.plotX + plotX) / 2,
plotY
];
} else {
pathToPoint = [
'L',
plotX,
lastPoint.plotY
];
}
pathToPoint.push('L', plotX, plotY);
} else {
// normal line to next point
pathToPoint = [
'L',
plotX,
plotY
];
}
// Prepare for animation. When step is enabled, there are two path nodes for each x value.
xMap.push(point.x);
if (step) {
xMap.push(point.x);
}
graphPath.push.apply(graphPath, pathToPoint);
gap = false;
}
});
graphPath.xMap = xMap;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function() {
var series = this,
options = this.options,
graphPath = (this.gappedPath || this.getGraphPath).call(this),
props = [
[
'graph',
'highcharts-graph'
]
];
// Add the zone properties if any
each(this.zones, function(zone, i) {
props.push([
'zone-graph-' + i,
'highcharts-graph highcharts-zone-graph-' + i + ' ' + (zone.className || '')
]);
});
// Draw the graph
each(props, function(prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
graph.endX = graphPath.xMap;
graph.animate({
d: graphPath
});
} else if (graphPath.length) { // #1487
series[graphKey] = series.chart.renderer.path(graphPath)
.addClass(prop[1])
.attr({
zIndex: 1
}) // #1069
.add(series.group);
}
// Helpers for animation
if (graph) {
graph.startX = graphPath.xMap;
//graph.shiftUnit = options.step ? 2 : 1;
graph.isArea = graphPath.isArea; // For arearange animation
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
applyZones: function() {
var series = this,
chart = this.chart,
renderer = chart.renderer,
zones = this.zones,
translatedFrom,
translatedTo,
clips = this.clips || [],
clipAttr,
graph = this.graph,
area = this.area,
chartSizeMax = Math.max(chart.chartWidth, chart.chartHeight),
axis = this[(this.zoneAxis || 'y') + 'Axis'],
extremes,
reversed,
inverted = chart.inverted,
horiz,
pxRange,
pxPosMin,
pxPosMax,
ignoreZones = false;
if (zones.length && (graph || area) && axis && axis.min !== undefined) {
reversed = axis.reversed;
horiz = axis.horiz;
// The use of the Color Threshold assumes there are no gaps
// so it is safe to hide the original graph and area
if (graph) {
graph.hide();
}
if (area) {
area.hide();
}
// Create the clips
extremes = axis.getExtremes();
each(zones, function(threshold, i) {
translatedFrom = reversed ?
(horiz ? chart.plotWidth : 0) :
(horiz ? 0 : axis.toPixels(extremes.min));
translatedFrom = Math.min(Math.max(pick(translatedTo, translatedFrom), 0), chartSizeMax);
translatedTo = Math.min(Math.max(Math.round(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);
if (ignoreZones) {
translatedFrom = translatedTo = axis.toPixels(extremes.max);
}
pxRange = Math.abs(translatedFrom - translatedTo);
pxPosMin = Math.min(translatedFrom, translatedTo);
pxPosMax = Math.max(translatedFrom, translatedTo);
if (axis.isXAxis) {
clipAttr = {
x: inverted ? pxPosMax : pxPosMin,
y: 0,
width: pxRange,
height: chartSizeMax
};
if (!horiz) {
clipAttr.x = chart.plotHeight - clipAttr.x;
}
} else {
clipAttr = {
x: 0,
y: inverted ? pxPosMax : pxPosMin,
width: chartSizeMax,
height: pxRange
};
if (horiz) {
clipAttr.y = chart.plotWidth - clipAttr.y;
}
}
if (clips[i]) {
clips[i].animate(clipAttr);
} else {
clips[i] = renderer.clipRect(clipAttr);
if (graph) {
series['zone-graph-' + i].clip(clips[i]);
}
if (area) {
series['zone-area-' + i].clip(clips[i]);
}
}
// if this zone extends out of the axis, ignore the others
ignoreZones = threshold.value > extremes.max;
});
this.clips = clips;
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function(inverted) {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function(groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert(inverted);
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function() {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(inverted); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function(prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
zIndex: zIndex || 0.1 // IE8 and pointer logic use this
})
.add(parent);
group.addClass('highcharts-series-' + this.index + ' highcharts-' + this.type + '-series highcharts-color-' + this.colorIndex +
' ' + (this.options.className || ''));
}
// Place it on first and subsequent (redraw) calls
group.attr({
visibility: visibility
})[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function() {
var chart = this.chart,
xAxis = this.xAxis,
yAxis = this.yAxis;
// Swap axes for inverted (#2339)
if (chart.inverted) {
xAxis = yAxis;
yAxis = this.xAxis;
}
return {
translateX: xAxis ? xAxis.left : chart.plotLeft,
translateY: yAxis ? yAxis.top : chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function() {
var series = this,
chart = series.chart,
group,
options = series.options,
// Animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration,
visibility = series.visible ? 'inherit' : 'hidden', // #2597
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup,
inverted = chart.inverted;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (animDuration) {
series.animate(true);
}
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.applyZones();
}
/* each(series.points, function (point) {
if (point.redraw) {
point.redraw();
}
});*/
// draw the data labels (inn pies they go before the points)
if (series.drawDataLabels) {
series.drawDataLabels();
}
// draw the points
if (series.visible) {
series.drawPoints();
}
// draw the mouse tracking area
if (series.drawTracker && series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
series.invertGroups(inverted);
// Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
group.clip(chart.clipRect);
}
// Run the animation
if (animDuration) {
series.animate();
}
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
if (!hasRendered) {
series.animationTimeout = syncTimeout(function() {
series.afterAnimate();
}, animDuration);
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function() {
var series = this,
chart = series.chart,
wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.render();
if (wasDirty) { // #3868, #3945
delete this.kdTree;
}
},
/**
* KD Tree && PointSearching Implementation
*/
kdDimensions: 1,
kdAxisArray: ['clientX', 'plotY'],
searchPoint: function(e, compareX) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
inverted = series.chart.inverted;
return this.searchKDTree({
clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
}, compareX);
},
buildKDTree: function() {
var series = this,
dimensions = series.kdDimensions;
// Internal function
function _kdtree(points, depth, dimensions) {
var axis,
median,
length = points && points.length;
if (length) {
// alternate between the axis
axis = series.kdAxisArray[depth % dimensions];
// sort point array
points.sort(function(a, b) {
return a[axis] - b[axis];
});
median = Math.floor(length / 2);
// build and return nod
return {
point: points[median],
left: _kdtree(points.slice(0, median), depth + 1, dimensions),
right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
};
}
}
// Start the recursive build process with a clone of the points array and null points filtered out (#3873)
function startRecursive() {
series.kdTree = _kdtree(
series.getValidPoints(
null, !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511)
),
dimensions,
dimensions
);
}
delete series.kdTree;
// For testing tooltips, don't build async
syncTimeout(startRecursive, series.options.kdNow ? 0 : 1);
},
searchKDTree: function(point, compareX) {
var series = this,
kdX = this.kdAxisArray[0],
kdY = this.kdAxisArray[1],
kdComparer = compareX ? 'distX' : 'dist';
// Set the one and two dimensional distance on the point object
function setDistance(p1, p2) {
var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
r = (x || 0) + (y || 0);
p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
}
function _search(search, tree, depth, dimensions) {
var point = tree.point,
axis = series.kdAxisArray[depth % dimensions],
tdist,
sideA,
sideB,
ret = point,
nPoint1,
nPoint2;
setDistance(search, point);
// Pick side based on distance to splitting point
tdist = search[axis] - point[axis];
sideA = tdist < 0 ? 'left' : 'right';
sideB = tdist < 0 ? 'right' : 'left';
// End of tree
if (tree[sideA]) {
nPoint1 = _search(search, tree[sideA], depth + 1, dimensions);
ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
}
if (tree[sideB]) {
// compare distance to current best to splitting point to decide wether to check side B or not
if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
}
}
return ret;
}
if (!this.kdTree) {
this.buildKDTree();
}
if (this.kdTree) {
return _search(point,
this.kdTree, this.kdDimensions, this.kdDimensions);
}
}
}); // end Series prototype
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
Axis = H.Axis,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
erase = H.erase,
extend = H.extend,
fireEvent = H.fireEvent,
inArray = H.inArray,
isNumber = H.isNumber,
isObject = H.isObject,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
setAnimation = H.setAnimation,
splat = H.splat;
// Extend the Chart prototype for dynamic methods
extend(Chart.prototype, {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function(options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', {
options: options
}, function() {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function(options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
userOptions = merge(options, {
index: this[key].length,
isX: isX
});
new Axis(this, userOptions); // eslint-disable-line no-new
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(userOptions);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function(str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv,
loadingOptions = options.loading,
setLoadingSize = function() {
if (loadingDiv) {
css(loadingDiv, {
left: chart.plotLeft + 'px',
top: chart.plotTop + 'px',
width: chart.plotWidth + 'px',
height: chart.plotHeight + 'px'
});
}
};
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement('div', {
className: 'highcharts-loading highcharts-loading-hidden'
}, null, chart.container);
chart.loadingSpan = createElement(
'span', {
className: 'highcharts-loading-inner'
},
null,
loadingDiv
);
addEvent(chart, 'redraw', setLoadingSize); // #1080
}
loadingDiv.className = 'highcharts-loading';
// Update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
chart.loadingShown = true;
setLoadingSize();
},
/**
* Hide the loading layer
*/
hideLoading: function() {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
loadingDiv.className = 'highcharts-loading highcharts-loading-hidden';
}
this.loadingShown = false;
},
/**
* These properties cause isDirtyBox to be set to true when updating. Can be extended from plugins.
*/
propsRequireDirtyBox: ['backgroundColor', 'borderColor', 'borderWidth', 'margin', 'marginTop', 'marginRight',
'marginBottom', 'marginLeft', 'spacing', 'spacingTop', 'spacingRight', 'spacingBottom', 'spacingLeft',
'borderRadius', 'plotBackgroundColor', 'plotBackgroundImage', 'plotBorderColor', 'plotBorderWidth',
'plotShadow', 'shadow'
],
/**
* These properties cause all series to be updated when updating. Can be extended from plugins.
*/
propsRequireUpdateSeries: ['chart.polar', 'chart.ignoreHiddenSeries', 'chart.type', 'colors', 'plotOptions'],
/**
* Chart.update function that takes the whole options stucture.
*/
update: function(options, redraw) {
var key,
adders = {
credits: 'addCredits',
title: 'setTitle',
subtitle: 'setSubtitle'
},
optionsChart = options.chart,
updateAllAxes,
updateAllSeries,
newWidth,
newHeight;
// If the top-level chart option is present, some special updates are required
if (optionsChart) {
merge(true, this.options.chart, optionsChart);
// Setter function
if ('className' in optionsChart) {
this.setClassName(optionsChart.className);
}
if ('inverted' in optionsChart || 'polar' in optionsChart) {
this.propFromSeries(); // Parses options.chart.inverted and options.chart.polar together with the available series
updateAllAxes = true;
}
for (key in optionsChart) {
if (optionsChart.hasOwnProperty(key)) {
if (inArray('chart.' + key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
// Only dirty box
if (inArray(key, this.propsRequireDirtyBox) !== -1) {
this.isDirtyBox = true;
}
}
}
}
// Some option stuctures correspond one-to-one to chart objects that have
// update methods, for example
// options.credits => chart.credits
// options.legend => chart.legend
// options.title => chart.title
// options.tooltip => chart.tooltip
// options.subtitle => chart.subtitle
// options.navigator => chart.navigator
// options.scrollbar => chart.scrollbar
for (key in options) {
if (this[key] && typeof this[key].update === 'function') {
this[key].update(options[key], false);
// If a one-to-one object does not exist, look for an adder function
} else if (typeof this[adders[key]] === 'function') {
this[adders[key]](options[key]);
}
if (key !== 'chart' && inArray(key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
}
if (options.plotOptions) {
merge(true, this.options.plotOptions, options.plotOptions);
}
// Setters for collections. For axes and series, each item is referred by an id. If the
// id is not found, it defaults to the first item in the collection, so setting series
// without an id, will update the first series in the chart.
each(['xAxis', 'yAxis', 'series'], function(coll) {
if (options[coll]) {
each(splat(options[coll]), function(newOptions) {
var item = (defined(newOptions.id) && this.get(newOptions.id)) || this[coll][0];
if (item && item.coll === coll) {
item.update(newOptions, false);
}
}, this);
}
}, this);
if (updateAllAxes) {
each(this.axes, function(axis) {
axis.update({}, false);
});
}
// Certain options require the whole series structure to be thrown away
// and rebuilt
if (updateAllSeries) {
each(this.series, function(series) {
series.update({}, false);
});
}
// For loading, just update the options, do not redraw
if (options.loading) {
merge(true, this.options.loading, options.loading);
}
// Update size. Redraw is forced.
newWidth = optionsChart && optionsChart.width;
newHeight = optionsChart && optionsChart.height;
if ((isNumber(newWidth) && newWidth !== this.chartWidth) ||
(isNumber(newHeight) && newHeight !== this.chartHeight)) {
this.setSize(newWidth, newHeight);
} else if (pick(redraw, true)) {
this.redraw();
}
},
/**
* Setter function to allow use from chart.update
*/
setSubtitle: function(options) {
this.setTitle(undefined, options);
}
});
// extend the Point prototype for dynamic methods
extend(Point.prototype, {
/**
* Point.update with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
update: function(options, redraw, animation, runEvent) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
chart = series.chart,
seriesOptions = series.options;
redraw = pick(redraw, true);
function update() {
point.applyOptions(options);
// Update visuals
if (point.y === null && graphic) { // #4146
point.graphic = graphic.destroy();
}
if (isObject(options, true)) {
// Destroy so we can get new elements
if (graphic && graphic.element) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
}
}
if (options && options.dataLabels && point.dataLabel) { // #2468
point.dataLabel = point.dataLabel.destroy();
}
}
// record changes in the parallel arrays
i = point.index;
series.updateParallelArrays(point, i);
// Record the options to options.data. If there is an object from before,
// use point options, otherwise use raw options. (#4701)
seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.isDirtyLegend = true;
}
if (redraw) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of doing the update
if (runEvent === false) { // When called from setData
update();
} else {
point.firePointEvent('update', {
options: options
}, update);
}
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation) {
this.series.removePoint(inArray(this, this.series.data), redraw, animation);
}
});
// Extend the series prototype for dynamic methods
extend(Series.prototype, {
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function(options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
chart = series.chart,
names = series.xAxis && series.xAxis.names,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
xData = series.xData,
i,
x;
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = {
series: series
};
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
series.updateParallelArrays(point, i); // update it
if (names && point.name) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
series.updateParallelArrays(point, 'shift');
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw(animation); // Animation is set anyway on redraw, #5665
}
},
/**
* Remove a point (rendered or not), by index
*/
removePoint: function(i, redraw, animation) {
var series = this,
data = series.data,
point = data[i],
points = series.points,
chart = series.chart,
remove = function() {
if (points && points.length === data.length) { // #4935
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.updateParallelArrays(point || {
series: series
}, 'splice', i, 1);
if (point) {
point.destroy();
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
};
setAnimation(animation, chart);
redraw = pick(redraw, true);
// Fire the event with a default handler of removing the point
if (point) {
point.firePointEvent('remove', null, remove);
} else {
remove();
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation, withEvent) {
var series = this,
chart = series.chart;
function remove() {
// Destroy elements
series.destroy();
// Redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (pick(redraw, true)) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of removing the point
if (withEvent !== false) {
fireEvent(series, 'remove', null, remove);
} else {
remove();
}
},
/**
* Series.update with a new set of options
*/
update: function(newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
newType = newOptions.type || oldOptions.type || chart.options.chart.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// If we're changing type or zIndex, create new groups (#3380, #3404)
if ((newType && newType !== oldType) || newOptions.zIndex !== undefined) {
preserve.length = 0;
}
// Make sure groups are not destroyed (#3094)
each(preserve, function(prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, {
data: this.options.data
}, newOptions);
// Destroy the series and delete all properties. Reinsert all methods
// and properties from the new type prototype (#2270, #3719)
this.remove(false, null, false);
for (n in proto) {
this[n] = undefined;
}
extend(this, seriesTypes[newType || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function(prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
}
});
// Extend the Axis.prototype for dynamic methods
extend(Axis.prototype, {
/**
* Axis.update with a new options structure
*/
update: function(newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this.init(chart, extend(newOptions, {
events: undefined
}));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function(redraw) {
var chart = this.chart,
key = this.coll, // xAxis or yAxis
axisSeries = this.series,
i = axisSeries.length;
// Remove associated series (#2687)
while (i--) {
if (axisSeries[i]) {
axisSeries[i].remove(false);
}
}
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function(axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Update the axis title by options
*/
setTitle: function(newTitleOptions, redraw) {
this.update({
title: newTitleOptions
}, redraw);
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function(categories, redraw) {
this.update({
categories: categories
}, redraw);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var animObject = H.animObject,
color = H.color,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
stop = H.stop,
svg = H.svg;
/**
* The column series type
*/
seriesType('column', 'line', {
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
halo: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
softThreshold: false,
startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/
stickyTracking: false,
tooltip: {
distance: 6
},
threshold: 0,
// Prototype members
}, {
cropShoulder: 0,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function() {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function(otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis,
columnIndex;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === undefined) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = Math.min(
Math.abs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
pointWidth = Math.min(
options.maxPointWidth || xAxis.len,
pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))
),
pointPadding = (pointOffsetWidth - pointWidth) / 2,
colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
};
return series.columnMetrics;
},
/**
* Make the columns crisp. The edges are rounded to the nearest full pixel.
*/
crispCol: function(x, y, w, h) {
var chart = this.chart,
borderWidth = this.borderWidth,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1,
right,
bottom,
fromTop;
if (chart.inverted && chart.renderer.isVML) {
yCrisp += 1;
}
// Horizontal. We need to first compute the exact right edge, then round it
// and compute the width from there.
right = Math.round(x + w) + xCrisp;
x = Math.round(x) + xCrisp;
w = right - x;
// Vertical
bottom = Math.round(y + h) + yCrisp;
fromTop = Math.abs(y) <= 0.5 && bottom > 0.5; // #4504, #4656
y = Math.round(y) + yCrisp;
h = bottom - y;
// Top edges are exceptions
if (fromTop && h) { // #5146
y -= 1;
h += 1;
}
return {
x: x,
y: y,
width: w,
height: h
};
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function() {
var series = this,
chart = series.chart,
options = series.options,
dense = series.dense = series.closestPointRange * series.xAxis.transA < 2,
borderWidth = series.borderWidth = pick(
options.borderWidth,
dense ? 0 : 1 // #3635
),
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = Math.max(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset;
if (chart.inverted) {
translatedThreshold -= 0.5; // #3355
}
// When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
// columns to have individual sizes. When pointPadding is greater, we strive for equal-width
// columns (#2694).
if (options.pointPadding) {
seriesBarW = Math.ceil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
each(series.points, function(point) {
var yBottom = pick(point.yBottom, translatedThreshold),
safeDistance = 999 + Math.abs(yBottom),
plotY = Math.min(Math.max(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = Math.min(plotY, yBottom),
up,
barH = Math.max(plotY, yBottom) - barY;
// Handle options.minPointLength
if (Math.abs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
barY = Math.abs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (up ? minPointLength : 0); // #1485, #4051
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424, #3648)
point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH];
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = series.crispCol.apply(
series,
point.isNull ? [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from
[barX, barY, barW, barH]
);
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*/
drawGraph: function() {
this.group[this.dense ? 'addClass' : 'removeClass']('highcharts-dense-data');
},
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function() {
var series = this,
chart = this.chart,
options = series.options,
renderer = chart.renderer,
animationLimit = options.animationLimit || 250,
shapeArgs;
// draw the columns
each(series.points, function(point) {
var plotY = point.plotY,
graphic = point.graphic;
if (isNumber(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
if (graphic) { // update
stop(graphic);
graphic[chart.pointCount < animationLimit ? 'animate' : 'attr'](
merge(shapeArgs)
);
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr({
'class': point.getClassName()
})
.add(point.group || series.group);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function(init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (svg) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = Math.min(yAxis.pos + yAxis.len, Math.max(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, extend(animObject(series.options.animation), {
// Do the scale synchronously to ensure smooth updating (#5030)
step: function(val, fx) {
series.group.attr({
scaleY: Math.max(0.001, fx.pos) // #5250
});
}
}));
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function() {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Series = H.Series,
seriesType = H.seriesType;
/**
* The scatter series type
*/
seriesType('scatter', 'line', {
lineWidth: 0,
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
tooltip: {
headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 0.85em"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
// Prototype members
}, {
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false, // #2342
kdDimensions: 2,
drawGraph: function() {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
arrayMax = H.arrayMax,
defined = H.defined,
each = H.each,
extend = H.extend,
format = H.format,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
relativeLength = H.relativeLength,
Series = H.Series,
seriesTypes = H.seriesTypes,
stableSort = H.stableSort,
stop = H.stop;
/**
* Generatl distribution algorithm for distributing labels of differing size along a
* confined length in two dimensions. The algorithm takes an array of objects containing
* a size, a target and a rank. It will place the labels as close as possible to their
* targets, skipping the lowest ranked labels if necessary.
*/
H.distribute = function(boxes, len) {
var i,
overlapping = true,
origBoxes = boxes, // Original array will be altered with added .pos
restBoxes = [], // The outranked overshoot
box,
target,
total = 0;
function sortByTarget(a, b) {
return a.target - b.target;
}
// If the total size exceeds the len, remove those boxes with the lowest rank
i = boxes.length;
while (i--) {
total += boxes[i].size;
}
// Sort by rank, then slice away overshoot
if (total > len) {
stableSort(boxes, function(a, b) {
return (b.rank || 0) - (a.rank || 0);
});
i = 0;
total = 0;
while (total <= len) {
total += boxes[i].size;
i++;
}
restBoxes = boxes.splice(i - 1, boxes.length);
}
// Order by target
stableSort(boxes, sortByTarget);
// So far we have been mutating the original array. Now
// create a copy with target arrays
boxes = map(boxes, function(box) {
return {
size: box.size,
targets: [box.target]
};
});
while (overlapping) {
// Initial positions: target centered in box
i = boxes.length;
while (i--) {
box = boxes[i];
// Composite box, average of targets
target = (Math.min.apply(0, box.targets) + Math.max.apply(0, box.targets)) / 2;
box.pos = Math.min(Math.max(0, target - box.size / 2), len - box.size);
}
// Detect overlap and join boxes
i = boxes.length;
overlapping = false;
while (i--) {
if (i > 0 && boxes[i - 1].pos + boxes[i - 1].size > boxes[i].pos) { // Overlap
boxes[i - 1].size += boxes[i].size; // Add this size to the previous box
boxes[i - 1].targets = boxes[i - 1].targets.concat(boxes[i].targets);
// Overlapping right, push left
if (boxes[i - 1].pos + boxes[i - 1].size > len) {
boxes[i - 1].pos = len - boxes[i - 1].size;
}
boxes.splice(i, 1); // Remove this item
overlapping = true;
}
}
}
// Now the composite boxes are placed, we need to put the original boxes within them
i = 0;
each(boxes, function(box) {
var posInCompositeBox = 0;
each(box.targets, function() {
origBoxes[i].pos = box.pos + posInCompositeBox;
posInCompositeBox += origBoxes[i].size;
i++;
});
});
// Add the rest (hidden) boxes and sort by target
origBoxes.push.apply(origBoxes, restBoxes);
stableSort(origBoxes, sortByTarget);
};
/**
* Draw the data labels
*/
Series.prototype.drawDataLabels = function() {
var series = this,
seriesOptions = series.options,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
hasRendered = series.hasRendered || 0,
str,
dataLabelsGroup,
defer = pick(options.defer, true),
renderer = series.chart.renderer;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
defer && !hasRendered ? 'hidden' : 'visible', // #5133
options.zIndex || 6
);
if (defer) {
dataLabelsGroup.attr({
opacity: +hasRendered
}); // #3300
if (!hasRendered) {
addEvent(series, 'afterAnimate', function() {
if (series.visible) { // #2597, #3023, #3024
dataLabelsGroup.show(true);
}
dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({
opacity: 1
}, {
duration: 200
});
});
}
}
// Make the labels for each point
generalOptions = options;
each(points, function(point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true,
style,
moreStyle = {};
// Determine if each data label is enabled
pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
style = options.style;
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === undefined) {
delete attr[name];
}
}
dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0, -9999,
options.shape,
null,
null,
options.useHTML,
null,
'data-label'
)
.attr(attr);
dataLabel.addClass('highcharts-data-label-color-' + point.colorIndex + ' ' + (options.className || ''));
dataLabel.add(dataLabelsGroup);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
};
/**
* Align each individual data label
*/
Series.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -9999),
plotY = pick(point.plotY, -9999),
bBox = dataLabel.getBBox(),
fontSize,
baseline,
rotation = options.rotation,
normRotation,
negRotation,
align = options.align,
rotCorr, // rotation correction
// Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, Math.round(plotY), inverted) ||
(alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
alignAttr, // the final position;
justify = pick(options.overflow, 'justify') === 'justify';
if (visible) {
baseline = chart.renderer.fontMetrics(fontSize, dataLabel).b;
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: Math.round(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (rotation) {
justify = false; // Not supported for rotated text
rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723
alignAttr = {
x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
y: alignTo.y + options.y + {
top: 0,
middle: 0.5,
bottom: 1
}[options.verticalAlign] * alignTo.height
};
dataLabel[isNew ? 'attr' : 'animate'](alignAttr)
.attr({ // #3003
align: align
});
// Compensate for the rotated label sticking out on the sides
normRotation = (rotation + 720) % 360;
negRotation = normRotation > 180 && normRotation < 360;
if (align === 'left') {
alignAttr.y -= negRotation ? bBox.height : 0;
} else if (align === 'center') {
alignAttr.x -= bBox.width / 2;
alignAttr.y -= bBox.height / 2;
} else if (align === 'right') {
alignAttr.x -= bBox.width;
alignAttr.y -= negRotation ? 0 : bBox.height;
}
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
}
// Handle justify or crop
if (justify) {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
// Now check that the data label is within the plot area
} else if (pick(options.crop, true)) {
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
// When we're using a shape, make it possible with a connector or an arrow pointing to thie point
if (options.shape && !rotation) {
dataLabel.attr({
anchorX: point.plotX,
anchorY: point.plotY
});
}
}
// Show or hide based on the final aligned position
if (!visible) {
stop(dataLabel);
dataLabel.attr({
y: -9999
});
dataLabel.placed = false; // don't animate back in
}
};
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
Series.prototype.justifyDataLabel = function(dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified,
padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
// Off left
off = alignAttr.x + padding;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width - padding;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y + padding;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height - padding;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
};
/**
* Override the base drawDataLabels method by pie specific functionality
*/
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawDataLabels = function() {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [ // divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
j,
overflow = [0, 0, 0, 0]; // top, right, bottom, left
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
each(data, function(point) {
if (point.dataLabel && point.visible) { // #407, #2510
// Arrange points for detection collision
halves[point.half].push(point);
// Reset positions (#4905)
point.dataLabel._pos = null;
}
});
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
each(halves, function(points, i) {
var top,
bottom,
length = points.length,
positions,
naturalY,
size;
if (!length) {
return;
}
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
top = Math.max(0, centerY - radius - distanceOption);
bottom = Math.min(centerY + radius + distanceOption, chart.plotHeight);
positions = map(points, function(point) {
if (point.dataLabel) {
size = point.dataLabel.getBBox().height || 21;
return {
target: point.labelPos[1] - top + size / 2,
size: size,
rank: point.y
};
}
});
H.distribute(positions, bottom + size - top);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? 'hidden' : 'inherit';
naturalY = labelPos[1];
if (positions) {
if (positions[j].pos === undefined) {
visibility = 'hidden';
} else {
labelHeight = positions[j].size;
y = top + positions[j].pos;
}
} else {
y = naturalY;
}
// get the x - use the natural x position for labels near the top and bottom, to prevent the top
// and botton slice connectors from touching each other on either side
if (options.justify) {
x = seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption);
} else {
x = series.getX(y < top + 2 || y > bottom - 2 ? naturalY : y, i);
}
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({
left: connectorPadding,
right: -connectorPadding
}[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
labelPos.x = x;
labelPos.y = y;
// Detect overflowing data labels
if (series.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = Math.max(Math.round(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = Math.max(Math.round(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = Math.max(Math.round(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = Math.max(Math.round(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
}); // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function(point) {
var isNew;
connector = point.connector;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos && point.visible) {
visibility = dataLabel._attr.visibility;
isNew = !connector;
if (isNew) {
point.connector = connector = chart.renderer.path()
.addClass('highcharts-data-label-connector highcharts-color-' + point.colorIndex)
.add(series.dataLabelsGroup);
}
connector[isNew ? 'attr' : 'animate']({
d: series.connectorPath(point.labelPos)
});
connector.attr('visibility', visibility);
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
};
/**
* Extendable method for getting the path of the connector between the data label
* and the pie slice.
*/
seriesTypes.pie.prototype.connectorPath = function(labelPos) {
var x = labelPos.x,
y = labelPos.y;
return pick(this.options.softConnector, true) ? [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
] : [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'L',
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
];
};
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
seriesTypes.pie.prototype.placeDataLabels = function() {
each(this.points, function(point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel && point.visible) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({
y: -9999
});
}
}
});
};
seriesTypes.pie.prototype.alignDataLabel = noop;
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
seriesTypes.pie.prototype.verifyDataLabelOverflow = function(overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = Math.max(center[2] - Math.max(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = Math.max(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = Math.max(Math.min(newSize, center[2] - Math.max(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = Math.max(
Math.min(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632
this.translate(center);
if (this.drawDataLabels) {
this.drawDataLabels();
}
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
};
}
if (seriesTypes.column) {
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
seriesTypes.column.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var inverted = this.chart.inverted,
series = point.series,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series
inside = pick(options.inside, !!this.options.stacking), // draw it inside the box?
overshoot;
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (alignTo.y < 0) {
alignTo.height += alignTo.y;
alignTo.y = 0;
}
overshoot = alignTo.y + alignTo.height - series.yAxis.len;
if (overshoot > 0) {
alignTo.height -= overshoot;
}
if (inverted) {
alignTo = {
x: series.yAxis.len - alignTo.y - alignTo.height,
y: series.xAxis.len - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align, !inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
};
}
}(Highcharts));
(function(H) {
/**
* (c) 2009-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/**
* Highcharts module to hide overlapping data labels. This module is included in Highcharts.
*/
var Chart = H.Chart,
each = H.each,
pick = H.pick,
addEvent = H.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function(chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function(series) {
var dlOptions = series.options.dataLabels,
collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
each(collections, function(coll) {
each(series.points, function(point) {
if (point[coll]) {
point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
labels.push(point[coll]);
}
});
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function(labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
isIntersecting,
pos1,
pos2,
parent1,
parent2,
padding,
intersectRect = function(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(
x2 > x1 + w1 ||
x2 + w2 < x1 ||
y2 > y1 + h1 ||
y2 + h2 < y1
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Prevent a situation in a gradually rising slope, that each label
// will hide the previous one because the previous one always has
// lower rank.
labels.sort(function(a, b) {
return (b.labelrank || 0) - (a.labelrank || 0);
});
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) {
pos1 = label1.alignAttr;
pos2 = label2.alignAttr;
parent1 = label1.parentGroup; // Different panes have different positions
parent2 = label2.parentGroup;
padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333)
isIntersecting = intersectRect(
pos1.x + parent1.translateX,
pos1.y + parent1.translateY,
label1.width - padding,
label1.height - padding,
pos2.x + parent2.translateX,
pos2.y + parent2.translateY,
label2.width - padding,
label2.height - padding
);
if (isIntersecting) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
}
// Hide or show
each(labels, function(label) {
var complete,
newOpacity;
if (label) {
newOpacity = label.newOpacity;
if (label.oldOpacity !== newOpacity && label.placed) {
// Make sure the label is completely hidden to avoid catching clicks (#4362)
if (newOpacity) {
label.show(true);
} else {
complete = function() {
label.hide();
};
}
// Animate or set the opacity
label.alignAttr.opacity = newOpacity;
label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
}
label.isOld = true;
}
});
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
each = H.each,
pick = H.pick,
wrap = H.wrap;
/**
* Override to use the extreme coordinates from the SVG shape, not the
* data values
*/
wrap(Axis.prototype, 'getSeriesExtremes', function(proceed) {
var isXAxis = this.isXAxis,
dataMin,
dataMax,
xData = [],
useMapGeometry;
// Remove the xData array and cache it locally so that the proceed method doesn't use it
if (isXAxis) {
each(this.series, function(series, i) {
if (series.useMapGeometry) {
xData[i] = series.xData;
series.xData = [];
}
});
}
// Call base to reach normal cartesian series (like mappoint)
proceed.call(this);
// Run extremes logic for map and mapline
if (isXAxis) {
dataMin = pick(this.dataMin, Number.MAX_VALUE);
dataMax = pick(this.dataMax, -Number.MAX_VALUE);
each(this.series, function(series, i) {
if (series.useMapGeometry) {
dataMin = Math.min(dataMin, pick(series.minX, dataMin));
dataMax = Math.max(dataMax, pick(series.maxX, dataMin));
series.xData = xData[i]; // Reset xData array
useMapGeometry = true;
}
});
if (useMapGeometry) {
this.dataMin = dataMin;
this.dataMax = dataMax;
}
}
});
/**
* Override axis translation to make sure the aspect ratio is always kept
*/
wrap(Axis.prototype, 'setAxisTranslation', function(proceed) {
var chart = this.chart,
mapRatio,
plotRatio = chart.plotWidth / chart.plotHeight,
adjustedAxisLength,
xAxis = chart.xAxis[0],
padAxis,
fixTo,
fixDiff,
preserveAspectRatio;
// Run the parent method
proceed.call(this);
// Check for map-like series
if (this.coll === 'yAxis' && xAxis.transA !== undefined) {
each(this.series, function(series) {
if (series.preserveAspectRatio) {
preserveAspectRatio = true;
}
});
}
// On Y axis, handle both
if (preserveAspectRatio) {
// Use the same translation for both axes
this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA);
mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min));
// What axis to pad to put the map in the middle
padAxis = mapRatio < 1 ? this : xAxis;
// Pad it
adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA;
padAxis.pixelPadding = padAxis.len - adjustedAxisLength;
padAxis.minPixelPadding = padAxis.pixelPadding / 2;
fixTo = padAxis.fixTo;
if (fixTo) {
fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true);
fixDiff *= padAxis.transA;
if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area
fixDiff = 0;
}
padAxis.minPixelPadding -= fixDiff;
}
}
});
/**
* Override Axis.render in order to delete the fixTo prop
*/
wrap(Axis.prototype, 'render', function(proceed) {
proceed.call(this);
this.fixTo = null;
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
Chart = H.Chart,
color = H.color,
ColorAxis,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
Legend = H.Legend,
LegendSymbolMixin = H.LegendSymbolMixin,
noop = H.noop,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
/**
* The ColorAxis object for inclusion in gradient legends
*/
ColorAxis = H.ColorAxis = function() {
this.init.apply(this, arguments);
};
extend(ColorAxis.prototype, Axis.prototype);
extend(ColorAxis.prototype, {
defaultColorAxisOptions: {
lineWidth: 0,
minPadding: 0,
maxPadding: 0,
gridLineWidth: 1,
tickPixelInterval: 72,
startOnTick: true,
endOnTick: true,
offset: 0,
marker: {
animation: {
duration: 50
},
width: 0.01
},
labels: {
overflow: 'justify'
},
minColor: '#e6ebf5',
maxColor: '#003399',
tickLength: 5,
showInLegend: true
},
init: function(chart, userOptions) {
var horiz = chart.options.legend.layout !== 'vertical',
options;
this.coll = 'colorAxis';
// Build the options
options = merge(this.defaultColorAxisOptions, {
side: horiz ? 2 : 1,
reversed: !horiz
}, userOptions, {
opposite: !horiz,
showEmpty: false,
title: null
});
Axis.prototype.init.call(this, chart, options);
// Base init() pushes it to the xAxis array, now pop it again
//chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
this.initDataClasses(userOptions);
}
this.initStops(userOptions);
// Override original axis properties
this.horiz = horiz;
this.zoomEnabled = false;
// Add default values
this.defaultLegendLength = 200;
},
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color.
* NOTE: Changes here should be copied
* to the same function in drilldown.src.js and solid-gauge-src.js.
*/
tweenColors: function(from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha,
ret;
// Unsupported color, return to-color (#3920)
if (!to.rgba.length || !from.rgba.length) {
ret = to.input || 'none';
// Interpolate
} else {
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
}
return ret;
},
initDataClasses: function(userOptions) {
var axis = this,
chart = this.chart,
dataClasses,
colorCounter = 0,
colorCount = chart.options.chart.colorCount,
options = this.options,
len = userOptions.dataClasses.length;
this.dataClasses = dataClasses = [];
this.legendItems = [];
each(userOptions.dataClasses, function(dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
dataClass.colorIndex = colorCounter;
// increase and loop back to zero
colorCounter++;
if (colorCounter === colorCount) {
colorCounter = 0;
}
} else {
dataClass.color = axis.tweenColors(
color(options.minColor),
color(options.maxColor),
len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
}
});
},
initStops: function(userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function(stop) {
stop.color = color(stop[1]);
});
},
/**
* Extend the setOptions method to process extreme colors and color
* stops.
*/
setOptions: function(userOptions) {
Axis.prototype.setOptions.call(this, userOptions);
this.options.crosshair = this.options.marker;
},
setAxisSize: function() {
var symbol = this.legendSymbol,
chart = this.chart,
legendOptions = chart.options.legend || {},
x,
y,
width,
height;
if (symbol) {
this.left = x = symbol.attr('x');
this.top = y = symbol.attr('y');
this.width = width = symbol.attr('width');
this.height = height = symbol.attr('height');
this.right = chart.chartWidth - x - width;
this.bottom = chart.chartHeight - y - height;
this.len = this.horiz ? width : height;
this.pos = this.horiz ? x : y;
} else {
// Fake length for disabled legend to avoid tick issues and such (#5205)
this.len = (this.horiz ? legendOptions.symbolWidth : legendOptions.symbolHeight) || this.defaultLegendLength;
}
},
/**
* Translate from a value to a color
*/
toColor: function(value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((from === undefined || value >= from) && (to === undefined || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
point.colorIndex = dataClass.colorIndex;
}
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / ((this.max - this.min) || 1));
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = this.tweenColors(
from.color,
to.color,
pos
);
}
return color;
},
/**
* Override the getOffset method to add the whole axis groups inside the legend.
*/
getOffset: function() {
var group = this.legendGroup,
sideOffset = this.chart.axisOffset[this.side];
if (group) {
// Hook for the getOffset method to add groups to this parent group
this.axisParent = group;
// Call the base
Axis.prototype.getOffset.call(this);
// First time only
if (!this.added) {
this.added = true;
this.labelLeft = 0;
this.labelRight = this.width;
}
// Reset it to avoid color axis reserving space
this.chart.axisOffset[this.side] = sideOffset;
}
},
/**
* Create the color gradient
*/
setLegendColor: function() {
var grad,
horiz = this.horiz,
options = this.options,
reversed = this.reversed,
one = reversed ? 1 : 0,
zero = reversed ? 0 : 1;
grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190
this.legendColor = {
linearGradient: {
x1: grad[0],
y1: grad[1],
x2: grad[2],
y2: grad[3]
},
stops: options.stops || [
[0, options.minColor],
[1, options.maxColor]
]
};
},
/**
* The color axis appears inside the legend and has its own legend symbol
*/
drawLegendSymbol: function(legend, item) {
var padding = legend.padding,
legendOptions = legend.options,
horiz = this.horiz,
width = pick(legendOptions.symbolWidth, horiz ? this.defaultLegendLength : 12),
height = pick(legendOptions.symbolHeight, horiz ? 12 : this.defaultLegendLength),
labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
itemDistance = pick(legendOptions.itemDistance, 10);
this.setLegendColor();
// Create the gradient
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
width,
height
).attr({
zIndex: 1
}).add(item.legendGroup);
// Set how much space this legend item takes up
this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding);
this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
},
/**
* Fool the legend
*/
setState: noop,
visible: true,
setVisible: noop,
getSeriesExtremes: function() {
var series;
if (this.series.length) {
series = this.series[0];
this.dataMin = series.valueMin;
this.dataMax = series.valueMax;
}
},
drawCrosshair: function(e, point) {
var plotX = point && point.plotX,
plotY = point && point.plotY,
crossPos,
axisPos = this.pos,
axisLen = this.len;
if (point) {
crossPos = this.toPixels(point[point.series.colorKey]);
if (crossPos < axisPos) {
crossPos = axisPos - 2;
} else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = this.len - crossPos;
Axis.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (this.cross) {
this.cross
.addClass('highcharts-coloraxis-marker')
.add(this.legendGroup);
}
}
},
getPlotLinePath: function(a, b, c, d, pos) {
return isNumber(pos) ? // crosshairs only // #3969 pos can be 0 !!
(this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z']) :
Axis.prototype.getPlotLinePath.call(this, a, b, c, d);
},
update: function(newOptions, redraw) {
var chart = this.chart,
legend = chart.legend;
each(this.series, function(series) {
series.isDirtyData = true; // Needed for Axis.update when choropleth colors change
});
// When updating data classes, destroy old items and make sure new ones are created (#3207)
if (newOptions.dataClasses && legend.allItems) {
each(legend.allItems, function(item) {
if (item.isDataClass) {
item.legendGroup.destroy();
}
});
chart.isDirtyLegend = true;
}
// Keep the options structure updated for export. Unlike xAxis and yAxis, the colorAxis is
// not an array. (#3207)
chart.options[this.coll] = merge(this.userOptions, newOptions);
Axis.prototype.update.call(this, newOptions, redraw);
if (this.legendItem) {
this.setLegendColor();
legend.colorizeItem(this, true);
}
},
/**
* Get the legend item symbols for data classes
*/
getDataClassLegendSymbols: function() {
var axis = this,
chart = this.chart,
legendItems = this.legendItems,
legendOptions = chart.options.legend,
valueDecimals = legendOptions.valueDecimals,
valueSuffix = legendOptions.valueSuffix || '',
name;
if (!legendItems.length) {
each(this.dataClasses, function(dataClass, i) {
var vis = true,
from = dataClass.from,
to = dataClass.to;
// Assemble the default name. This can be overridden by legend.options.labelFormatter
name = '';
if (from === undefined) {
name = '< ';
} else if (to === undefined) {
name = '> ';
}
if (from !== undefined) {
name += H.numberFormat(from, valueDecimals) + valueSuffix;
}
if (from !== undefined && to !== undefined) {
name += ' - ';
}
if (to !== undefined) {
name += H.numberFormat(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
visible: true,
setState: noop,
isDataClass: true,
setVisible: function() {
vis = this.visible = !vis;
each(axis.series, function(series) {
each(series.points, function(point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
},
name: '' // Prevents 'undefined' in legend in IE8
});
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function(prop) {
H.Fx.prototype[prop + 'Setter'] = function() {
this.elem.attr(prop, ColorAxis.prototype.tweenColors(color(this.start), color(this.end), this.pos));
};
});
/**
* Extend the chart getAxes method to also get the color axis
*/
wrap(Chart.prototype, 'getAxes', function(proceed) {
var options = this.options,
colorAxisOptions = options.colorAxis;
proceed.call(this);
this.colorAxis = [];
if (colorAxisOptions) {
new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new
}
});
/**
* Wrap the legend getAllItems method to add the color axis. This also removes the
* axis' own series to prevent them from showing up individually.
*/
wrap(Legend.prototype, 'getAllItems', function(proceed) {
var allItems = [],
colorAxis = this.chart.colorAxis[0];
if (colorAxis && colorAxis.options) {
if (colorAxis.options.showInLegend) {
// Data classes
if (colorAxis.options.dataClasses) {
allItems = allItems.concat(colorAxis.getDataClassLegendSymbols());
// Gradient legend
} else {
// Add this axis on top
allItems.push(colorAxis);
}
}
// Don't add the color axis' series
each(colorAxis.series, function(series) {
series.options.showInLegend = false;
});
}
return allItems.concat(proceed.call(this));
});
wrap(Legend.prototype, 'colorizeItem', function(proceed, item, visible) {
proceed.call(this, item, visible);
if (visible && item.legendColor) {
item.legendSymbol.attr({
fill: item.legendColor
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var defined = H.defined,
each = H.each,
noop = H.noop,
seriesTypes = H.seriesTypes;
/**
* Mixin for maps and heatmaps
*/
H.colorPointMixin = {
/**
* Color points have a value option that determines whether or not it is a null point
*/
isValid: function() {
return this.value !== null;
},
/**
* Set the visibility of a single point
*/
setVisible: function(vis) {
var point = this,
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel'], function(key) {
if (point[key]) {
point[key][method]();
}
});
}
};
H.colorSeriesMixin = {
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
/**
* In choropleth maps, the color is a result of the value, so this needs translation too
*/
translateColors: function() {
var series = this,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
each(this.data, function(point) {
var value = point[colorKey],
color;
color = point.options.color ||
(point.isNull ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color);
if (color) {
point.color = color;
}
});
},
/**
* Get the color attibutes to apply on the graphic
*/
colorAttribs: function(point) {
var ret = {};
if (defined(point.color)) {
ret[this.colorProp || 'fill'] = point.color;
}
return ret;
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
ColorAxis = H.ColorAxis,
colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
doc = H.doc,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
isArray = H.isArray,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes,
splat = H.splat;
// The vector-effect attribute is not supported in IE <= 11 (at least), so we need
// diffent logic (#3218)
var supportsVectorEffect = doc.documentElement.style.vectorEffect !== undefined;
/**
* The MapAreaPoint object
*/
/**
* Add the map series type
*/
seriesType('map', 'scatter', {
allAreas: true,
animation: false, // makes the complex shapes slow
nullColor: '#f7f7f7',
borderColor: '#cccccc',
borderWidth: 1,
marker: null,
stickyTracking: false,
joinBy: 'hc-key',
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true, // for the color
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0
},
turboThreshold: 0,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
brightness: 0.2,
halo: null
},
select: {
color: '#cccccc'
}
}
// Prototype members
}, merge(colorSeriesMixin, {
type: 'map',
supportsDrilldown: true,
getExtremesFromAll: true,
useMapGeometry: true, // get axis extremes from paths, not values
forceDL: true,
searchPoint: noop,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
preserveAspectRatio: true, // X axis and Y axis must have same translation slope
pointArrayMap: ['value'],
/**
* Get the bounding box of all paths in the map combined.
*/
getBox: function(paths) {
var MAX_VALUE = Number.MAX_VALUE,
maxX = -MAX_VALUE,
minX = MAX_VALUE,
maxY = -MAX_VALUE,
minY = MAX_VALUE,
minRange = MAX_VALUE,
xAxis = this.xAxis,
yAxis = this.yAxis,
hasBox;
// Find the bounding box
each(paths || [], function(point) {
if (point.path) {
if (typeof point.path === 'string') {
point.path = H.splitPath(point.path);
}
var path = point.path || [],
i = path.length,
even = false, // while loop reads from the end
pointMaxX = -MAX_VALUE,
pointMinX = MAX_VALUE,
pointMaxY = -MAX_VALUE,
pointMinY = MAX_VALUE,
properties = point.properties;
// The first time a map point is used, analyze its box
if (!point._foundBox) {
while (i--) {
if (isNumber(path[i])) {
if (even) { // even = x
pointMaxX = Math.max(pointMaxX, path[i]);
pointMinX = Math.min(pointMinX, path[i]);
} else { // odd = Y
pointMaxY = Math.max(pointMaxY, path[i]);
pointMinY = Math.min(pointMinY, path[i]);
}
even = !even;
}
}
// Cache point bounding box for use to position data labels, bubbles etc
point._midX = pointMinX + (pointMaxX - pointMinX) *
(point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed
point._midY = pointMinY + (pointMaxY - pointMinY) *
(point.middleY || (properties && properties['hc-middle-y']) || 0.5);
point._maxX = pointMaxX;
point._minX = pointMinX;
point._maxY = pointMaxY;
point._minY = pointMinY;
point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY));
point._foundBox = true;
}
maxX = Math.max(maxX, point._maxX);
minX = Math.min(minX, point._minX);
maxY = Math.max(maxY, point._maxY);
minY = Math.min(minY, point._minY);
minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange);
hasBox = true;
}
});
// Set the box for the whole series
if (hasBox) {
this.minY = Math.min(minY, pick(this.minY, MAX_VALUE));
this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE));
this.minX = Math.min(minX, pick(this.minX, MAX_VALUE));
this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE));
// If no minRange option is set, set the default minimum zooming range to 5 times the
// size of the smallest element
if (xAxis && xAxis.options.minRange === undefined) {
xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE);
}
if (yAxis && yAxis.options.minRange === undefined) {
yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE);
}
}
},
getExtremes: function() {
// Get the actual value extremes for colors
Series.prototype.getExtremes.call(this, this.valueData);
// Recalculate box on updated data
if (this.chart.hasRendered && this.isDirtyData) {
this.getBox(this.options.data);
}
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Extremes for the mock Y axis
this.dataMin = this.minY;
this.dataMax = this.maxY;
},
/**
* Translate the path so that it automatically fits into the plot area box
* @param {Object} path
*/
translatePath: function(path) {
var series = this,
even = false, // while loop reads from the end
xAxis = series.xAxis,
yAxis = series.yAxis,
xMin = xAxis.min,
xTransA = xAxis.transA,
xMinPixelPadding = xAxis.minPixelPadding,
yMin = yAxis.min,
yTransA = yAxis.transA,
yMinPixelPadding = yAxis.minPixelPadding,
i,
ret = []; // Preserve the original
// Do the translation
if (path) {
i = path.length;
while (i--) {
if (isNumber(path[i])) {
ret[i] = even ?
(path[i] - xMin) * xTransA + xMinPixelPadding :
(path[i] - yMin) * yTransA + yMinPixelPadding;
even = !even;
} else {
ret[i] = path[i];
}
}
}
return ret;
},
/**
* Extend setData to join in mapData. If the allAreas option is true, all areas
* from the mapData are used, and those that don't correspond to a data value
* are given null values.
*/
setData: function(data, redraw, animation, updatePoints) {
var options = this.options,
chartOptions = this.chart.options.chart,
globalMapData = chartOptions && chartOptions.map,
mapData = options.mapData,
joinBy = options.joinBy,
joinByNull = joinBy === null,
pointArrayMap = options.keys || this.pointArrayMap,
dataUsed = [],
mapMap = {},
mapPoint,
transform,
mapTransforms = this.chart.mapTransforms,
props,
i;
// Collect mapData from chart options if not defined on series
if (!mapData && globalMapData) {
mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData;
}
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
// Pick up numeric values, add index
// Convert Array point definitions to objects using pointArrayMap
if (data) {
each(data, function(val, i) {
var ix = 0;
if (isNumber(val)) {
data[i] = {
value: val
};
} else if (isArray(val)) {
data[i] = {};
// Automatically copy first item to hc-key if there is an extra leading string
if (!options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string') {
data[i]['hc-key'] = val[0];
++ix;
}
// Run through pointArrayMap and what's left of the point data array in parallel, copying over the values
for (var j = 0; j < pointArrayMap.length; ++j, ++ix) {
if (pointArrayMap[j]) {
data[i][pointArrayMap[j]] = val[ix];
}
}
}
if (joinByNull) {
data[i]._i = i;
}
});
}
this.getBox(data);
// Pick up transform definitions for chart
this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms;
// Cache cos/sin of transform rotation angle
if (mapTransforms) {
for (transform in mapTransforms) {
if (mapTransforms.hasOwnProperty(transform) && transform.rotation) {
transform.cosAngle = Math.cos(transform.rotation);
transform.sinAngle = Math.sin(transform.rotation);
}
}
}
if (mapData) {
if (mapData.type === 'FeatureCollection') {
this.mapTitle = mapData.title;
mapData = H.geojson(mapData, this.type, this);
}
this.mapData = mapData;
this.mapMap = {};
for (i = 0; i < mapData.length; i++) {
mapPoint = mapData[i];
props = mapPoint.properties;
mapPoint._i = i;
// Copy the property over to root for faster access
if (joinBy[0] && props && props[joinBy[0]]) {
mapPoint[joinBy[0]] = props[joinBy[0]];
}
mapMap[mapPoint[joinBy[0]]] = mapPoint;
}
this.mapMap = mapMap;
// Registered the point codes that actually hold data
if (data && joinBy[1]) {
each(data, function(point) {
if (mapMap[point[joinBy[1]]]) {
dataUsed.push(mapMap[point[joinBy[1]]]);
}
});
}
if (options.allAreas) {
this.getBox(mapData);
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
each(data, function(point) {
dataUsed.push(point[joinBy[1]]);
});
}
// Add those map points that don't correspond to data, which will be drawn as null points
dataUsed = '|' + map(dataUsed, function(point) {
return point && point[joinBy[0]];
}).join('|') + '|'; // String search is faster than array.indexOf
each(mapData, function(mapPoint) {
if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, {
value: null
}));
updatePoints = false; // #5050 - adding all areas causes the update optimization of setData to kick in, even though the point order has changed
}
});
} else {
this.getBox(dataUsed); // Issue #4784
}
}
Series.prototype.setData.call(this, data, redraw, animation, updatePoints);
},
/**
* No graph for the map series
*/
drawGraph: noop,
/**
* We need the points' bounding boxes in order to draw the data labels, so
* we skip it now and call it from drawPoints instead.
*/
drawDataLabels: noop,
/**
* Allow a quick redraw by just translating the area group. Used for zooming and panning
* in capable browsers.
*/
doFullTranslate: function() {
return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans;
},
/**
* Add the path option for data points. Find the max value for color calculation.
*/
translate: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
doFullTranslate = series.doFullTranslate();
series.generatePoints();
each(series.data, function(point) {
// Record the middle point (loosely based on centroid), determined
// by the middleX and middleY options.
point.plotX = xAxis.toPixels(point._midX, true);
point.plotY = yAxis.toPixels(point._midY, true);
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: series.translatePath(point.path)
};
}
});
series.translateColors();
},
/**
* Get presentational attributes
*/
pointAttribs: function(point, state) {
var attr = seriesTypes.column.prototype.pointAttribs.call(this, point, state);
// Prevent flickering whan called from setState
if (point.isFading) {
delete attr.fill;
}
// If vector-effect is not supported, we set the stroke-width on the group element
// and let all point graphics inherit. That way we don't have to iterate over all
// points to update the stroke-width on zooming. TODO: Check unstyled
if (supportsVectorEffect) {
attr['vector-effect'] = 'non-scaling-stroke';
} else {
attr['stroke-width'] = 'inherit';
}
return attr;
},
/**
* Use the drawPoints method of column, that is able to handle simple shapeArgs.
* Extend it by assigning the tooltip position.
*/
drawPoints: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
group = series.group,
chart = series.chart,
renderer = chart.renderer,
scaleX,
scaleY,
translateX,
translateY,
baseTrans = this.baseTrans;
// Set a group that handles transform during zooming and panning in order to preserve clipping
// on series.group
if (!series.transformGroup) {
series.transformGroup = renderer.g()
.attr({
scaleX: 1,
scaleY: 1
})
.add(group);
series.transformGroup.survive = true;
}
// Draw the shapes again
if (series.doFullTranslate()) {
// Individual point actions. TODO: Check unstyled.
// Draw them in transformGroup
series.group = series.transformGroup;
seriesTypes.column.prototype.drawPoints.apply(series);
series.group = group; // Reset
// Add class names
each(series.points, function(point) {
if (point.graphic) {
if (point.name) {
point.graphic.addClass('highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase());
}
if (point.properties && point.properties['hc-key']) {
point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase());
}
}
});
// Set the base for later scale-zooming. The originX and originY properties are the
// axis values in the plot area's upper left corner.
this.baseTrans = {
originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA,
originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA),
transAX: xAxis.transA,
transAY: yAxis.transA
};
// Reset transformation in case we're doing a full translate (#3789)
this.transformGroup.animate({
translateX: 0,
translateY: 0,
scaleX: 1,
scaleY: 1
});
// Just update the scale and transform for better performance
} else {
scaleX = xAxis.transA / baseTrans.transAX;
scaleY = yAxis.transA / baseTrans.transAY;
translateX = xAxis.toPixels(baseTrans.originX, true);
translateY = yAxis.toPixels(baseTrans.originY, true);
// Handle rounding errors in normal view (#3789)
if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) {
scaleX = 1;
scaleY = 1;
translateX = Math.round(translateX);
translateY = Math.round(translateY);
}
this.transformGroup.animate({
translateX: translateX,
translateY: translateY,
scaleX: scaleX,
scaleY: scaleY
});
}
// Set the stroke-width directly on the group element so the children inherit it. We need to use
// setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be
// set.
if (!supportsVectorEffect) {
series.group.element.setAttribute(
'stroke-width',
series.options[
(series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth'
] / (scaleX || 1)
);
}
this.drawMapDataLabels();
},
/**
* Draw the data labels. Special for maps is the time that the data labels are drawn (after points),
* and the clipping of the dataLabelsGroup.
*/
drawMapDataLabels: function() {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
},
/**
* Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo.
*/
render: function() {
var series = this,
render = Series.prototype.render;
// Give IE8 some time to breathe.
if (series.chart.renderer.isVML && series.data.length > 3000) {
setTimeout(function() {
render.call(series);
});
} else {
render.call(series);
}
},
/**
* The initial animation for the map series. By default, animation is disabled.
* Animation of map shapes is not at all supported in VML browsers.
*/
animate: function(init) {
var chart = this.chart,
animation = this.options.animation,
group = this.group,
xAxis = this.xAxis,
yAxis = this.yAxis,
left = xAxis.pos,
top = yAxis.pos;
if (chart.renderer.isSVG) {
if (animation === true) {
animation = {
duration: 1000
};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: left + xAxis.len / 2,
translateY: top + yAxis.len / 2,
scaleX: 0.001, // #1499
scaleY: 0.001
});
// Run the animation
} else {
group.animate({
translateX: left,
translateY: top,
scaleX: 1,
scaleY: 1
}, animation);
// Delete this function to allow it only once
this.animate = null;
}
}
},
/**
* Animate in the new series from the clicked point in the old series.
* Depends on the drilldown.js module
*/
animateDrilldown: function(init) {
var toBox = this.chart.plotBox,
level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1],
fromBox = level.bBox,
animationOptions = this.chart.options.drilldown.animation,
scale;
if (!init) {
scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height);
level.shapeArgs = {
scaleX: scale,
scaleY: scale,
translateX: fromBox.x,
translateY: fromBox.y
};
each(this.points, function(point) {
if (point.graphic) {
point.graphic
.attr(level.shapeArgs)
.animate({
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0
}, animationOptions);
}
});
this.animate = null;
}
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* When drilling up, pull out the individual point graphics from the lower series
* and animate them into the origin point in the upper series.
*/
animateDrillupFrom: function(level) {
seriesTypes.column.prototype.animateDrillupFrom.call(this, level);
},
/**
* When drilling up, keep the upper series invisible until the lower series has
* moved into place
*/
animateDrillupTo: function(init) {
seriesTypes.column.prototype.animateDrillupTo.call(this, init);
}
// Point class
}), extend({
/**
* Extend the Point object to split paths
*/
applyOptions: function(options, x) {
var point = Point.prototype.applyOptions.call(this, options, x),
series = this.series,
joinBy = series.joinBy,
mapPoint;
if (series.mapData) {
mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]];
if (mapPoint) {
// This applies only to bubbles
if (series.xyFromShape) {
point.x = mapPoint._midX;
point.y = mapPoint._midY;
}
extend(point, mapPoint); // copy over properties
} else {
point.value = point.value || null;
}
}
return point;
},
/**
* Stop the fade-out
*/
onMouseOver: function(e) {
clearTimeout(this.colorInterval);
if (this.value !== null) {
Point.prototype.onMouseOver.call(this, e);
} else { //#3401 Tooltip doesn't hide when hovering over null points
this.series.onMouseOut(e);
}
},
/**
* Zoom the chart to view a specific area point
*/
zoomTo: function() {
var point = this,
series = point.series;
series.xAxis.setExtremes(
point._minX,
point._maxX,
false
);
series.yAxis.setExtremes(
point._minY,
point._maxY,
false
);
series.chart.redraw();
}
}, colorPointMixin));
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
doc = H.doc,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
// Add events to the Chart object itself
extend(Chart.prototype, {
renderMapNavigation: function() {
var chart = this,
options = this.options.mapNavigation,
buttons = options.buttons,
n,
button,
buttonOptions,
attr,
states,
hoverStates,
selectStates,
outerHandler = function(e) {
this.handler.call(chart, e);
stopEvent(e); // Stop default click event (#4444)
};
if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) {
chart.mapNavButtons = [];
for (n in buttons) {
if (buttons.hasOwnProperty(n)) {
buttonOptions = merge(options.buttonOptions, buttons[n]);
button = chart.renderer.button(
buttonOptions.text,
0,
0,
outerHandler,
attr,
hoverStates,
selectStates,
0,
n === 'zoomIn' ? 'topbutton' : 'bottombutton'
)
.addClass('highcharts-map-navigation')
.attr({
width: buttonOptions.width,
height: buttonOptions.height,
title: chart.options.lang[n],
padding: buttonOptions.padding,
zIndex: 5
})
.add();
button.handler = buttonOptions.onclick;
button.align(extend(buttonOptions, {
width: button.width,
height: 2 * button.height
}), null, buttonOptions.alignTo);
addEvent(button.element, 'dblclick', stopEvent); // Stop double click event (#4444)
chart.mapNavButtons.push(button);
}
}
}
},
/**
* Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the
* outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places
* in Highcharts, perhaps it should be elevated to a common utility function.
*/
fitToBox: function(inner, outer) {
each([
['x', 'width'],
['y', 'height']
], function(dim) {
var pos = dim[0],
size = dim[1];
if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow
if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer
inner[size] = outer[size];
inner[pos] = outer[pos];
} else { // align right
inner[pos] = outer[pos] + outer[size] - inner[size];
}
}
if (inner[size] > outer[size]) {
inner[size] = outer[size];
}
if (inner[pos] < outer[pos]) {
inner[pos] = outer[pos];
}
});
return inner;
},
/**
* Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out.
*/
mapZoom: function(howMuch, centerXArg, centerYArg, mouseX, mouseY) {
/*if (this.isMapZooming) {
this.mapZoomQueue = arguments;
return;
}*/
var chart = this,
xAxis = chart.xAxis[0],
xRange = xAxis.max - xAxis.min,
centerX = pick(centerXArg, xAxis.min + xRange / 2),
newXRange = xRange * howMuch,
yAxis = chart.yAxis[0],
yRange = yAxis.max - yAxis.min,
centerY = pick(centerYArg, yAxis.min + yRange / 2),
newYRange = yRange * howMuch,
fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5,
fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5,
newXMin = centerX - newXRange * fixToX,
newYMin = centerY - newYRange * fixToY,
newExt = chart.fitToBox({
x: newXMin,
y: newYMin,
width: newXRange,
height: newYRange
}, {
x: xAxis.dataMin,
y: yAxis.dataMin,
width: xAxis.dataMax - xAxis.dataMin,
height: yAxis.dataMax - yAxis.dataMin
}),
zoomOut = newExt.x <= xAxis.dataMin &&
newExt.width >= xAxis.dataMax - xAxis.dataMin &&
newExt.y <= yAxis.dataMin &&
newExt.height >= yAxis.dataMax - yAxis.dataMin;
// When mousewheel zooming, fix the point under the mouse
if (mouseX) {
xAxis.fixTo = [mouseX - xAxis.pos, centerXArg];
}
if (mouseY) {
yAxis.fixTo = [mouseY - yAxis.pos, centerYArg];
}
// Zoom
if (howMuch !== undefined && !zoomOut) {
xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false);
yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false);
// Reset zoom
} else {
xAxis.setExtremes(undefined, undefined, false);
yAxis.setExtremes(undefined, undefined, false);
}
// Prevent zooming until this one is finished animating
/*chart.holdMapZoom = true;
setTimeout(function () {
chart.holdMapZoom = false;
}, 200);*/
/*delay = animation ? animation.duration || 500 : 0;
if (delay) {
chart.isMapZooming = true;
setTimeout(function () {
chart.isMapZooming = false;
if (chart.mapZoomQueue) {
chart.mapZoom.apply(chart, chart.mapZoomQueue);
}
chart.mapZoomQueue = null;
}, delay);
}*/
chart.redraw();
}
});
/**
* Extend the Chart.render method to add zooming and panning
*/
wrap(Chart.prototype, 'render', function(proceed) {
var chart = this,
mapNavigation = chart.options.mapNavigation;
// Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome.
chart.renderMapNavigation();
proceed.call(chart);
// Add the double click event
if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) {
addEvent(chart.container, 'dblclick', function(e) {
chart.pointer.onContainerDblClick(e);
});
}
// Add the mousewheel event
if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) {
addEvent(chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function(e) {
chart.pointer.onContainerMouseWheel(e);
stopEvent(e); // Issue #5011, returning false from non-jQuery event does not prevent default
return false;
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var extend = H.extend,
pick = H.pick,
Pointer = H.Pointer,
wrap = H.wrap;
// Extend the Pointer
extend(Pointer.prototype, {
/**
* The event handler for the doubleclick event
*/
onContainerDblClick: function(e) {
var chart = this.chart;
e = this.normalize(e);
if (chart.options.mapNavigation.enableDoubleClickZoomTo) {
if (chart.pointer.inClass(e.target, 'highcharts-tracker') && chart.hoverPoint) {
chart.hoverPoint.zoomTo();
}
} else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
0.5,
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
},
/**
* The event handler for the mouse scroll event
*/
onContainerMouseWheel: function(e) {
var chart = this.chart,
delta;
e = this.normalize(e);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
Math.pow(chart.options.mapNavigation.mouseWheelSensitivity, delta),
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
}
});
// Implement the pinchType option
wrap(Pointer.prototype, 'zoomOption', function(proceed) {
var mapNavigation = this.chart.options.mapNavigation;
proceed.apply(this, [].slice.call(arguments, 1));
// Pinch status
if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) {
this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true;
}
});
// Extend the pinchTranslate method to preserve fixed ratio when zooming
wrap(Pointer.prototype, 'pinchTranslate', function(proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
var xBigger;
proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
// Keep ratio
if (this.chart.options.chart.type === 'map' && this.hasZoom) {
xBigger = transform.scaleX > transform.scaleY;
this.pinchTranslateDirection(!xBigger,
pinchDown,
touches,
transform,
selectionMarker,
clip,
lastValidTouch,
xBigger ? transform.scaleX : transform.scaleY
);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapline series type
seriesType('mapline', 'map', {
}, {
type: 'mapline',
colorProp: 'stroke',
drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType;
// The mappoint series type
seriesType('mappoint', 'scatter', {
dataLabels: {
enabled: true,
formatter: function() { // #2945
return this.point.name;
},
crop: false,
defer: false,
overflow: false,
style: {
color: '#000000'
}
}
// Prototype members
}, {
type: 'mappoint',
forceDL: true
// Point class
}, {
applyOptions: function(options, x) {
var mergedOptions = options.lat !== undefined && options.lon !== undefined ? merge(options, this.series.chart.fromLatLonToPoint(options)) : options;
return Point.prototype.applyOptions.call(this, mergedOptions, x);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
Axis = H.Axis,
color = H.color,
each = H.each,
isNumber = H.isNumber,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
/* ****************************************************************************
* Start Bubble series code *
*****************************************************************************/
seriesType('bubble', 'scatter', {
dataLabels: {
formatter: function() { // #2945
return this.point.z;
},
inside: true,
verticalAlign: 'middle'
},
// displayNegative: true,
marker: {
// Avoid offset in Point.setState
radius: null,
states: {
hover: {
radiusPlus: 0
}
}
},
minSize: 8,
maxSize: '20%',
// negativeColor: null,
// sizeBy: 'area'
softThreshold: false,
states: {
hover: {
halo: {
size: 5
}
}
},
tooltip: {
pointFormat: '({point.x}, {point.y}), Size: {point.z}'
},
turboThreshold: 0,
zThreshold: 0,
zoneAxis: 'z'
// Prototype members
}, {
pointArrayMap: ['y', 'z'],
parallelArrays: ['x', 'y', 'z'],
trackerGroups: ['group', 'dataLabelsGroup'],
bubblePadding: true,
zoneAxis: 'z',
/**
* Get the radius for each point based on the minSize, maxSize and each point's Z value. This
* must be done prior to Series.translate because the axis needs to add padding in
* accordance with the point sizes.
*/
getRadii: function(zMin, zMax, minSize, maxSize) {
var len,
i,
pos,
zData = this.zData,
radii = [],
options = this.options,
sizeByArea = options.sizeBy !== 'width',
zThreshold = options.zThreshold,
zRange = zMax - zMin,
value,
radius;
// Set the shape type and arguments to be picked up in drawPoints
for (i = 0, len = zData.length; i < len; i++) {
value = zData[i];
// When sizing by threshold, the absolute value of z determines the size
// of the bubble.
if (options.sizeByAbsoluteValue && value !== null) {
value = Math.abs(value - zThreshold);
zMax = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold));
zMin = 0;
}
if (value === null) {
radius = null;
// Issue #4419 - if value is less than zMin, push a radius that's always smaller than the minimum size
} else if (value < zMin) {
radius = minSize / 2 - 1;
} else {
// Relative size, a number between 0 and 1
pos = zRange > 0 ? (value - zMin) / zRange : 0.5;
if (sizeByArea && pos >= 0) {
pos = Math.sqrt(pos);
}
radius = Math.ceil(minSize + pos * (maxSize - minSize)) / 2;
}
radii.push(radius);
}
this.radii = radii;
},
/**
* Perform animation on the bubbles
*/
animate: function(init) {
var animation = this.options.animation;
if (!init) { // run the animation
each(this.points, function(point) {
var graphic = point.graphic,
shapeArgs = point.shapeArgs;
if (graphic && shapeArgs) {
// start values
graphic.attr('r', 1);
// animate
graphic.animate({
r: shapeArgs.r
}, animation);
}
});
// delete this function to allow it only once
this.animate = null;
}
},
/**
* Extend the base translate method to handle bubble size
*/
translate: function() {
var i,
data = this.data,
point,
radius,
radii = this.radii;
// Run the parent method
seriesTypes.scatter.prototype.translate.call(this);
// Set the shape type and arguments to be picked up in drawPoints
i = data.length;
while (i--) {
point = data[i];
radius = radii ? radii[i] : 0; // #1737
if (isNumber(radius) && radius >= this.minPxSize / 2) {
// Shape arguments
point.shapeType = 'circle';
point.shapeArgs = {
x: point.plotX,
y: point.plotY,
r: radius
};
// Alignment box for the data label
point.dlBox = {
x: point.plotX - radius,
y: point.plotY - radius,
width: 2 * radius,
height: 2 * radius
};
} else { // below zThreshold
point.shapeArgs = point.plotY = point.dlBox = undefined; // #1691
}
}
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function(legend, item) {
var renderer = this.chart.renderer,
radius = renderer.fontMetrics(legend.itemStyle.fontSize).f / 2;
item.legendSymbol = renderer.circle(
radius,
legend.baseline - radius,
radius
).attr({
zIndex: 3
}).add(item.legendGroup);
item.legendSymbol.isMarker = true;
},
drawPoints: seriesTypes.column.prototype.drawPoints,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
buildKDTree: noop,
applyZones: noop
// Point class
}, {
haloPath: function() {
return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size);
},
ttBelow: false
});
/**
* Add logic to pad each axis with the amount of pixels
* necessary to avoid the bubbles to overflow.
*/
Axis.prototype.beforePadding = function() {
var axis = this,
axisLength = this.len,
chart = this.chart,
pxMin = 0,
pxMax = axisLength,
isXAxis = this.isXAxis,
dataKey = isXAxis ? 'xData' : 'yData',
min = this.min,
extremes = {},
smallestSize = Math.min(chart.plotWidth, chart.plotHeight),
zMin = Number.MAX_VALUE,
zMax = -Number.MAX_VALUE,
range = this.max - min,
transA = axisLength / range,
activeSeries = [];
// Handle padding on the second pass, or on redraw
each(this.series, function(series) {
var seriesOptions = series.options,
zData;
if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) {
// Correction for #1673
axis.allowZoomOutside = true;
// Cache it
activeSeries.push(series);
if (isXAxis) { // because X axis is evaluated first
// For each series, translate the size extremes to pixel values
each(['minSize', 'maxSize'], function(prop) {
var length = seriesOptions[prop],
isPercent = /%$/.test(length);
length = pInt(length);
extremes[prop] = isPercent ?
smallestSize * length / 100 :
length;
});
series.minPxSize = extremes.minSize;
series.maxPxSize = extremes.maxSize;
// Find the min and max Z
zData = series.zData;
if (zData.length) { // #1735
zMin = pick(seriesOptions.zMin, Math.min(
zMin,
Math.max(
arrayMin(zData),
seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE
)
));
zMax = pick(seriesOptions.zMax, Math.max(zMax, arrayMax(zData)));
}
}
}
});
each(activeSeries, function(series) {
var data = series[dataKey],
i = data.length,
radius;
if (isXAxis) {
series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize);
}
if (range > 0) {
while (i--) {
if (isNumber(data[i]) && axis.dataMin <= data[i] && data[i] <= axis.dataMax) {
radius = series.radii[i];
pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin);
pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax);
}
}
}
});
if (activeSeries.length && range > 0 && !this.isLog) {
pxMax -= axisLength;
transA *= (axisLength + pxMin - pxMax) / axisLength;
each([
['min', 'userMin', pxMin],
['max', 'userMax', pxMax]
], function(keys) {
if (pick(axis.options[keys[0]], axis[keys[1]]) === undefined) {
axis[keys[0]] += keys[2] / transA;
}
});
}
};
/* ****************************************************************************
* End Bubble series code *
*****************************************************************************/
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapbubble series type
if (seriesTypes.bubble) {
seriesType('mapbubble', 'bubble', {
animationLimit: 500,
tooltip: {
pointFormat: '{point.name}: {point.z}'
}
// Prototype members
}, {
xyFromShape: true,
type: 'mapbubble',
pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z
/**
* Return the map area identified by the dataJoinBy option
*/
getMapData: seriesTypes.map.prototype.getMapData,
getBox: seriesTypes.map.prototype.getBox,
setData: seriesTypes.map.prototype.setData
// Point class
}, {
applyOptions: function(options, x) {
var point;
if (options && options.lat !== undefined && options.lon !== undefined) {
point = Point.prototype.applyOptions.call(
this,
merge(options, this.series.chart.fromLatLonToPoint(options)),
x
);
} else {
point = seriesTypes.map.prototype.pointClass.prototype.applyOptions.call(this, options, x);
}
return point;
},
ttBelow: false
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
extend = H.extend,
error = H.error,
format = H.format,
merge = H.merge,
win = H.win,
wrap = H.wrap;
/**
* Test for point in polygon. Polygon defined as array of [x,y] points.
*/
function pointInPolygon(point, polygon) {
var i,
j,
rel1,
rel2,
c = false,
x = point.x,
y = point.y;
for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
rel1 = polygon[i][1] > y;
rel2 = polygon[j][1] > y;
if (rel1 !== rel2 && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) {
c = !c;
}
}
return c;
}
/**
* Get point from latLon using specified transform definition
*/
Chart.prototype.transformFromLatLon = function(latLon, transform) {
if (win.proj4 === undefined) {
error(21);
return {
x: 0,
y: null
};
}
var projected = win.proj4(transform.crs, [latLon.lon, latLon.lat]),
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected;
return {
x: ((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0),
y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0)
};
};
/**
* Get latLon from point using specified transform definition
*/
Chart.prototype.transformToLatLon = function(point, transform) {
if (win.proj4 === undefined) {
error(21);
return;
}
var normalized = {
x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0),
y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0)
},
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
// Note: Inverted sinAngle to reverse rotation direction
projected = win.proj4(transform.crs, 'WGS84', transform.rotation ? {
x: normalized.x * cosAngle + normalized.y * -sinAngle,
y: normalized.x * sinAngle + normalized.y * cosAngle
} : normalized);
return {
lat: projected.y,
lon: projected.x
};
};
Chart.prototype.fromPointToLatLon = function(point) {
var transforms = this.mapTransforms,
transform;
if (!transforms) {
error(22);
return;
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone &&
pointInPolygon({
x: point.x,
y: -point.y
}, transforms[transform].hitZone.coordinates[0])) {
return this.transformToLatLon(point, transforms[transform]);
}
}
return this.transformToLatLon(point, transforms['default']); // eslint-disable-line dot-notation
};
Chart.prototype.fromLatLonToPoint = function(latLon) {
var transforms = this.mapTransforms,
transform,
coords;
if (!transforms) {
error(22);
return {
x: 0,
y: null
};
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) {
coords = this.transformFromLatLon(latLon, transforms[transform]);
if (pointInPolygon({
x: coords.x,
y: -coords.y
}, transforms[transform].hitZone.coordinates[0])) {
return coords;
}
}
}
return this.transformFromLatLon(latLon, transforms['default']); // eslint-disable-line dot-notation
};
/**
* Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline).
*/
H.geojson = function(geojson, hType, series) {
var mapData = [],
path = [],
polygonToPath = function(polygon) {
var i,
len = polygon.length;
path.push('M');
for (i = 0; i < len; i++) {
if (i === 1) {
path.push('L');
}
path.push(polygon[i][0], -polygon[i][1]);
}
};
hType = hType || 'map';
each(geojson.features, function(feature) {
var geometry = feature.geometry,
type = geometry.type,
coordinates = geometry.coordinates,
properties = feature.properties,
point;
path = [];
if (hType === 'map' || hType === 'mapbubble') {
if (type === 'Polygon') {
each(coordinates, polygonToPath);
path.push('Z');
} else if (type === 'MultiPolygon') {
each(coordinates, function(items) {
each(items, polygonToPath);
});
path.push('Z');
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mapline') {
if (type === 'LineString') {
polygonToPath(coordinates);
} else if (type === 'MultiLineString') {
each(coordinates, polygonToPath);
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mappoint') {
if (type === 'Point') {
point = {
x: coordinates[0],
y: -coordinates[1]
};
}
}
if (point) {
mapData.push(extend(point, {
name: properties.name || properties.NAME,
properties: properties
}));
}
});
// Create a credits text that includes map source, to be picked up in Chart.addCredits
if (series && geojson.copyrightShort) {
series.chart.mapCredits = format(series.chart.options.credits.mapText, {
geojson: geojson
});
series.chart.mapCreditsFull = format(series.chart.options.credits.mapTextFull, {
geojson: geojson
});
}
return mapData;
};
/**
* Override addCredits to include map source by default
*/
wrap(Chart.prototype, 'addCredits', function(proceed, credits) {
credits = merge(true, this.options.credits, credits);
// Disable credits link if map credits enabled. This to allow for in-text anchors.
if (this.mapCredits) {
credits.href = null;
}
proceed.call(this, credits);
// Add full map credits to hover
if (this.credits && this.mapCreditsFull) {
this.credits.attr({
title: this.mapCreditsFull
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
defaultOptions = H.defaultOptions,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
Renderer = H.Renderer,
SVGRenderer = H.SVGRenderer,
VMLRenderer = H.VMLRenderer;
// Add language
extend(defaultOptions.lang, {
zoomIn: 'Zoom in',
zoomOut: 'Zoom out'
});
// Set the default map navigation options
defaultOptions.mapNavigation = {
buttonOptions: {
alignTo: 'plotBox',
align: 'left',
verticalAlign: 'top',
x: 0,
width: 18,
height: 18,
padding: 5
},
buttons: {
zoomIn: {
onclick: function() {
this.mapZoom(0.5);
},
text: '+',
y: 0
},
zoomOut: {
onclick: function() {
this.mapZoom(2);
},
text: '-',
y: 28
}
},
mouseWheelSensitivity: 1.1
// enabled: false,
// enableButtons: null, // inherit from enabled
// enableTouchZoom: null, // inherit from enabled
// enableDoubleClickZoom: null, // inherit from enabled
// enableDoubleClickZoomTo: false
// enableMouseWheelZoom: null, // inherit from enabled
};
/**
* Utility for reading SVG paths directly.
*/
H.splitPath = function(path) {
var i;
// Move letters apart
path = path.replace(/([A-Za-z])/g, ' $1 ');
// Trim
path = path.replace(/^\s*/, '').replace(/\s*$/, '');
// Split on spaces and commas
path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task
// Parse numbers
for (i = 0; i < path.length; i++) {
if (!/[a-zA-Z]/.test(path[i])) {
path[i] = parseFloat(path[i]);
}
}
return path;
};
// A placeholder for map definitions
H.maps = {};
// Create symbols for the zoom buttons
function selectiveRoundedRect(x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) {
return ['M', x + rTopLeft, y,
// top side
'L', x + w - rTopRight, y,
// top right corner
'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight,
// right side
'L', x + w, y + h - rBottomRight,
// bottom right corner
'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h,
// bottom side
'L', x + rBottomLeft, y + h,
// bottom left corner
'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft,
// left side
'L', x, y + rTopLeft,
// top left corner
'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y,
'Z'
];
}
SVGRenderer.prototype.symbols.topbutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0);
};
SVGRenderer.prototype.symbols.bottombutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r);
};
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
each(['topbutton', 'bottombutton'], function(shape) {
VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape];
});
}
/**
* A wrapper for Chart with all the default values for a Map
*/
H.Map = H.mapChart = function(a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
hiddenAxis = {
endOnTick: false,
visible: false,
minPadding: 0,
maxPadding: 0,
startOnTick: false
},
seriesOptions,
defaultCreditsOptions = H.getOptions().credits;
/* For visual testing
hiddenAxis.gridLineWidth = 1;
hiddenAxis.gridZIndex = 10;
hiddenAxis.tickPositions = undefined;
// */
// Don't merge the data
seriesOptions = options.series;
options.series = null;
options = merge({
chart: {
panning: 'xy',
type: 'map'
},
credits: {
mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'),
mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}')
},
xAxis: hiddenAxis,
yAxis: merge(hiddenAxis, {
reversed: true
})
},
options, // user's options
{ // forced options
chart: {
inverted: false,
alignTicks: false
}
}
);
options.series = seriesOptions;
return hasRenderToArg ?
new Chart(a, options, c) :
new Chart(options, b);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
each = H.each,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The Heatmap series type
seriesType('heatmap', 'scatter', {
animation: false,
borderWidth: 0,
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0 // #3837
},
marker: null,
pointRange: null, // dynamically set to colsize by default
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
halo: false, // #3406, halo is not required on heatmaps
brightness: 0.2
}
}
}, merge(colorSeriesMixin, {
pointArrayMap: ['y', 'value'],
hasPointSpecificOptions: true,
supportsDrilldown: true,
getExtremesFromAll: true,
directTouch: true,
/**
* Override the init method to add point ranges on both axes.
*/
init: function() {
var options;
seriesTypes.scatter.prototype.init.apply(this, arguments);
options = this.options;
options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData
this.yAxis.axisPointRange = options.rowsize || 1; // general point range
},
translate: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
between = function(x, a, b) {
return Math.min(Math.max(a, x), b);
};
series.generatePoints();
each(series.points, function(point) {
var xPad = (options.colsize || 1) / 2,
yPad = (options.rowsize || 1) / 2,
x1 = between(Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
x2 = between(Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
y1 = between(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len),
y2 = between(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len);
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = (x1 + x2) / 2;
point.plotY = (y1 + y2) / 2;
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
});
series.translateColors();
},
drawPoints: function() {
seriesTypes.column.prototype.drawPoints.call(this);
each(this.points, function(point) {
point.graphic.attr(this.colorAttribs(point, point.state));
}, this);
},
animate: noop,
getBox: noop,
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
getExtremes: function() {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.valueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
}
}), colorPointMixin);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
hasTouch = H.hasTouch,
inArray = H.inArray,
isObject = H.isObject,
Legend = H.Legend,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
svg = H.svg,
TrackerMixin;
/**
* TrackerMixin for points and graphs
*/
TrackerMixin = H.TrackerMixin = {
drawTrackerPoint: function() {
var series = this,
chart = series.chart,
pointer = chart.pointer,
onMouseOver = function(e) {
var target = e.target,
point;
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== undefined && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function(point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function(key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTrackerGraph: function() {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
i,
onMouseOver = function() {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === 'M') { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L');
}
if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
/*for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}*/
// draw the tracker
if (tracker) {
tracker.attr({
d: trackerPath
});
} else if (series.graph) { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? 'visible' : 'hidden',
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : 'none',
'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function(tracker) {
tracker.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
};
/* End TrackerMixin */
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
if (seriesTypes.column) {
seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.scatter) {
seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
/*
* Extend Legend for item events
*/
extend(Legend.prototype, {
setItemEvents: function(item, legendItem, useHTML) {
var legend = this,
chart = legend.chart,
activeClass = 'highcharts-legend-' + (item.series ? 'point' : 'series') + '-active';
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? legendItem : item.legendGroup).on('mouseover', function() {
item.setState('hover');
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.addClass(activeClass);
})
.on('mouseout', function() {
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.removeClass(activeClass);
item.setState();
})
.on('click', function(event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function() {
if (item.setVisible) {
item.setVisible();
}
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
},
createCheckboxForItem: function(item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function(event) {
var target = event.target;
fireEvent(
item.series || item,
'checkboxClick', { // #3712
checked: target.checked,
item: item
},
function() {
item.select();
}
);
});
}
});
/*
* Extend the Chart object with interaction
*/
extend(Chart.prototype, {
/**
* Display the zoom button
*/
showResetZoom: function() {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
function zoomOut() {
chart.zoomOut();
}
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.addClass('highcharts-reset-zoom')
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function() {
var chart = this;
fireEvent(chart, 'selection', {
resetSelection: true
}, function() {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function(event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function(axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function(axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function(e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function(isX) { // xy is used in maps
var axis = chart[isX ? 'xAxis' : 'yAxis'][0],
horiz = axis.horiz,
mousePos = e[horiz ? 'chartX' : 'chartY'],
mouseDown = horiz ? 'mouseDownX' : 'mouseDownY',
startPos = chart[mouseDown],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange,
goingLeft = startPos > mousePos; // #3613
if (axis.series.length &&
(goingLeft || newMin > Math.min(extremes.dataMin, extremes.min)) &&
(!goingLeft || newMax < Math.max(extremes.dataMax, extremes.max))) {
axis.setExtremes(newMin, newMax, false, false, {
trigger: 'pan'
});
doRedraw = true;
}
chart[mouseDown] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, {
cursor: 'move'
});
}
});
/*
* Extend the Point object with interaction
*/
extend(Point.prototype, {
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function(selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the default handler
point.firePointEvent(selected ? 'select' : 'unselect', {
accumulate: accumulate
}, function() {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && 'select');
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function(loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState('');
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*
* @param {Object} e The event arguments
* @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to
* actually hovered points. True for other points in shared tooltip.
*/
onMouseOver: function(e, byProximity) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
if (point.series) { // It may have been destroyed, #4130
// In shared tooltip, call mouse over when point/series is actually hovered: (#5766)
if (!byProximity) {
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
chart.hoverPoint = point;
}
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
// hover point only for non shared points: (#5766)
point.setState('hover');
tooltip.refresh(point, e);
} else if (!tooltip) {
point.setState('hover');
}
// trigger the event
point.firePointEvent('mouseOver');
}
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function() {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function() {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function(state, move) {
var point = this,
plotX = Math.floor(point.plotX), // #4586
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states[state] || {},
markerOptions = defaultPlotOptions[series.type].marker &&
series.options.marker,
normalDisabled = markerOptions && markerOptions.enabled === false,
markerStateOptions = (markerOptions && markerOptions.states &&
markerOptions.states[state]) || {},
stateDisabled = markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
halo = series.halo,
haloOptions,
markerAttribs,
newSymbol;
state = state || ''; // empty string
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== 'select') ||
// series' state options is disabled
(stateOptions.enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
if (markerOptions) {
markerAttribs = series.markerAttribs(point, state);
}
// Apply hover styles to the existing point
if (point.graphic) {
if (point.state) {
point.graphic.removeClass('highcharts-point-' + point.state);
}
if (state) {
point.graphic.addClass('highcharts-point-' + state);
}
/*attribs = radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {};*/
if (markerAttribs) {
point.graphic.animate(
markerAttribs,
pick(
chart.options.chart.animation, // Turn off globally
markerStateOptions.animation,
markerOptions.animation
)
);
}
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height
)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
} else {
stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
x: markerAttribs.x,
y: markerAttribs.y
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
stateMarkerGraphic.element.point = point; // #4310
}
}
// Show me your halo
haloOptions = stateOptions.halo;
if (haloOptions && haloOptions.size) {
if (!halo) {
series.halo = halo = chart.renderer.path()
.add(series.markerGroup || series.group);
}
H.stop(halo);
halo[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
halo.attr({
'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex)
});
} else if (halo) {
halo.animate({
d: point.haloPath(0)
}); // Hide
}
point.state = state;
},
/**
* Get the circular path definition for the halo
* @param {Number} size The radius of the circular halo
* @returns {Array} The path definition
*/
haloPath: function(size) {
var series = this.series,
chart = series.chart,
inverted = chart.inverted,
plotX = Math.floor(this.plotX);
return chart.renderer.symbols.circle(
(inverted ? series.yAxis.len - this.plotY : plotX) - size,
(inverted ? series.xAxis.len - plotX : this.plotY) - size,
size * 2,
size * 2
);
}
});
/*
* Extend the Series object with interaction
*/
extend(Series.prototype, {
/**
* Series mouse over handler
*/
onMouseOver: function() {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState('hover');
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function() {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
chart.hoverSeries = null; // #182, set to null before the mouseOut event fires
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
},
/**
* Set the state of the graph
*/
setState: function(state) {
var series = this,
options = series.options,
graph = series.graph,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs,
i = 0;
state = state || '';
if (series.state !== state) {
// Toggle class names
each([series.group, series.markerGroup], function(group) {
if (group) {
// Old state
if (series.state) {
group.removeClass('highcharts-series-' + series.state);
}
// New state
if (state) {
group.addClass('highcharts-series-' + state);
}
}
});
series.state = state;
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If undefined,
* the visibility is toggled.
*/
setVisible: function(vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt'], function(key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function(otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function(otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function() {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function() {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* undefined, the selection state is toggled.
*/
select: function(selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === undefined) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
drawTracker: TrackerMixin.drawTrackerGraph
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
inArray = H.inArray,
isObject = H.isObject,
pick = H.pick,
splat = H.splat;
/**
* Update the chart based on the current chart/document size and options for responsiveness
*/
Chart.prototype.setResponsive = function(redraw) {
var options = this.options.responsive;
if (options && options.rules) {
each(options.rules, function(rule) {
this.matchResponsiveRule(rule, redraw);
}, this);
}
};
/**
* Handle a single responsiveness rule
*/
Chart.prototype.matchResponsiveRule = function(rule, redraw) {
var respRules = this.respRules,
condition = rule.condition,
matches,
fn = rule.callback || function() {
return this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) &&
this.chartHeight <= pick(condition.maxHeight, Number.MAX_VALUE) &&
this.chartWidth >= pick(condition.minWidth, 0) &&
this.chartHeight >= pick(condition.minHeight, 0);
};
if (rule._id === undefined) {
rule._id = H.idCounter++;
}
matches = fn.call(this);
// Apply a rule
if (!respRules[rule._id] && matches) {
// Store the current state of the options
if (rule.chartOptions) {
respRules[rule._id] = this.currentOptions(rule.chartOptions);
this.update(rule.chartOptions, redraw);
}
// Unapply a rule based on the previous options before the rule
// was applied
} else if (respRules[rule._id] && !matches) {
this.update(respRules[rule._id], redraw);
delete respRules[rule._id];
}
};
/**
* Get the current values for a given set of options. Used before we update
* the chart with a new responsiveness rule.
* TODO: Restore axis options (by id?)
*/
Chart.prototype.currentOptions = function(options) {
var ret = {};
/**
* Recurse over a set of options and its current values,
* and store the current values in the ret object.
*/
function getCurrent(options, curr, ret) {
var key, i;
for (key in options) {
if (inArray(key, ['series', 'xAxis', 'yAxis']) > -1) {
options[key] = splat(options[key]);
ret[key] = [];
for (i = 0; i < options[key].length; i++) {
ret[key][i] = {};
getCurrent(options[key][i], curr[key][i], ret[key][i]);
}
} else if (isObject(options[key])) {
ret[key] = {};
getCurrent(options[key], curr[key] || {}, ret[key]);
} else {
ret[key] = curr[key] || null;
}
}
}
getCurrent(options, this.options, ret);
return ret;
};
}(Highcharts));
return Highcharts
}));
|
// -*- C++ -*-
// Copyright (C) 2005-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, 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
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file left_child_next_sibling_heap_/info_fn_imps.hpp
* Contains an implementation class for left_child_next_sibling_heap_.
*/
PB_DS_CLASS_T_DEC
inline bool
PB_DS_CLASS_C_DEC::
empty() const
{
return (m_size == 0);
}
PB_DS_CLASS_T_DEC
inline typename PB_DS_CLASS_C_DEC::size_type
PB_DS_CLASS_C_DEC::
size() const
{
return (m_size);
}
PB_DS_CLASS_T_DEC
inline typename PB_DS_CLASS_C_DEC::size_type
PB_DS_CLASS_C_DEC::
max_size() const
{
return (s_node_allocator.max_size());
}
|
/*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program 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 General Public License for more details.
*/
#ifndef __PM8XXX_ADC_H
#define __PM8XXX_ADC_H
#include <linux/kernel.h>
#include <linux/list.h>
enum pm8xxx_adc_channels {
CHANNEL_VCOIN = 0,
CHANNEL_VBAT,
CHANNEL_DCIN,
CHANNEL_ICHG,
CHANNEL_VPH_PWR,
CHANNEL_IBAT,
CHANNEL_MPP_1,
CHANNEL_MPP_2,
CHANNEL_BATT_THERM,
CHANNEL_BATT_ID_THERM = CHANNEL_BATT_THERM,
CHANNEL_BATT_ID,
CHANNEL_USBIN,
CHANNEL_DIE_TEMP,
CHANNEL_625MV,
CHANNEL_125V,
CHANNEL_CHG_TEMP,
CHANNEL_MUXOFF,
CHANNEL_NONE,
ADC_MPP_1_ATEST_8 = 20,
ADC_MPP_1_USB_SNS_DIV20,
ADC_MPP_1_DCIN_SNS_DIV20,
ADC_MPP_1_AMUX3,
ADC_MPP_1_AMUX4,
ADC_MPP_1_AMUX5,
ADC_MPP_1_AMUX6,
ADC_MPP_1_AMUX7,
ADC_MPP_1_AMUX8,
ADC_MPP_1_ATEST_1,
ADC_MPP_1_ATEST_2,
ADC_MPP_1_ATEST_3,
ADC_MPP_1_ATEST_4,
ADC_MPP_1_ATEST_5,
ADC_MPP_1_ATEST_6,
ADC_MPP_1_ATEST_7,
ADC_MPP_2_ATEST_8 = 40,
ADC_MPP_2_USB_SNS_DIV20,
ADC_MPP_2_DCIN_SNS_DIV20,
ADC_MPP_2_AMUX3,
ADC_MPP_2_AMUX4,
ADC_MPP_2_AMUX5,
ADC_MPP_2_AMUX6,
ADC_MPP_2_AMUX7,
ADC_MPP_2_AMUX8,
ADC_MPP_2_ATEST_1,
ADC_MPP_2_ATEST_2,
ADC_MPP_2_ATEST_3,
ADC_MPP_2_ATEST_4,
ADC_MPP_2_ATEST_5,
ADC_MPP_2_ATEST_6,
ADC_MPP_2_ATEST_7,
ADC_CHANNEL_MAX_NUM,
};
#define PM8XXX_ADC_PMIC_0 0x0
#define PM8XXX_CHANNEL_ADC_625_UV 625000
#define PM8XXX_CHANNEL_MPP_SCALE1_IDX 20
#define PM8XXX_CHANNEL_MPP_SCALE3_IDX 40
#define PM8XXX_AMUX_MPP_1 0x1
#define PM8XXX_AMUX_MPP_2 0x2
#define PM8XXX_AMUX_MPP_3 0x3
#define PM8XXX_AMUX_MPP_4 0x4
#define PM8XXX_AMUX_MPP_5 0x5
#define PM8XXX_AMUX_MPP_6 0x6
#define PM8XXX_AMUX_MPP_7 0x7
#define PM8XXX_AMUX_MPP_8 0x8
#define PM8XXX_AMUX_MPP_9 0x9
#define PM8XXX_AMUX_MPP_10 0xA
#define PM8XXX_AMUX_MPP_11 0xB
#define PM8XXX_AMUX_MPP_12 0xC
#define PM8XXX_ADC_DEV_NAME "pm8xxx-adc"
enum pm8xxx_adc_decimation_type {
ADC_DECIMATION_TYPE1 = 0,
ADC_DECIMATION_TYPE2,
ADC_DECIMATION_TYPE3,
ADC_DECIMATION_TYPE4,
ADC_DECIMATION_NONE,
};
enum pm8xxx_adc_calib_type {
ADC_CALIB_ABSOLUTE = 0,
ADC_CALIB_RATIOMETRIC,
ADC_CALIB_NONE,
};
enum pm8xxx_adc_channel_scaling_param {
CHAN_PATH_SCALING1 = 0,
CHAN_PATH_SCALING2,
CHAN_PATH_SCALING3,
CHAN_PATH_SCALING4,
CHAN_PATH_SCALING_NONE,
};
enum pm8xxx_adc_amux_input_rsv {
AMUX_RSV0 = 0,
AMUX_RSV1,
AMUX_RSV2,
AMUX_RSV3,
AMUX_RSV4,
AMUX_RSV5,
AMUX_NONE,
};
enum pm8xxx_adc_premux_mpp_scale_type {
PREMUX_MPP_SCALE_0 = 0,
PREMUX_MPP_SCALE_1,
PREMUX_MPP_SCALE_1_DIV3,
PREMUX_MPP_NONE,
};
enum pm8xxx_adc_scale_fn_type {
ADC_SCALE_DEFAULT = 0,
ADC_SCALE_BATT_THERM,
ADC_SCALE_PA_THERM,
ADC_SCALE_PMIC_THERM,
ADC_SCALE_XOTHERM,
ADC_SCALE_NONE,
};
struct pm8xxx_adc_linear_graph {
int64_t dy;
int64_t dx;
int64_t adc_vref;
int64_t adc_gnd;
};
struct pm8xxx_adc_map_pt {
int32_t x;
int32_t y;
};
struct pm8xxx_adc_map_table {
const struct pm8xxx_adc_map_pt *table;
int32_t size;
};
struct pm8xxx_adc_scaling_ratio {
int32_t num;
int32_t den;
};
struct pm8xxx_adc_properties {
uint32_t adc_vdd_reference;
uint32_t bitresolution;
bool bipolar;
};
struct pm8xxx_adc_chan_properties {
uint32_t offset_gain_numerator;
uint32_t offset_gain_denominator;
struct pm8xxx_adc_linear_graph adc_graph[2];
};
struct pm8xxx_adc_chan_result {
uint32_t chan;
int32_t adc_code;
int64_t measurement;
int64_t physical;
};
#if defined(CONFIG_SENSORS_PM8XXX_ADC) \
|| defined(CONFIG_SENSORS_PM8XXX_ADC_MODULE)
void pm8xxx_adc_set_adcmap_btm_table(
struct pm8xxx_adc_map_table *adcmap_table);
int32_t pm8xxx_adc_scale_default(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
int32_t pm8xxx_adc_tdkntcg_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
int32_t pm8xxx_adc_scale_batt_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
int32_t pm8xxx_adc_scale_pa_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
int32_t pm8xxx_adc_scale_pmic_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
int32_t pm8xxx_adc_scale_batt_id(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt);
#else
static inline void pm8xxx_adc_set_adcmap_btm_table(
struct pm8xxx_adc_map_table *adcmap_table)
{ return; }
static inline int32_t pm8xxx_adc_scale_default(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
static inline int32_t pm8xxx_adc_tdkntcg_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
static inline int32_t pm8xxx_adc_scale_batt_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
static inline int32_t pm8xxx_adc_scale_pa_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
static inline int32_t pm8xxx_adc_scale_pmic_therm(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
static inline int32_t pm8xxx_adc_scale_batt_id(int32_t adc_code,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop,
struct pm8xxx_adc_chan_result *chan_rslt)
{ return -ENXIO; }
#endif
struct pm8xxx_adc_scale_fn {
int32_t (*chan) (int32_t,
const struct pm8xxx_adc_properties *,
const struct pm8xxx_adc_chan_properties *,
struct pm8xxx_adc_chan_result *);
};
struct pm8xxx_adc_amux {
char *name;
enum pm8xxx_adc_channels channel_name;
enum pm8xxx_adc_channel_scaling_param chan_path_prescaling;
enum pm8xxx_adc_amux_input_rsv adc_rsv;
enum pm8xxx_adc_decimation_type adc_decimation;
enum pm8xxx_adc_scale_fn_type adc_scale_fn;
};
struct pm8xxx_adc_arb_btm_param {
int32_t low_thr_temp;
int32_t high_thr_temp;
uint64_t low_thr_voltage;
uint64_t high_thr_voltage;
int32_t interval;
void (*btm_warm_fn) (bool);
void (*btm_cool_fn) (bool);
};
int32_t pm8xxx_adc_batt_scaler(struct pm8xxx_adc_arb_btm_param *,
const struct pm8xxx_adc_properties *adc_prop,
const struct pm8xxx_adc_chan_properties *chan_prop);
struct pm8xxx_adc_platform_data {
struct pm8xxx_adc_properties *adc_prop;
struct pm8xxx_adc_amux *adc_channel;
uint32_t adc_num_board_channel;
uint32_t adc_mpp_base;
struct pm8xxx_adc_map_table *adc_map_btm_table;
void (*pm8xxx_adc_device_register)(void);
};
#if defined(CONFIG_SENSORS_PM8XXX_ADC) \
|| defined(CONFIG_SENSORS_PM8XXX_ADC_MODULE)
uint32_t pm8xxx_adc_read(enum pm8xxx_adc_channels channel,
struct pm8xxx_adc_chan_result *result);
uint32_t pm8xxx_adc_mpp_config_read(uint32_t mpp_num,
enum pm8xxx_adc_channels channel,
struct pm8xxx_adc_chan_result *result);
uint32_t pm8xxx_adc_btm_start(void);
uint32_t pm8xxx_adc_btm_end(void);
uint32_t pm8xxx_adc_btm_configure(struct pm8xxx_adc_arb_btm_param *);
int pm8xxx_adc_btm_is_cool(void);
int pm8xxx_adc_btm_is_warm(void);
#else
static inline uint32_t pm8xxx_adc_read(uint32_t channel,
struct pm8xxx_adc_chan_result *result)
{ return -ENXIO; }
static inline uint32_t pm8xxx_adc_mpp_config_read(uint32_t mpp_num,
enum pm8xxx_adc_channels channel,
struct pm8xxx_adc_chan_result *result)
{ return -ENXIO; }
static inline uint32_t pm8xxx_adc_btm_start(void)
{ return -ENXIO; }
static inline uint32_t pm8xxx_adc_btm_end(void)
{ return -ENXIO; }
static inline uint32_t pm8xxx_adc_btm_configure(
struct pm8xxx_adc_arb_btm_param *param)
{ return -ENXIO; }
static inline int pm8xxx_adc_btm_is_cool(void)
{ return 0; }
static inline int pm8xxx_adc_btm_is_warm(void)
{ return 0; }
#endif
#endif
|
/*
* Copyright (c) 2010 Nuvoton technology corporation.
*
* Wan ZongShun <mcuos.com@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation;version 2 of the License.
*
*/
#ifndef _NUC900_AUDIO_H
#define _NUC900_AUDIO_H
#include <linux/io.h>
/* Audio Control Registers */
#define ACTL_CON 0x00
#define ACTL_RESET 0x04
#define ACTL_RDSTB 0x08
#define ACTL_RDST_LENGTH 0x0C
#define ACTL_RDSTC 0x10
#define ACTL_RSR 0x14
#define ACTL_PDSTB 0x18
#define ACTL_PDST_LENGTH 0x1C
#define ACTL_PDSTC 0x20
#define ACTL_PSR 0x24
#define ACTL_IISCON 0x28
#define ACTL_ACCON 0x2C
#define ACTL_ACOS0 0x30
#define ACTL_ACOS1 0x34
#define ACTL_ACOS2 0x38
#define ACTL_ACIS0 0x3C
#define ACTL_ACIS1 0x40
#define ACTL_ACIS2 0x44
#define ACTL_COUNTER 0x48
/* bit definition of REG_ACTL_CON register */
#define R_DMA_IRQ 0x1000
#define T_DMA_IRQ 0x0800
#define IIS_AC_PIN_SEL 0x0100
#define FIFO_TH 0x0080
#define ADC_EN 0x0010
#define M80_EN 0x0008
#define ACLINK_EN 0x0004
#define IIS_EN 0x0002
/* bit definition of REG_ACTL_RESET register */
#define W5691_PLAY 0x20000
#define ACTL_RESET_BIT 0x10000
#define RECORD_RIGHT_CHNNEL 0x08000
#define RECORD_LEFT_CHNNEL 0x04000
#define PLAY_RIGHT_CHNNEL 0x02000
#define PLAY_LEFT_CHNNEL 0x01000
#define DAC_PLAY 0x00800
#define ADC_RECORD 0x00400
#define M80_PLAY 0x00200
#define AC_RECORD 0x00100
#define AC_PLAY 0x00080
#define IIS_RECORD 0x00040
#define IIS_PLAY 0x00020
#define DAC_RESET 0x00010
#define ADC_RESET 0x00008
#define M80_RESET 0x00004
#define AC_RESET 0x00002
#define IIS_RESET 0x00001
/* bit definition of REG_ACTL_ACCON register */
#define AC_BCLK_PU_EN 0x20
#define AC_R_FINISH 0x10
#define AC_W_FINISH 0x08
#define AC_W_RES 0x04
#define AC_C_RES 0x02
/* bit definition of ACTL_RSR register */
#define R_FIFO_EMPTY 0x04
#define R_DMA_END_IRQ 0x02
#define R_DMA_MIDDLE_IRQ 0x01
/* bit definition of ACTL_PSR register */
#define P_FIFO_EMPTY 0x04
#define P_DMA_END_IRQ 0x02
#define P_DMA_MIDDLE_IRQ 0x01
/* bit definition of ACTL_ACOS0 register */
#define SLOT1_VALID 0x01
#define SLOT2_VALID 0x02
#define SLOT3_VALID 0x04
#define SLOT4_VALID 0x08
#define VALID_FRAME 0x10
/* bit definition of ACTL_ACOS1 register */
#define R_WB 0x80
#define CODEC_READY 0x10
#define RESET_PRSR 0x00
#define AUDIO_WRITE(addr, val) __raw_writel(val, addr)
#define AUDIO_READ(addr) __raw_readl(addr)
struct nuc900_audio {
void __iomem *mmio;
spinlock_t lock;
unsigned long irq_num;
struct resource *res;
struct clk *clk;
struct device *dev;
};
extern struct nuc900_audio *nuc900_ac97_data;
#endif /*end _NUC900_AUDIO_H */
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*jslint evil: true, regexp: true */
/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push,
retrocycle, stringify, test, toString
*/
(function (exports) {
if (typeof exports.decycle !== 'function') {
exports.decycle = function decycle(object) {
'use strict';
var objects = [],
paths = [];
return (function derez(value, path) {
var i,
name,
nu;
switch (typeof value) {
case 'object':
if (!value) {
return null;
}
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
objects.push(value);
paths.push(path);
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
case 'number':
case 'string':
case 'boolean':
return value;
}
}(object, '$'));
};
}
if (typeof exports.retrocycle !== 'function') {
exports.retrocycle = function retrocycle($) {
'use strict';
var px =
/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
(function rez(value) {
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[i] = eval(path);
} else {
rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
}
}
}
}
}($));
return $;
};
}
}) (
(typeof exports !== 'undefined') ?
exports :
(window.JSON ?
(window.JSON) :
(window.JSON = {})
)
);
},{}],2:[function(require,module,exports){
var JSON2 = require('./json2');
var cycle = require('./cycle');
JSON2.decycle = cycle.decycle;
JSON2.retrocycle = cycle.retrocycle;
module.exports = JSON2;
},{"./cycle":1,"./json2":3}],3:[function(require,module,exports){
/*
json2.js
2011-10-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
(function (JSON) {
'use strict';
function f(n) {
return n < 10 ? '0' + n : n;
}
/* DDOPSON-2012-04-16 - mutating global prototypes is NOT allowed for a well-behaved module.
* It's also unneeded, since Date already defines toJSON() to the same ISOwhatever format below
* Thus, we skip this logic for the CommonJS case where 'exports' is defined
*/
if (typeof exports === 'undefined') {
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
}
if (typeof String.prototype.toJSON !== 'function') {
String.prototype.toJSON = function (key) { return this.valueOf(); };
}
if (typeof Number.prototype.toJSON !== 'function') {
Number.prototype.toJSON = function (key) { return this.valueOf(); };
}
if (typeof Boolean.prototype.toJSON !== 'function') {
Boolean.prototype.toJSON = function (key) { return this.valueOf(); };
}
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
var i,
k,
v,
length,
mind = gap,
partial,
value = holder[key];
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
return String(value);
case 'object':
if (!value) {
return 'null';
}
gap += indent;
partial = [];
if (Object.prototype.toString.apply(value) === '[object Array]') {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
var i;
gap = '';
indent = '';
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
} else if (typeof space === 'string') {
indent = space;
}
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
return str('', {'': value});
};
}
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
var j;
function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
j = eval('(' + text + ')');
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
throw new SyntaxError('JSON.parse');
};
}
})(
(typeof exports !== 'undefined') ?
exports :
(window.JSON ?
(window.JSON) :
(window.JSON = {})
)
);
},{}],4:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks[event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],5:[function(require,module,exports){
/*!
* domready (c) Dustin Diaz 2012 - License MIT
*/
!function (name, definition) {
if (typeof module != 'undefined') module.exports = definition()
else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
else this[name] = definition()
}('domready', function (ready) {
var fns = [], fn, f = false
, doc = document
, testEl = doc.documentElement
, hack = testEl.doScroll
, domContentLoaded = 'DOMContentLoaded'
, addEventListener = 'addEventListener'
, onreadystatechange = 'onreadystatechange'
, readyState = 'readyState'
, loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/
, loaded = loadedRgx.test(doc[readyState])
function flush(f) {
loaded = 1
while (f = fns.shift()) f()
}
doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
doc.removeEventListener(domContentLoaded, fn, f)
flush()
}, f)
hack && doc.attachEvent(onreadystatechange, fn = function () {
if (/^c/.test(doc[readyState])) {
doc.detachEvent(onreadystatechange, fn)
flush()
}
})
return (ready = hack ?
function (fn) {
self != top ?
loaded ? fn() : fns.push(fn) :
function () {
try {
testEl.doScroll('left')
} catch (e) {
return setTimeout(function() { ready(fn) }, 50)
}
fn()
}()
} :
function (fn) {
loaded ? fn() : fns.push(fn)
})
})
},{}],6:[function(require,module,exports){
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var reduce = require('reduce');
/**
* Root reference for iframes.
*/
var root = 'undefined' == typeof window
? this
: window;
/**
* Noop.
*/
function noop(){};
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* TODO: future proof, move to compoent land
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isHost(obj) {
var str = {}.toString.call(obj);
switch (str) {
case '[object File]':
case '[object Blob]':
case '[object FormData]':
return true;
default:
return false;
}
}
/**
* Determine XHR.
*/
function getXHR() {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
}
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return obj === Object(obj);
}
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
if (null != obj[key]) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return obj;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'application/xml',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop();
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function type(str){
return str.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
function params(str){
return reduce(str.split(/ *; */), function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
if (key && val) obj[key] = val;
return obj;
}, {});
};
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(req, options) {
options = options || {};
this.req = req;
this.xhr = this.req.xhr;
this.text = this.req.method !='HEAD'
? this.xhr.responseText
: null;
this.setStatusProperties(this.xhr.status);
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this.setHeaderProperties(this.header);
this.body = this.req.method != 'HEAD'
? this.parseBody(this.text)
: null;
}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
Response.prototype.get = function(field){
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
Response.prototype.setHeaderProperties = function(header){
var ct = this.header['content-type'] || '';
this.type = type(ct);
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
return parse && str && str.length
? parse(str)
: null;
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
Response.prototype.setStatusProperties = function(status){
var type = status / 100 | 0;
this.status = status;
this.statusType = type;
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = (4 == type || 5 == type)
? this.toError()
: false;
this.accepted = 202 == status;
this.noContent = 204 == status || 1223 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var url = req.url;
var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
err.method = method;
err.url = url;
return err;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
Emitter.call(this);
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {};
this._header = {};
this.on('end', function(){
var err = null;
var res = null;
try {
res = new Response(self);
} catch(e) {
err = new Error('Parser is unable to parse the response');
err.parse = true;
err.original = e;
}
self.callback(err, res);
});
}
/**
* Mixin `Emitter`.
*/
Emitter(Request.prototype);
/**
* Allow for extension
*/
Request.prototype.use = function(fn) {
fn(this);
return this;
}
/**
* Set timeout to `ms`.
*
* @param {Number} ms
* @return {Request} for chaining
* @api public
*/
Request.prototype.timeout = function(ms){
this._timeout = ms;
return this;
};
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
Request.prototype.clearTimeout = function(){
this._timeout = 0;
clearTimeout(this._timer);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request}
* @api public
*/
Request.prototype.abort = function(){
if (this.aborted) return;
this.aborted = true;
this.xhr.abort();
this.clearTimeout();
this.emit('abort');
return this;
};
/**
* Set header `field` to `val`, or multiple fields with one object.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = val;
this.header[field] = val;
return this;
};
/**
* Remove header `field`.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field
* @return {Request} for chaining
* @api public
*/
Request.prototype.unset = function(field){
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Get case-insensitive header `field` value.
*
* @param {String} field
* @return {String}
* @api private
*/
Request.prototype.getHeader = function(field){
return this._header[field.toLowerCase()];
};
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function(type){
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} pass
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function(user, pass){
var str = btoa(user + ':' + pass);
this.set('Authorization', 'Basic ' + str);
return this;
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(val){
if ('string' != typeof val) val = serialize(val);
if (val) this._query.push(val);
return this;
};
/**
* Write the field `name` and `val` for "multipart/form-data"
* request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
* ```
*
* @param {String} name
* @param {String|Blob|File} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.field = function(name, val){
if (!this._formData) this._formData = new FormData();
this._formData.append(name, val);
return this;
};
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `filename`.
*
* ``` js
* request.post('/upload')
* .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
* .end(callback);
* ```
*
* @param {String} field
* @param {Blob|File} file
* @param {String} filename
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function(field, file, filename){
if (!this._formData) this._formData = new FormData();
this._formData.append(field, file, filename);
return this;
};
/**
* Send `data`, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
*
* request.get('/search')
* .end(callback)
*
*
* request.get('/search')
* .send({ search: 'query' })
* .send({ range: '1..5' })
* .send({ order: 'desc' })
* .end(callback)
*
*
* request.post('/user')
* .type('json')
* .send('{"name":"tj"})
* .end(callback)
*
*
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
*
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
*
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this.getHeader('Content-Type');
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this.getHeader('Content-Type');
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj) return this;
if (!type) this.type('json');
return this;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function(err, res){
var fn = this._callback;
this.clearTimeout();
if (2 == fn.length) return fn(err, res);
if (err) return this.emit('error', err);
fn(res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function(){
var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
err.crossDomain = true;
this.callback(err);
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
Request.prototype.timeoutError = function(){
var timeout = this._timeout;
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
this.callback(err);
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
Request.prototype.withCredentials = function(){
this._withCredentials = true;
return this;
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = getXHR();
var query = this._query.join('&');
var timeout = this._timeout;
var data = this._formData || this._data;
this._callback = fn || noop;
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (0 == xhr.status) {
if (self.aborted) return self.timeoutError();
return self.crossDomainError();
}
self.emit('end');
};
if (xhr.upload) {
xhr.upload.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
self.emit('progress', e);
};
}
if (timeout && !this._timer) {
this._timer = setTimeout(function(){
self.abort();
}, timeout);
}
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
xhr.open(this.method, this.url, true);
if (this._withCredentials) xhr.withCredentials = true;
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
var serialize = request.serialize[this.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
for (var field in this.header) {
if (null == this.header[field]) continue;
xhr.setRequestHeader(field, this.header[field]);
}
this.emit('request', this);
xhr.send(data);
return this;
};
/**
* Expose `Request`.
*/
request.Request = Request;
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
function request(method, url) {
if ('function' == typeof url) {
return new Request('GET', method).end(url);
}
if (1 == arguments.length) {
return new Request('GET', method);
}
return new Request(method, url);
}
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
request.del = function(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* Expose `request`.
*/
module.exports = request;
},{"emitter":7,"reduce":8}],7:[function(require,module,exports){
arguments[4][4][0].apply(exports,arguments)
},{"dup":4}],8:[function(require,module,exports){
/**
* Reduce `arr` with `fn`.
*
* @param {Array} arr
* @param {Function} fn
* @param {Mixed} initial
*
* TODO: combatible error handling?
*/
module.exports = function(arr, fn, initial){
var idx = 0;
var len = arr.length;
var curr = arguments.length == 3
? initial
: arr[idx++];
while (idx < len) {
curr = fn.call(null, curr, arr[idx], ++idx, arr);
}
return curr;
};
},{}],9:[function(require,module,exports){
var Keen = require("./index"),
each = require("./utils/each");
module.exports = function(){
var loaded = window['Keen'] || null,
cached = window['_' + 'Keen'] || null,
clients,
ready;
if (loaded && cached) {
clients = cached['clients'] || {},
ready = cached['ready'] || [];
each(clients, function(client, id){
each(Keen.prototype, function(method, key){
loaded.prototype[key] = method;
});
each(["Query", "Request", "Dataset", "Dataviz"], function(name){
loaded[name] = (Keen[name]) ? Keen[name] : function(){};
});
if (client._config) {
client.configure.call(client, client._config);
}
if (client._setGlobalProperties) {
each(client._setGlobalProperties, function(fn){
client.setGlobalProperties.apply(client, fn);
});
}
if (client._addEvent) {
each(client._addEvent, function(obj){
client.addEvent.apply(client, obj);
});
}
var callback = client._on || [];
if (client._on) {
each(client._on, function(obj){
client.on.apply(client, obj);
});
client.trigger('ready');
}
each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){
if (client[name]) {
client[name] = undefined;
try{
delete client[name];
} catch(e){}
}
});
});
each(ready, function(cb, i){
Keen.once("ready", cb);
});
}
window['_' + 'Keen'] = undefined;
try {
delete window['_' + 'Keen']
} catch(e) {}
};
},{"./index":17,"./utils/each":23}],10:[function(require,module,exports){
var Emitter = require('component-emitter');
Emitter.prototype.trigger = Emitter.prototype.emit;
module.exports = Emitter;
},{"component-emitter":4}],11:[function(require,module,exports){
module.exports = function(){
return "undefined" == typeof window ? "server" : "browser";
};
},{}],12:[function(require,module,exports){
var each = require('../utils/each'),
JSON2 = require('JSON2');
module.exports = function(params){
var query = [];
each(params, function(value, key){
if ('string' !== typeof value) {
value = JSON2.stringify(value);
}
query.push(key + '=' + encodeURIComponent(value));
});
return '?' + query.join('&');
};
},{"../utils/each":23,"JSON2":2}],13:[function(require,module,exports){
module.exports = function(){
if ("undefined" !== typeof window) {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
return 2000;
}
}
return 16000;
};
},{}],14:[function(require,module,exports){
module.exports = function() {
var root = "undefined" == typeof window ? this : window;
if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
}
return false;
};
},{}],15:[function(require,module,exports){
module.exports = function(err, res, callback) {
var cb = callback || function() {};
if (res && !res.ok) {
var is_err = res.body && res.body.error_code;
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
err.code = is_err ? res.body.error_code : 'UnknownError';
}
if (err) {
cb(err, null);
}
else {
cb(null, res.body);
}
return;
};
},{}],16:[function(require,module,exports){
var superagent = require('superagent');
var each = require('../utils/each'),
getXHR = require('./get-xhr-object');
module.exports = function(type, opts){
return function(request) {
var __super__ = request.constructor.prototype.end;
if ( 'undefined' === typeof window ) return;
request.requestType = request.requestType || {};
request.requestType['type'] = type;
request.requestType['options'] = request.requestType['options'] || {
async: true,
success: {
responseText: '{ "created": true }',
status: 201
},
error: {
responseText: '{ "error_code": "ERROR", "message": "Request failed" }',
status: 404
}
};
if (opts) {
if ( 'boolean' === typeof opts.async ) {
request.requestType['options'].async = opts.async;
}
if ( opts.success ) {
extend(request.requestType['options'].success, opts.success);
}
if ( opts.error ) {
extend(request.requestType['options'].error, opts.error);
}
}
request.end = function(fn){
var self = this,
reqType = (this.requestType) ? this.requestType['type'] : 'xhr',
query,
timeout;
if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) {
__super__.call(self, fn);
return;
}
query = self._query.join('&');
timeout = self._timeout;
self._callback = fn || noop;
if (timeout && !self._timer) {
self._timer = setTimeout(function(){
abortRequest.call(self);
}, timeout);
}
if (query) {
query = superagent.serializeObject(query);
self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query;
}
self.emit('request', self);
if ( !self.requestType['options'].async ) {
sendXhrSync.call(self);
}
else if ( 'jsonp' === reqType ) {
sendJsonp.call(self);
}
else if ( 'beacon' === reqType ) {
sendBeacon.call(self);
}
return self;
};
return request;
};
};
function sendXhrSync(){
var xhr = getXHR();
if (xhr) {
xhr.open('GET', this.url, false);
xhr.send(null);
}
return this;
}
function sendJsonp(){
var self = this,
timestamp = new Date().getTime(),
script = document.createElement('script'),
parent = document.getElementsByTagName('head')[0],
callbackName = 'keenJSONPCallback',
loaded = false;
callbackName += timestamp;
while (callbackName in window) {
callbackName += 'a';
}
window[callbackName] = function(response) {
if (loaded === true) return;
loaded = true;
handleSuccess.call(self, response);
cleanup();
};
script.src = self.url + '&jsonp=' + callbackName;
parent.appendChild(script);
script.onreadystatechange = function() {
if (loaded === false && self.readyState === 'loaded') {
loaded = true;
handleError.call(self);
cleanup();
}
};
script.onerror = function() {
if (loaded === false) {
loaded = true;
handleError.call(self);
cleanup();
}
};
function cleanup(){
window[callbackName] = undefined;
try {
delete window[callbackName];
} catch(e){}
parent.removeChild(script);
}
}
function sendBeacon(){
var self = this,
img = document.createElement('img'),
loaded = false;
img.onload = function() {
loaded = true;
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height === 0) {
this.onerror();
return;
}
handleSuccess.call(self);
};
img.onerror = function() {
loaded = true;
handleError.call(self);
};
img.src = self.url + '&c=clv1';
}
function handleSuccess(res){
var opts = this.requestType['options']['success'],
response = '';
xhrShim.call(this, opts);
if (res) {
try {
response = JSON.stringify(res);
} catch(e) {}
}
else {
response = opts['responseText'];
}
this.xhr.responseText = response;
this.xhr.status = opts['status'];
this.emit('end');
}
function handleError(){
var opts = this.requestType['options']['error'];
xhrShim.call(this, opts);
this.xhr.responseText = opts['responseText'];
this.xhr.status = opts['status'];
this.emit('end');
}
function abortRequest(){
this.aborted = true;
this.clearTimeout();
this.emit('abort');
}
function xhrShim(opts){
this.xhr = {
getAllResponseHeaders: function(){ return ''; },
getResponseHeader: function(){ return 'application/json'; },
responseText: opts['responseText'],
status: opts['status']
};
return this;
}
},{"../utils/each":23,"./get-xhr-object":14,"superagent":6}],17:[function(require,module,exports){
var root = this;
var previous_Keen = root.Keen;
var extend = require('./utils/extend');
var Emitter = require('./helpers/emitter-shim');
function Keen(config) {
this.configure(config || {});
Keen.trigger('client', this);
}
Keen.debug = false;
Keen.enabled = true;
Keen.loaded = true;
Keen.version = '3.2.0';
Emitter(Keen);
Emitter(Keen.prototype);
Keen.prototype.configure = function(cfg){
var config = cfg || {};
if (config['host']) {
config['host'].replace(/.*?:\/\//g, '');
}
if (config.protocol && config.protocol === 'auto') {
config['protocol'] = location.protocol.replace(/:/g, '');
}
this.config = {
projectId : config.projectId,
writeKey : config.writeKey,
readKey : config.readKey,
masterKey : config.masterKey,
requestType : config.requestType || 'jsonp',
host : config['host'] || 'api.keen.io/3.0',
protocol : config['protocol'] || 'https',
globalProperties: null
};
if (Keen.debug) {
this.on('error', Keen.log);
}
this.trigger('ready');
};
Keen.prototype.projectId = function(str){
if (!arguments.length) return this.config.projectId;
this.config.projectId = (str ? String(str) : null);
return this;
};
Keen.prototype.masterKey = function(str){
if (!arguments.length) return this.config.masterKey;
this.config.masterKey = (str ? String(str) : null);
return this;
};
Keen.prototype.readKey = function(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = (str ? String(str) : null);
return this;
};
Keen.prototype.writeKey = function(str){
if (!arguments.length) return this.config.writeKey;
this.config.writeKey = (str ? String(str) : null);
return this;
};
Keen.prototype.url = function(path){
if (!this.projectId()) {
this.trigger('error', 'Client is missing projectId property');
return;
}
return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path;
};
Keen.log = function(message) {
if (Keen.debug && typeof console == 'object') {
console.log('[Keen IO]', message);
}
};
Keen.noConflict = function(){
root.Keen = previous_Keen;
return Keen;
};
Keen.ready = function(fn){
if (Keen.loaded) {
fn();
} else {
Keen.once('ready', fn);
}
};
module.exports = Keen;
},{"./helpers/emitter-shim":10,"./utils/extend":24}],18:[function(require,module,exports){
var JSON2 = require('JSON2');
var request = require('superagent');
var Keen = require('../index');
var base64 = require('../utils/base64'),
each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getQueryString = require('../helpers/get-query-string'),
getUrlMaxLength = require('../helpers/get-url-max-length'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(collection, payload, callback, async) {
var self = this,
urlBase = this.url('/events/' + collection),
reqType = this.config.requestType,
data = {},
cb = callback,
isAsync,
getUrl;
isAsync = ('boolean' === typeof async) ? async : true;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (!collection || typeof collection !== 'string') {
handleValidationError.call(self, 'Collection name must be a string');
return;
}
if (self.config.globalProperties) {
data = self.config.globalProperties(collection);
}
each(payload, function(value, key){
data[key] = value;
});
if ( !getXHR() && 'xhr' === reqType ) {
reqType = 'jsonp';
}
if ( 'xhr' !== reqType || !isAsync ) {
getUrl = prepareGetRequest.call(self, urlBase, data);
}
if ( getUrl && getContext() === 'browser' ) {
request
.get(getUrl)
.use(function(req){
req.async = isAsync;
return req;
})
.use(requestTypes(reqType))
.end(handleResponse);
}
else if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(handleResponse);
}
else {
self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.');
}
function handleResponse(err, res){
responseHandler(err, res, cb);
cb = callback = null;
}
function handleValidationError(msg){
var err = 'Event not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
function prepareGetRequest(url, data){
url += getQueryString({
api_key : this.writeKey(),
data : base64.encode( JSON2.stringify(data) ),
modified : new Date().getTime()
});
return ( url.length < getUrlMaxLength() ) ? url : false;
}
},{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":13,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/base64":22,"../utils/each":23,"JSON2":2,"superagent":6}],19:[function(require,module,exports){
var Keen = require('../index');
var request = require('superagent');
var each = require('../utils/each'),
getContext = require('../helpers/get-context'),
getXHR = require('../helpers/get-xhr-object'),
requestTypes = require('../helpers/superagent-request-types'),
responseHandler = require('../helpers/superagent-handle-response');
module.exports = function(payload, callback) {
var self = this,
urlBase = this.url('/events'),
data = {},
cb = callback;
if (!Keen.enabled) {
handleValidationError.call(self, 'Keen.enabled = false');
return;
}
if (!self.projectId()) {
handleValidationError.call(self, 'Missing projectId property');
return;
}
if (!self.writeKey()) {
handleValidationError.call(self, 'Missing writeKey property');
return;
}
if (arguments.length > 2) {
handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method');
return;
}
if (typeof payload !== 'object' || payload instanceof Array) {
handleValidationError.call(self, 'Request payload must be an object');
return;
}
if (self.config.globalProperties) {
each(payload, function(events, collection){
each(events, function(body, index){
var base = self.config.globalProperties(collection);
each(body, function(value, key){
base[key] = value;
});
data[collection].push(base);
});
});
}
else {
data = payload;
}
if ( getXHR() || getContext() === 'server' ) {
request
.post(urlBase)
.set('Content-Type', 'application/json')
.set('Authorization', self.writeKey())
.send(data)
.end(function(err, res){
responseHandler(err, res, cb);
cb = callback = null;
});
}
else {
self.trigger('error', 'Events not recorded: XHR support is required for batch upload');
}
function handleValidationError(msg){
var err = 'Events not recorded: ' + msg;
self.trigger('error', err);
if (cb) {
cb.call(self, err, null);
cb = callback = null;
}
}
return;
};
},{"../helpers/get-context":11,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/each":23,"superagent":6}],20:[function(require,module,exports){
module.exports = function(newGlobalProperties) {
if (newGlobalProperties && typeof(newGlobalProperties) == "function") {
this.config.globalProperties = newGlobalProperties;
} else {
this.trigger("error", "Invalid value for global properties: " + newGlobalProperties);
}
};
},{}],21:[function(require,module,exports){
var addEvent = require("./addEvent");
module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){
var evt = jsEvent,
target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target),
timer = timeout || 500,
triggered = false,
targetAttr = "",
callback,
win;
if (target.getAttribute !== void 0) {
targetAttr = target.getAttribute("target");
} else if (target.target) {
targetAttr = target.target;
}
if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) {
win = window.open("about:blank");
win.document.location = target.href;
}
if (target.nodeName === "A") {
callback = function(){
if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){
triggered = true;
window.location = target.href;
}
};
} else if (target.nodeName === "FORM") {
callback = function(){
if(!triggered){
triggered = true;
target.submit();
}
};
} else {
this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element");
}
if (timeoutCallback) {
callback = function(){
if(!triggered){
triggered = true;
timeoutCallback();
}
};
}
addEvent.call(this, eventCollection, payload, callback);
setTimeout(callback, timer);
if (!evt.metaKey) {
return false;
}
};
},{"./addEvent":18}],22:[function(require,module,exports){
module.exports = {
map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4;
n = this.utf8.encode(n);
while (i < n.length) {
i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++);
e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6));
e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63;
o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4);
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3;
n = n.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < n.length) {
e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++));
e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++));
c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2);
c3 = ((e3 & 3) << 6) | e4;
o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : ""));
} return this.utf8.decode(o);
},
utf8: {
encode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c;
while (i < n.length) {
c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ?
(cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128)));
} return o;
},
decode: function (n) {
"use strict";
var o = "", i = 0, cc = String.fromCharCode, c2, c;
while (i < n.length) {
c = n.charCodeAt(i);
o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ?
[cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] :
[cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]);
} return o;
}
}
};
},{}],23:[function(require,module,exports){
module.exports = function(o, cb, s){
var n;
if (!o){
return 0;
}
s = !s ? o : s;
if (o instanceof Array){
for (n=0; n<o.length; n++) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
} else {
for (n in o){
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false){
return 0;
}
}
}
}
return 1;
};
},{}],24:[function(require,module,exports){
module.exports = function(target){
for (var i = 1; i < arguments.length; i++) {
for (var prop in arguments[i]){
target[prop] = arguments[i][prop];
}
}
return target;
};
},{}],25:[function(require,module,exports){
function parseParams(str){
var urlParams = {},
match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = str.split("?")[1];
while (!!(match=search.exec(query))) {
urlParams[decode(match[1])] = decode(match[2]);
}
return urlParams;
};
module.exports = parseParams;
},{}],26:[function(require,module,exports){
(function (global){
;(function (f) {
if (typeof define === "function" && define.amd) {
define("keen", [], function(){ return f(); });
}
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f();
}
var g = null;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
}
if (g) {
g.Keen = f();
}
})(function() {
"use strict";
var Keen = require("./core"),
extend = require("./core/utils/extend");
extend(Keen.prototype, {
"addEvent" : require("./core/lib/addEvent"),
"addEvents" : require("./core/lib/addEvents"),
"setGlobalProperties" : require("./core/lib/setGlobalProperties"),
"trackExternalLink" : require("./core/lib/trackExternalLink")
});
Keen.Base64 = require("./core/utils/base64");
Keen.utils = {
"domready" : require("domready"),
"each" : require("./core/utils/each"),
"extend" : extend,
"parseParams" : require("./core/utils/parseParams")
};
if (Keen.loaded) {
setTimeout(function(){
Keen.utils.domready(function(){
Keen.emit("ready");
});
}, 0);
}
require("./core/async")();
module.exports = Keen;
return Keen;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./core":17,"./core/async":9,"./core/lib/addEvent":18,"./core/lib/addEvents":19,"./core/lib/setGlobalProperties":20,"./core/lib/trackExternalLink":21,"./core/utils/base64":22,"./core/utils/each":23,"./core/utils/extend":24,"./core/utils/parseParams":25,"domready":5}]},{},[26]);
|
// Copyright (c) 2011 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.
#ifndef CHROME_FRAME_TEST_WIN_EVENT_RECEIVER_H_
#define CHROME_FRAME_TEST_WIN_EVENT_RECEIVER_H_
#include <windows.h>
#include <string>
#include <vector>
#include <utility>
#include "base/memory/linked_ptr.h"
#include "base/win/object_watcher.h"
struct FunctionStub;
// Listens to WinEvents from the WinEventReceiver.
class WinEventListener {
public:
virtual ~WinEventListener() {}
// Called when an event has been received. |hwnd| is the window that generated
// the event, or null if no window is associated with the event.
virtual void OnEventReceived(DWORD event, HWND hwnd, LONG object_id,
LONG child_id) = 0;
};
// Receives WinEvents and forwards them to its listener. The event types the
// listener wants to receive can be specified.
class WinEventReceiver {
public:
WinEventReceiver();
~WinEventReceiver();
// Sets the sole listener of this receiver. The listener will receive all
// WinEvents of the given event type. Any previous listener will be
// replaced. |listener| should not be NULL.
void SetListenerForEvent(WinEventListener* listener, DWORD event);
// Same as above, but sets a range of events to listen for.
void SetListenerForEvents(WinEventListener* listener, DWORD event_min,
DWORD event_max);
// Stops receiving events and forwarding them to the listener. It is
// permitted to call this even if the receiver has already been stopped.
void StopReceivingEvents();
private:
bool InitializeHook(DWORD event_min, DWORD event_max);
static void CALLBACK WinEventHook(WinEventReceiver* me, HWINEVENTHOOK hook,
DWORD event, HWND hwnd, LONG object_id, LONG child_id,
DWORD event_thread_id, DWORD event_time);
WinEventListener* listener_;
HWINEVENTHOOK hook_;
FunctionStub* hook_stub_;
};
// Receives notifications when a window is opened or closed.
class WindowObserver {
public:
virtual ~WindowObserver() {}
virtual void OnWindowOpen(HWND hwnd) = 0;
virtual void OnWindowClose(HWND hwnd) = 0;
};
// Notifies observers when windows whose captions match specified patterns
// open or close. When a window opens, its caption is compared to the patterns
// associated with each observer. Observers registered with matching patterns
// are notified of the window's opening and will be notified when the same
// window is closed (including if the owning process terminates without closing
// the window).
//
// Changes to a window's caption while it is open do not affect the set of
// observers to be notified when it closes.
//
// Observers are not notified of the closing of windows that were already open
// when they were registered.
//
// Observers may call AddObserver and/or RemoveObserver during notifications.
//
// Each instance of this class must only be accessed from a single thread, and
// that thread must be running a message loop.
class WindowWatchdog : public WinEventListener {
public:
WindowWatchdog();
// Register |observer| to be notified when windows matching |caption_pattern|
// and/or |class_name_pattern| are opened or closed. A single observer may be
// registered multiple times.
// If a single window caption and/or class name matches multiple
// registrations of a single observer, the observer will be notified once per
// matching registration.
void AddObserver(WindowObserver* observer,
const std::string& caption_pattern,
const std::string& class_name_pattern);
// Remove all registrations of |observer|. The |observer| will not be notified
// during or after this call.
void RemoveObserver(WindowObserver* observer);
private:
class ProcessExitObserver;
// The Delegate object is actually a ProcessExitObserver, but declaring
// it as such would require fully declaring the ProcessExitObserver class
// here in order for linked_ptr to access its destructor.
typedef std::pair<HWND, linked_ptr<base::win::ObjectWatcher::Delegate> >
OpenWindowEntry;
typedef std::vector<OpenWindowEntry> OpenWindowList;
struct ObserverEntry {
WindowObserver* observer;
std::string caption_pattern;
std::string class_name_pattern;
OpenWindowList open_windows;
};
typedef std::vector<ObserverEntry> ObserverEntryList;
// WinEventListener implementation.
virtual void OnEventReceived(
DWORD event, HWND hwnd, LONG object_id, LONG child_id);
static std::string GetWindowCaption(HWND hwnd);
void HandleOnOpen(HWND hwnd);
void HandleOnClose(HWND hwnd);
void OnHwndProcessExited(HWND hwnd);
// Returns true if the caption pattern and/or the class name pattern in the
// observer entry structure matches the caption and/or class name passed in.
bool MatchingWindow(const ObserverEntry& entry,
const std::string& caption,
const std::string& class_name);
ObserverEntryList observers_;
WinEventReceiver win_event_receiver_;
DISALLOW_COPY_AND_ASSIGN(WindowWatchdog);
};
#endif // CHROME_FRAME_TEST_WIN_EVENT_RECEIVER_H_
|
def foo():
pass \
\
\ |
// "Create local variable 'zeit'" "true"
public class A {
void foo() {
ze<caret>it = A::foo;
}
static void foo(){}
}
|
/*
*
* Copyright 2012 Adobe Systems Inc.;
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* This css is customized for Onsen UI Theming by Mitsunori KUBOTA<mitsunori@asial.co.jp>.
*/
* {
font-family: 'Helvetica Neue', Helvetica, Arial, Verdana, sans-serif;
-webkit-font-smoothing: antialiased;
}
.quarter {
width: 25%;
}
.half {
width: 50%;
}
.three-quarters {
width: 75%;
}
.third {
width: 33.333%;
}
.two-thirds {
width: 66.666%;
}
.full {
width: 100%;
}
.left {
text-align: left;
}
.center {
text-align: center;
}
.right {
text-align: right;
}
.reset-ui {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
position: relative;
display: inline-block;
vertical-align: top;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
/* topdoc
name: Button
description: A simple button
modifiers:
:active: Active state
:disabled: Disabled state
:focus: Focused
markup:
<button class="topcoat-button">Button</button>
<button class="topcoat-button" disabled>Button</button>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Button</h1>
</div>
</div>
<div style="padding:8px">
<button class="topcoat-button">Button</button>
<button class="topcoat-button--cta">Button</button>
<button class="topcoat-button--quiet">Button</button>
<br>
<br>
<div style="padding:4px 0px">
<button class="topcoat-button--large">Button</button>
</div>
<div style="padding:4px 0px">
<button class="topcoat-button--large--cta">Button</button>
</div>
<div style="padding:4px 0px">
<button class="topcoat-button--large--quiet">Button</button>
</div>
</div>
*/
/* topdoc
name: Button:Call To Action Button
markup:
<button class="topcoat-button--cta" >Button</button>
<button class="topcoat-button--cta" disabled>Button</button>
*/
/* topdoc
name: Button:Quiet Button
markup:
<button class="topcoat-button--quiet">Button</button>
<button class="topcoat-button--quiet" disabled>Button</button>
*/
/* topdoc
name: Button:Large Button
markup:
<button class="topcoat-button--large" >Button</button><br>
<button class="topcoat-button--large" disabled>Button</button>
*/
/* topdoc
name: Button:Large Quiet Button
markup:
<button class="topcoat-button--large--quiet">Button</button>
<button class="topcoat-button--large--quiet" disabled>Button</button>
*/
/* topdoc
name: Button:Large Call To Action Button
markup:
<button class="topcoat-button--large--cta" >Button</button><br>
<button class="topcoat-button--large--cta" disabled>Button</button>
*/
.button,
.topcoat-button,
.topcoat-button--quiet,
.topcoat-button--large,
.topcoat-button--large--quiet,
.topcoat-button--cta,
.topcoat-button--large--cta,
.topcoat-button-bar__button,
.topcoat-icon-button,
.topcoat-icon-button--quiet,
.topcoat-tab-bar__button {
position: relative;
display: inline-block;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
text-decoration: none;
}
.button--quiet {
background: transparent;
border: 1px solid transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.button--disabled,
.topcoat-button:disabled,
.topcoat-button--quiet:disabled,
.topcoat-button--large:disabled,
.topcoat-button--large--quiet:disabled,
.topcoat-button--cta:disabled,
.topcoat-button--large--cta:disabled,
.topcoat-button-bar__button:disabled,
.topcoat-icon-button:disabled,
.topcoat-icon-button--quiet:disabled,
.topcoat-tab-bar__button:disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-button,
.topcoat-button--quiet,
.topcoat-button--large,
.topcoat-button--large--quiet,
.topcoat-button--cta,
.topcoat-button--large--cta,
.topcoat-button-bar__button {
padding: 0 20px;
font-size: 16px;
line-height: 36px;
letter-spacing: 1px;
color: #c6c8c8;
color: #fff;
text-shadow: 0 1px none;
vertical-align: top;
background-color: transparent;
background-color: #a64a97;
-webkit-box-shadow: none;
box-shadow: none;
border: 1px solid #a64a97;
border: none;
-webkit-border-radius: 4px;
border-radius: 4px;
}
.topcoat-button:hover,
.topcoat-button--quiet:hover,
.topcoat-button--large:hover,
.topcoat-button--large--quiet:hover,
.topcoat-button-bar__button:hover {
background-color: transparent;
background-color: #b559a6;
color: var-color--button--hover;
}
.topcoat-button:active,
.topcoat-button--large:active,
.topcoat-button-bar__button:active,
:checked + .topcoat-button-bar__button {
background-color: #a64a97;
background-color: #c379b7;
-webkit-box-shadow: none;
box-shadow: none;
color: #fff;
}
.topcoat-button:focus,
.topcoat-button--quiet:focus,
.topcoat-button--large:focus,
.topcoat-button--large--quiet:focus,
.topcoat-button--cta:focus,
.topcoat-button--large--cta:focus,
.topcoat-button-bar__button:focus {
border: none;
-webkit-box-shadow: none;
box-shadow: none;
outline: 0;
}
.topcoat-button--quiet {
background: transparent;
border: 1px solid transparent;
-webkit-box-shadow: none;
box-shadow: none;
background: transparent;
color: #a64a97;
border: none;
}
.topcoat-button--quiet:disabled {
border: none;
}
.topcoat-button--quiet:hover,
.topcoat-button--large--quiet:hover {
text-shadow: 0 1px none;
border: 1px solid #a64a97;
border: none;
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-button--quiet:active,
.topcoat-button--large--quiet:active {
color: #c6c8c8;
color: #c379b7;
text-shadow: 0 1px none;
background-color: #a64a97;
background-color: transparent;
border: 1px solid #a64a97;
border: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-button--large,
.topcoat-button--large--quiet {
font-size: 16px;
font-weight: 500;
line-height: 54px;
padding: 0 20px;
width: 100%;
display: block;
}
.topcoat-button--large--quiet {
color: #a64a97;
background: transparent;
border: 1px solid transparent;
-webkit-box-shadow: none;
box-shadow: none;
color: #a64a97;
}
.topcoat-button--large--quiet:active {
color: inherit;
}
.topcoat-button--cta,
.topcoat-button--large--cta {
border: none;
background-color: #4a9cd2;
-webkit-box-shadow: none;
box-shadow: none;
color: #fff;
font-weight: 500;
text-shadow: none;
}
.topcoat-button--cta:hover,
.topcoat-button--large--cta:hover {
background-color: #63a9d8;
}
.topcoat-button--cta:active,
.topcoat-button--large--cta:active {
color: var-color--cta--down;
background-color: #87bee1;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-button--large--cta {
font-size: 16px;
font-weight: 500;
line-height: 54px;
padding: 0 20px;
width: 100%;
display: block;
}
.topcoat-button__spinner {
border: 3px solid #c6c8c8;
border: 3px solid #fff;
}
/* topdoc
name: Button Bar
description: Component of grouped buttons
modifiers:
:disabled: Disabled state
markup:
<div class="topcoat-button-bar" style="width:280px">
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">One</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Two</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Three</button>
</div>
</div>
<br>
<div class="topcoat-button-bar" style="width:280px">
<div class="topcoat-button-bar__item active">
<button class="topcoat-button-bar__button">One</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Two</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Three</button>
</div>
</div>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Button Bar</h1>
</div>
</div>
<div style="padding:8px">
<div class="topcoat-button-bar" style="width:100%">
<div class="topcoat-button-bar__item active">
<button class="topcoat-button-bar__button">One</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Two</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Three</button>
</div>
</div>
</div>
<div style="padding:8px">
<div class="topcoat-button-bar" style="width:100%">
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">One</button>
</div>
<div class="topcoat-button-bar__item active">
<button class="topcoat-button-bar__button">Two</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Three</button>
</div>
</div>
</div>
<div style="padding:8px">
<div class="topcoat-button-bar" style="width:100%">
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">One</button>
</div>
<div class="topcoat-button-bar__item">
<button class="topcoat-button-bar__button">Two</button>
</div>
<div class="topcoat-button-bar__item active">
<button class="topcoat-button-bar__button">Three</button>
</div>
</div>
</div>
*/
.button-bar,
.topcoat-button-bar,
.topcoat-tab-bar {
display: table;
table-layout: fixed;
white-space: nowrap;
margin: 0;
padding: 0;
}
.button-bar__item,
.topcoat-button-bar__item,
.topcoat-tab-bar__item {
display: table-cell;
width: auto;
-webkit-border-radius: 0;
border-radius: 0;
}
.button-bar__item > input,
.topcoat-button-bar__item > input,
.topcoat-tab-bar__item > input {
position: absolute;
overflow: hidden;
padding: 0;
border: 0;
opacity: 0.001;
z-index: 1;
vertical-align: top;
outline: none;
}
.button-bar__button {
-webkit-border-radius: inherit;
border-radius: inherit;
}
.button-bar__itemdisabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-button-bar {
margin: inherit;
border: var-border--button-bar;
}
.topcoat-button-bar__item {
border-top: var-border-top--button-bar__button;
border-bottom: var-border-bottom--button-bar__button;
width: 100%;
}
.topcoat-button-bar > .topcoat-button-bar__item:first-child {
-webkit-border-top-left-radius: 4px;
border-top-left-radius: 4px;
-webkit-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.topcoat-button-bar > .topcoat-button-bar__item:last-child {
-webkit-border-top-right-radius: 4px;
border-top-right-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.topcoat-button-bar__item:first-child > .topcoat-button-bar__button {
border-left: var-border-left--button-bar__button__first;
border-right: none;
border-right: 1px solid #a64a97;
}
.topcoat-button-bar__item:last-child > .topcoat-button-bar__button {
border-left: none;
border-right: none;
}
.topcoat-button-bar__button {
-webkit-border-radius: inherit;
border-radius: inherit;
background-color: #944287;
color: var-color--button-bar--button;
border: none;
border-right: 1px solid #a64a97;
width: 100%;
}
.topcoat-button-bar__button:active,
:checked + .topcoat-button-bar__button {
background-color: #f5f0e8 !important;
color: #a64a97;
border: none;
border-right: 1px solid #a64a97;
border-right: 1px solid #a64a97;
}
.topcoat-button-bar__button:hover {
background-color: #b559a6;
color: var-color--button-bar__button--hover;
}
.topcoat-button-bar__button:focus {
z-index: 1;
z-index: 1;
border-right: 1px solid #a64a97;
}
/* topdoc
name: Icon Button
description: Like button, but it has an icon.
modifiers:
:active: Active state
:disabled: Disabled state
:focus: Focused
markup:
<p>Icon Button</p>
<button class="topcoat-icon-button">
<i class="fa fa-bell" style="font-size:17px"></i> Label
</button>
<button class="topcoat-icon-button" disabled>
<i class="fa fa-bell" style="font-size:17px"></i> Label
</button>
<p>Quiet Icon Button</p>
<button class="topcoat-icon-button--quiet">
<i class="fa fa-bell" style="font-size:17px"></i> Label
</button>
<button class="topcoat-icon-button--quiet" disabled>
<i class="fa fa-bell" style="font-size:17px"></i> Label
</button>
*/
.topcoat-icon-button,
.topcoat-icon-button--quiet {
padding: 0 9px;
line-height: 36px;
letter-spacing: 1px;
color: #c6c8c8;
text-shadow: 0 1px none;
vertical-align: baseline;
background-color: transparent;
background-color: #fff;
-webkit-box-shadow: none;
box-shadow: none;
border: 1px solid #a64a97;
border: none;
-webkit-border-radius: 4px;
border-radius: 4px;
border-radius: 3px;
}
.topcoat-icon-button:hover,
.topcoat-icon-button--quiet:hover {
background-color: transparent;
background-color: transparent;
}
.topcoat-icon-button:active {
background-color: #a64a97;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-icon-button:focus,
.topcoat-icon-button--quiet:focus,
.topcoat-icon-button--quiet:hover:focus {
border: none;
-webkit-box-shadow: none;
box-shadow: none;
outline: 0;
}
.topcoat-icon-button--quiet {
background: transparent;
border: 1px solid transparent;
-webkit-box-shadow: none;
box-shadow: none;
background-color: var-background-color__icon-button--quiet;
border: none;
color: #fff;
}
.topcoat-icon-button--quiet:hover {
text-shadow: 0 1px none;
border: 1px solid #a64a97;
border: none;
-webkit-box-shadow: none;
box-shadow: none;
box-shadow: none;
}
.topcoat-icon-button--quiet:active {
color: #c6c8c8;
color: #b3b3b3;
text-shadow: 0 1px none;
background-color: #a64a97;
background-color: transparent;
border: 1px solid #a64a97;
border: none;
-webkit-box-shadow: none;
box-shadow: none;
box-shadow: none;
}
.topcoat-icon,
.topcoat-icon--large {
position: relative;
display: inline-block;
vertical-align: top;
overflow: hidden;
width: 19.44px;
height: 19.44px;
vertical-align: middle;
top: -1px;
}
.topcoat-icon--large {
width: 30.857142834px;
height: 30.857142834px;
top: -2px;
}
/* topdoc
name: Checkbox
description: Default skin for Topcoat checkbox
modifiers:
:focus: Focus state
:disabled: Disabled state
markup:
<label class="topcoat-checkbox">
<input type="checkbox">
<div class="topcoat-checkbox__checkmark"></div>
OFF
</label>
<br>
<label class="topcoat-checkbox">
<input type="checkbox" checked="checked">
<div class="topcoat-checkbox__checkmark"></div>
ON
</label>
<br>
<label class="topcoat-checkbox">
<input type="checkbox" disabled>
<div class="topcoat-checkbox__checkmark"></div>
Disabled
</label>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Checkbox</h1>
</div>
</div>
<br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item__line-height">
<label class="topcoat-checkbox">
<input type="checkbox" checked="checked">
<div class="topcoat-checkbox__checkmark"></div>
ON
</label>
</li>
<li class="topcoat-list__item topcoat-list__item__line-height">
<label class="topcoat-checkbox">
<input type="checkbox">
<div class="topcoat-checkbox__checkmark"></div>
OFF
</label>
</li>
<li class="topcoat-list__item topcoat-list__item__line-height">
<label class="topcoat-checkbox--noborder">
<input type="checkbox" checked="checked">
<div class="topcoat-checkbox__checkmark"></div>
ON
</label>
</li>
<li class="topcoat-list__item topcoat-list__item__line-height">
<label class="topcoat-checkbox--noborder">
<input type="checkbox">
<div class="topcoat-checkbox__checkmark"></div>
OFF
</label>
</li>
</ul>
</div>
*/
/* topdoc
name: Checkbox:Noborder Checkbox
markup:
<label class="topcoat-checkbox--noborder">
<input type="checkbox">
<div class="topcoat-checkbox__checkmark"></div>
OFF
</label>
<br>
<label class="topcoat-checkbox--noborder">
<input type="checkbox" checked="checked">
<div class="topcoat-checkbox__checkmark"></div>
ON
</label>
<br>
<label class="topcoat-checkbox--noborder">
<input type="checkbox" disabled checked="checked">
<div class="topcoat-checkbox__checkmark"></div>
Disabled
</label>
*/
input[type="checkbox"] {
position: absolute;
overflow: hidden;
padding: 0;
border: 0;
opacity: 0.001;
z-index: 1;
vertical-align: top;
outline: none;
}
.checkbox,
.topcoat-checkbox__checkmark {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
position: relative;
display: inline-block;
vertical-align: top;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.checkbox__label,
.topcoat-checkbox {
position: relative;
display: inline-block;
vertical-align: top;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.checkbox--disabled,
input[type="checkbox"]:disabled + .topcoat-checkbox__checkmark {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.checkbox:before,
.checkbox:after,
.topcoat-checkbox__checkmark:before,
.topcoat-checkbox__checkmark:after {
content: '';
position: absolute;
}
.checkbox:before,
.topcoat-checkbox__checkmark:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.topcoat-checkbox__checkmark {
height: 32px;
}
input[type="checkbox"] {
height: 32px;
width: 32px;
margin-top: 0;
margin-right: -32px;
margin-bottom: -32px;
margin-left: 0;
}
input[type="checkbox"]:checked {
background: var-background-color-checked--checkbox;
}
input[type="checkbox"]:checked + .topcoat-checkbox__checkmark:before {
background: var-background-color--before--checkbox;
}
input[type="checkbox"]:checked + .topcoat-checkbox__checkmark:after {
opacity: 1;
}
.topcoat-checkbox {
line-height: 32px;
}
.topcoat-checkbox__checkmark:before {
width: 32px;
height: 32px;
background: transparent;
background: #fff;
border: 1px solid #a64a97;
border: var-border--checkbox;
-webkit-border-radius: 3px;
border-radius: 3px;
-webkit-box-shadow: none;
box-shadow: none;
left: 0;
}
.topcoat-checkbox__checkmark {
width: 32px;
height: 32px;
}
.topcoat-checkbox__checkmark:after {
top: 7px;
left: 4px;
opacity: 0;
width: 18px;
height: 6px;
background: transparent;
border: 7px solid #a64a97;
border-width: 6px;
border-top: none;
border-right: none;
-webkit-border-radius: 2px;
border-radius: 2px;
-webkit-transform: rotate(-50deg);
-moz-transform: rotate(-50deg);
-ms-transform: rotate(-50deg);
-o-transform: rotate(-50deg);
transform: rotate(-50deg);
}
input[type="checkbox"]:focus + .topcoat-checkbox__checkmark:before {
border: none;
border: 1px solid #a64a97;
-webkit-box-shadow: none, none;
box-shadow: none, none;
}
input[type="checkbox"]:active + .topcoat-checkbox__checkmark:before {
border: 1px solid #a64a97;
border: 1px solid #a64a97;
background-color: #a64a97;
background-color: transparent;
border: 1px solid #a64a97;
-webkit-box-shadow: none;
box-shadow: none;
}
input[type="checkbox"]:disabled:active + .topcoat-checkbox__checkmark:before {
border: 1px solid #a64a97;
background: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
/* topdoc
name: List
description: Topcoat default list skin
markup:
<div class="page">
<br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
</ul>
</div>
<br>
</div>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">List</h1>
</div>
</div>
<br>
<div class="topcoat-list">
<h3 class="topcoat-list__header">Category</h3>
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
</ul>
<h3 class="topcoat-list__header">Category</h3>
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item--tappable">
<span class="topcoat-list__item__line-height">Tappable Item</span>
</li>
<li class="topcoat-list__item topcoat-list__item--tappable">
<span class="topcoat-list__item__line-height">Tappable Item</span>
</li>
</ul>
</div>
*/
/* topdoc
name: List:Noborder List
markup:
<div class="page">
<br>
<div class="topcoat-list topcoat-list--noborder">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
<li class="topcoat-list__item">
<span class="topcoat-list__item__line-height">Item</span>
</li>
</ul>
</div>
<br>
</div>
*/
/* topdoc
name: List:Category Header
markup:
<div class="topcoat-list topcoat-list--noborder">
<h3 class="topcoat-list__header">Category</h3>
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item__line-height">
Item
</li>
<li class="topcoat-list__item topcoat-list__item__line-height">
Item
</li>
</ul>
<h3 class="topcoat-list__header">Category</h3>
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item__line-height">
Item
</li>
<li class="topcoat-list__item topcoat-list__item__line-height">
Item
</li>
</ul>
</div>
*/
/* topdoc
name: List:Tappable List Item
markup:
<div class="page">
<br>
<div class="topcoat-list topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item--tappable">
<span class="topcoat-list__item__line-height">Tappable Item</span>
</li>
<li class="topcoat-list__item topcoat-list__item--tappable">
<span class="topcoat-list__item__line-height">Tappable Item</span>
</li>
</ul>
</div>
<br>
</div>
*/
.list,
.topcoat-list {
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.list__header,
.topcoat-list__header {
margin: 0;
}
.list__container,
.topcoat-list__container {
padding: 0;
margin: 0;
list-style-type: none;
}
.list__item,
.topcoat-list__item {
margin: 0;
padding: 0;
position: relative;
list-style: none;
}
.topcoat-list {
border-top: none;
border-bottom: none;
background-color: #f5f0e8;
}
.topcoat-list__header {
padding: 4px 11px;
font-size: 15px;
font-weight: 400;
background-color: #e2dcd5;
color: #666;
text-shadow: none;
border-top: none;
border-bottom: none;
}
.topcoat-list__container {
border-top: none;
color: #c6c8c8;
padding: 0;
background-color: var-background-color--list-container;
}
.topcoat-list__item {
padding: 11px;
margin: 0;
border-top: none;
border-bottom: 1px solid #b3b3b3;
color: #666;
background-color: transparent;
}
.topcoat-list__item_active:active {
background-color: #ddbed0;
}
.topcoat-list__item:first-child {
padding-left: var-padding-left--list-item--first;
margin: var-margin--list-item--first;
border-top: none;
border-bottom: var-border-bottom--list-item--first;
}
.topcoat-list__item:last-child {
padding-left: var-padding-left--list-item--last;
margin: var-margin--list-item--last;
border-top: var-border-top--list-item--last;
border-bottom: 1px solid #b3b3b3;
}
.topcoat-list__item:nth-child(2) {
border-top: var-border-top--list-item--2;
}
/* topdoc
name: Navigation Bar
description: A place where navigation goes to drink
markup:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Navigation Bar</h1>
</div>
</div>
<br><br><br>
<div class="topcoat-navigation-bar topcoat-navigation-bar--bottom">
<div class="topcoat-navigation-bar__line-height" style="text-align:center">Bottom Toolbar</div>
</div>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Navigation Bar</h1>
</div>
</div>
<div class="topcoat-navigation-bar topcoat-navigation-bar--bottom" style="position:absolute;left:0px;right:0px;bottom:0px">
<div class="topcoat-navigation-bar__line-height" style="text-align:center">Bottom Toolbar</div>
</div>
*/
/* topdoc
name: Navigation Bar:Bottom Bar
markup:
<div class="topcoat-navigation-bar topcoat-navigation-bar--bottom">
<div class="topcoat-navigation-bar__line-height" style="text-align:center">Bottom Toolbar</div>
</div>
*/
.navigation-bar,
.topcoat-navigation-bar {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
white-space: nowrap;
overflow: hidden;
word-spacing: 0;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.navigation-bar__item,
.topcoat-navigation-bar__item {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
position: relative;
display: inline-block;
vertical-align: top;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
}
.navigation-bar__title,
.topcoat-navigation-bar__title {
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.topcoat-navigation-bar {
height: 54px;
height: 44px;
padding-left: 16px;
padding-right: 16px;
background: transparent;
background: #a64a97;
color: #fff;
-webkit-box-shadow: none;
box-shadow: none;
border-bottom: 1px solid #8b8b8b;
}
.topcoat-navigation-bar__line-height {
line-height: 54px !important;
line-height: 44px !important;
}
.topcoat-navigation-bar__bg {
background: transparent;
background: #a64a97;
}
.topcoat-navigation-bar__item {
margin: 0;
line-height: 54px;
line-height: 44px;
vertical-align: top;
}
.topcoat-navigation-bar__title {
font-size: 16px;
font-weight: 500;
color: #fff;
}
.topcoat-navigation-bar--bottom {
border-bottom: none;
border-top: 1px solid #8b8b8b;
}
/* topdoc
name: Notification
description: Notification badge
markup:
<span class="topcoat-notification">1</span>
<br><br>
<span class="topcoat-notification">10</span>
<br><br>
<span class="topcoat-notification">999</span>
<br><br>
<span class="topcoat-notification">9999</span>
*/
.notification,
.topcoat-notification {
position: relative;
display: inline-block;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
text-decoration: none;
}
.topcoat-notification {
padding: 0 6px 0;
min-width: 19px;
height: 19px;
-webkit-border-radius: 19px;
border-radius: 19px;
background-color: #ec514e;
color: #fff;
}
/* topdoc
name: Page
description: Default skin for Onsen UI Page
modifiers:
markup:
<div class="page" style="height:200px">
</div>
*/
.page {
background-color: #f5f0e8;
font-weight: 200;
}
.topcoat-page__bg {
background-color: #f5f0e8;
}
/* topdoc
name: Radio Button
description: A button that can play music, but usually just plays ads.
modifiers:
markup:
<label class="topcoat-radio-button">
<input type="radio" name="topcoat" checked="checked">
<div class="topcoat-radio-button__checkmark"></div>
Label
</label>
<br>
<label class="topcoat-radio-button">
<input type="radio" name="topcoat">
<div class="topcoat-radio-button__checkmark"></div>
Label
</label>
<br>
<label class="topcoat-radio-button">
<input type="radio" name="topcoat">
<div class="topcoat-radio-button__checkmark"></div>
Label
</label>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Radio Button</h1>
</div>
</div>
<br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<label class="topcoat-radio-button" style="float:right; margin-right:8px;">
<input type="radio" name="example" checked="checked">
<div class="topcoat-radio-button__checkmark"></div>
</label>
<span class="topcoat-list__item__line-height">Label</span>
</li>
<li class="topcoat-list__item">
<label class="topcoat-radio-button" style="float:right; margin-right:8px;">
<input type="radio" name="example">
<div class="topcoat-radio-button__checkmark"></div>
</label>
<span class="topcoat-list__item__line-height">Label</span>
</li>
</ul>
</div>
*/
input[type="radio"] {
position: absolute;
overflow: hidden;
padding: 0;
border: 0;
opacity: 0.001;
z-index: 1;
vertical-align: top;
outline: none;
}
.radio-button,
.topcoat-radio-button__checkmark {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
position: relative;
display: inline-block;
vertical-align: top;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.radio-button__label,
.topcoat-radio-button {
position: relative;
display: inline-block;
vertical-align: top;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.radio-button:before,
.radio-button:after,
.topcoat-radio-button__checkmark:before,
.topcoat-radio-button__checkmark:after {
content: '';
position: absolute;
-webkit-border-radius: 100%;
border-radius: 100%;
}
.radio-button:after,
.topcoat-radio-button__checkmark:after {
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.radio-button:before,
.topcoat-radio-button__checkmark:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.radio-button--disabled,
input[type="radio"]:disabled + .topcoat-radio-button__checkmark {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
input[type="radio"] {
height: 30px;
width: 30px;
margin-top: 0;
margin-right: -30px;
margin-bottom: -30px;
margin-left: 0;
}
input[type="radio"]:checked + .topcoat-radio-button__checkmark:after {
opacity: 1;
}
.topcoat-radio-button {
color: #c6c8c8;
color: #666;
line-height: 30px;
text-align: left;
}
.topcoat-radio-button__checkmark:before {
width: 30px;
height: 30px;
background: transparent;
background: #fff;
border: 1px solid #a64a97;
border: 1px solid #b3b3b3;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-radio-button__checkmark {
position: relative;
width: 30px;
height: 30px;
}
.topcoat-radio-button__checkmark:after {
opacity: 0;
width: 14px;
height: 14px;
background: #a64a97;
border: 1px solid transparent;
-webkit-box-shadow: 0 1px rgba(255,255,255,0.5);
box-shadow: 0 1px rgba(255,255,255,0.5);
-webkit-transform: none;
-moz-transform: none;
-ms-transform: none;
-o-transform: none;
transform: none;
top: 7px;
left: 7px;
}
input[type="radio"]:focus + .topcoat-radio-button__checkmark:before {
border: none;
border: 1px solid #a64a97;
-webkit-box-shadow: none, none;
box-shadow: none, none;
}
input[type="radio"]:active + .topcoat-radio-button__checkmark:before {
border: 1px solid #a64a97;
border: 1px solid #a64a97;
background-color: #a64a97;
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
input[type="radio"]:disabled:active + .topcoat-radio-button__checkmark:before {
border: 1px solid #a64a97;
background: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
/* topdoc
name: Range
description: Range input
modifiers:
:active: Active state
:disabled: Disabled state
:focus: Focused
markup:
<input type="range" class="topcoat-range">
<input type="range" class="topcoat-range" disabled>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Range</h1>
</div>
</div>
<div style="padding:8px">
<input type="range" class="topcoat-range" style="width:100%" value="0">
</div>
<div style="padding:8px">
<input type="range" class="topcoat-range" style="width:100%" value="30">
</div>
<div style="padding:8px">
<input type="range" class="topcoat-range" style="width:100%" value="60">
</div>
<div style="padding:8px">
<input type="range" class="topcoat-range" style="width:100%" value="90">
</div>
*/
.range,
.topcoat-range {
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
vertical-align: top;
outline: none;
-webkit-appearance: none;
}
.range__thumb,
.topcoat-range::-moz-range-thumb {
cursor: pointer;
}
.range__thumb--webkit,
.topcoat-range::-webkit-slider-thumb {
cursor: pointer;
-webkit-appearance: none;
}
.range:disabled,
.topcoat-range:disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-range {
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid #a64a97;
border: none;
background-color: transparent;
background-color: #a64a97;
height: 5px;
border-radius: 0;
border-radius: 3px;
}
.topcoat-range::-moz-range-track {
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid #a64a97;
background-color: transparent;
background-color: #a64a97;
height: 5px;
border-radius: 0;
border-radius: none;
}
.topcoat-range::-webkit-slider-thumb {
height: 36px;
height: 16px;
width: 16px;
background-color: transparent;
background-color: #fff;
border: 1px solid #a64a97;
border: 1px solid #8a8a8a;
-webkit-border-radius: 4px;
border-radius: 4px;
border-radius: 50%;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-range::-moz-range-thumb {
height: 36px;
width: 16px;
background-color: transparent;
border: 1px solid #a64a97;
border: 1px solid #8a8a8a;
-webkit-border-radius: 4px;
border-radius: 4px;
border-radius: 50%;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-range:focus::-webkit-slider-thumb {
border: none;
border: 1px solid #8a8a8a;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-range:focus::-moz-range-thumb {
border: none;
border: 1px solid #8a8a8a;
-webkit-box-shadow: none;
box-shadow: none;
}
/* topdoc
name: Search Input
description: A text input designed for searching.
modifiers:
:disabled: Disabled state
markup:
<input type="search" value="" placeholder="Search" class="topcoat-search-input">
<br>
<input type="search" value="" placeholder="Search" class="topcoat-search-input" disabled>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Search Input</h1>
</div>
</div>
<div style="padding:4px">
<input type="search" value="" placeholder="Search" class="topcoat-search-input">
</div>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item topcoat-list__item__line-height">Label</li>
<li class="topcoat-list__item topcoat-list__item__line-height">Label</li>
<li class="topcoat-list__item topcoat-list__item__line-height">Label</li>
<li class="topcoat-list__item topcoat-list__item__line-height">Label</li>
</ul>
</div>
*/
.search-input,
.topcoat-search-input {
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
vertical-align: top;
outline: none;
-webkit-appearance: none;
}
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: none;
}
.search-input:disabled,
.topcoat-search-input:disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-search-input {
line-height: 36px;
height: 36px;
font-size: 16px;
border: 1px solid #a64a97;
border: none;
background-color: #fff;
background-color: #faf7f3;
-webkit-box-shadow: none;
box-shadow: none;
color: #c6c8c8;
color: var-color--search-input;
padding: 0 0 0 35px;
-webkit-border-radius: 0;
border-radius: 0;
border-radius: 4px;
background-image: url("../img/search.svg");
background-position: 16px center;
background-position: var-background-position--search-input;
background-repeat: no-repeat;
-webkit-background-size: 16px;
background-size: 16px;
}
.topcoat-search-input:focus {
background-color: #ececec;
background-color: var-background-color--search-input--focus;
color: #000;
color: var-color--search-input--focus;
border: none;
border: none;
-webkit-box-shadow: none, none;
box-shadow: none, none;
}
.topcoat-search-input::-webkit-search-cancel-button,
.topcoat-search-input::-webkit-search-decoration {
margin-right: 5px;
margin-right: var-margin-right--search-decoration;
}
.topcoat-search-input:focus::-webkit-input-placeholder {
color: #c6c8c8;
}
.topcoat-search-input:disabled::-webkit-input-placeholder {
color: #000;
}
.topcoat-search-input:disabled::-moz-placeholder {
color: #000;
}
.topcoat-search-input:disabled:-ms-input-placeholder {
color: #000;
}
/* topdoc
name: Switch
description: Default skin for Topcoat switch
modifiers:
:focus: Focus state
:disabled: Disabled state
markup:
<label class="topcoat-switch">
<input type="checkbox" class="topcoat-switch__input">
<div class="topcoat-switch__toggle"></div>
</label>
<label class="topcoat-switch">
<input type="checkbox" class="topcoat-switch__input" checked>
<div class="topcoat-switch__toggle"></div>
</label>
<label class="topcoat-switch">
<input type="checkbox" class="topcoat-switch__input" disabled>
<div class="topcoat-switch__toggle"></div>
</label>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Switch</h1>
</div>
</div>
<br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<label class="topcoat-switch" style="float:right;margin-right:8px">
<input type="checkbox" class="topcoat-switch__input">
<div class="topcoat-switch__toggle"></div>
</label>
<span class="topcoat-list__item__line-height">Label</span>
</li>
<li class="topcoat-list__item">
<label class="topcoat-switch" style="float:right;margin-right:8px">
<input type="checkbox" class="topcoat-switch__input" checked>
<div class="topcoat-switch__toggle"></div>
</label>
<span class="topcoat-list__item__line-height">Label</span>
</li>
</ul>
</div>
*/
.switch,
.topcoat-switch {
position: relative;
display: inline-block;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.switch__input,
.topcoat-switch__input {
position: absolute;
overflow: hidden;
padding: 0;
border: 0;
opacity: 0.001;
z-index: 1;
vertical-align: top;
outline: none;
}
.switch__toggle,
.topcoat-switch__toggle {
position: relative;
display: inline-block;
vertical-align: top;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.switch__toggle:before,
.switch__toggle:after,
.topcoat-switch__toggle:before,
.topcoat-switch__toggle:after {
content: '';
position: absolute;
z-index: -1;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
}
.switch--disabled,
.topcoat-switch__input:disabled + .topcoat-switch__toggle {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-switch {
font-size: 16px;
padding: 0 20px;
-webkit-border-radius: 4px;
border-radius: 4px;
border-radius: 30px;
border: 1px solid #a64a97;
border: none;
overflow: hidden;
width: 64px;
height: var-height--switch;
z-index: 0;
}
.topcoat-switch__toggle:before,
.topcoat-switch__toggle:after {
top: -1px;
width: 64px;
border: var-border--switch__label;
margin: var-margin--switch__label;
}
.topcoat-switch__toggle:before {
content: '';
color: #0083e8;
background-color: #a64a97;
right: -1px;
padding-left: 24px;
height: 24px;
top: 3px;
-webkit-border-radius: 15px;
border-radius: 15px;
}
.topcoat-switch__toggle {
line-height: 36px;
line-height: 32px;
height: 36px;
height: 32px;
width: 32px;
-webkit-border-radius: 4px;
border-radius: 4px;
border-radius: 50%;
color: #c6c8c8;
text-shadow: 0 1px none;
background-color: transparent;
background-color: #fff;
border: 1px solid #a64a97;
border: 1px solid #b3b3b3;
margin-left: -20px;
margin-bottom: 0;
margin-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
-webkit-transition: margin-left 0.05s ease-in-out;
-moz-transition: margin-left 0.05s ease-in-out;
-o-transition: margin-left 0.05s ease-in-out;
transition: margin-left 0.05s ease-in-out;
}
.topcoat-switch__toggle:after {
content: '';
background-color: #b3b3b3;
left: -1px;
padding-left: 32px;
height: 24px;
top: 3px;
-webkit-border-radius: 15px;
border-radius: 15px;
}
.topcoat-switch__input:checked + .topcoat-switch__toggle {
margin-left: 12px;
background-color: #fff;
}
.topcoat-switch__input:active + .topcoat-switch__toggle {
border: 1px solid #a64a97;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-switch__input:focus + .topcoat-switch__toggle {
border: none;
border: 1px solid #b3b3b3;
-webkit-box-shadow: none;
box-shadow: none;
}
.topcoat-switch__input:disabled + .topcoat-switch__toggle:after,
.topcoat-switch__input:disabled + .topcoat-switch__toggle:before {
background: transparent;
}
.topcoat-switch__input:checked + .topcoat-switch__toggle:after,
.topcoat-switch__input:checked + .topcoat-switch__toggle:before {
background-color: var-background-color--switch__label--checked;
-webkit-transition: var-transition--switch__label--checked;
-moz-transition: var-transition--switch__label--checked;
-o-transition: var-transition--switch__label--checked;
transition: var-transition--switch__label--checked;
}
.topcoat-switch__input + .topcoat-switch__toggle:after,
.topcoat-switch__input + .topcoat-switch__toggle:before {
background-color: var-background-color--switch__label;
-webkit-transition: var-transition--switch__label;
-moz-transition: var-transition--switch__label;
-o-transition: var-transition--switch__label;
transition: var-transition--switch__label;
}
.topcoat-switch__input:checked + .topcoat-switch__toggle:after,
box-shadow var-box-shadow--switch__label--after--checked,
.topcoat-switch__input + .topcoat-switch__toggle:after {
-webkit-box-shadow: var-box-shadow--switch__label--after;
box-shadow: var-box-shadow--switch__label--after;
}
/* topdoc
name: Tab Bar
description: Component of tab buttons
modifiers:
:disabled: Disabled state
markup:
<div class="topcoat-tab-bar">
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-a" checked="checked">
<button class="topcoat-tab-bar__button">
<div class="onsen_tab-bar__label">One</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-a">
<button class="topcoat-tab-bar__button">
<div class="onsen_tab-bar__label">Two</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-a">
<button class="topcoat-tab-bar__button">
<div class="onsen_tab-bar__label">Three</div>
</button>
</label>
</div>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Tab Bar</h1>
</div>
</div>
<div class="topcoat-tab-bar" style="position:absolute;left:0px;right:0px;bottom:0px">
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-bb">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-folder"></i>
<div class="onsen_tab-bar__label">One</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-bb">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-heart"></i>
<div class="onsen_tab-bar__label">Two</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-bb" checked="checked">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-stop"></i>
<div class="onsen_tab-bar__label">Three</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-bb">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-circle"></i>
<div class="onsen_tab-bar__label">Four</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-bb">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-cloud"></i>
<div class="onsen_tab-bar__label">Five</div>
</button>
</label>
</div>
*/
/* topdoc
name: Tab Bar:Icon + Label Tab Item
markup:
<div class="topcoat-tab-bar">
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-b" checked="checked">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-comment"></i>
<div class="onsen_tab-bar__label">Comments</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-b">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-video-camera"></i>
<div class="onsen_tab-bar__label">Videos</div>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-b">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-gear"></i>
<div class="onsen_tab-bar__label">Settings</div>
</button>
</label>
</div>
*/
/* topdoc
name: Tab Bar:Icon Only Tab Item
markup:
<div class="topcoat-tab-bar">
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-c">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-star"></i>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-c">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-comment"></i>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-c">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-circle"></i>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-c">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-play fa-rotate-270"></i>
</button>
</label>
<label class="topcoat-tab-bar__item">
<input type="radio" name="tab-bar-c" checked="checked">
<button class="topcoat-tab-bar__button">
<i class="fa fa-2x fa-gear"></i>
</button>
</label>
</div>
*/
.topcoat-tab-bar {
height: var-height--tab-bar;
background-color: #eae5e3;
border-top: 1px solid #b5b0aa;
width: 100%;
}
.topcoat-tab-bar__button {
padding: 0 20px;
height: 36px;
height: 48px;
line-height: 36px;
line-height: 48px;
letter-spacing: 1px;
color: #c6c8c8;
color: #b3b3b3;
text-shadow: 0 1px none;
vertical-align: top;
background-color: transparent;
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
border-top: 1px solid #a64a97;
border-top: none;
width: 100%;
}
.topcoat-tab-bar__button:active,
.topcoat-tab-bar__button--large:active,
:checked + .topcoat-tab-bar__button {
color: #a64a97;
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
border-top: none;
}
.topcoat-tab-bar__button:focus,
.topcoat-tab-bar__button--large:focus {
z-index: 1;
border-top: none;
-webkit-box-shadow: none, none;
box-shadow: none, none;
box-shadow: none;
outline: 0;
}
/* topdoc
name: Text Input
modifiers:
:disabled: Disabled state
:focus: Focused
:invalid: Hover state
markup:
<input type="text" class="topcoat-text-input" placeholder="text" value="">
<br>
<input type="text" class="topcoat-text-input" placeholder="text" value="" disabled>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Text Input</h1>
</div>
</div>
<br>
<div style="padding:8px">
<input type="text" class="topcoat-text-input" placeholder="text" style="width:100%">
<button class="topcoat-button--large" style="margin-top:8px">submit</button>
</div>
<br><br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<input type="text" class="topcoat-text-input--transparent" placeholder="text" style="width:100%;margin-top:4px">
</li>
</ul>
</div>
<div style="padding:8px">
<button class="topcoat-button--large">submit</button>
</div>
*/
/* topdoc
name: Text Input:Transparent Text Input
markup:
<input type="text" class="topcoat-text-input topcoat-text-input--transparent" placeholder="text" value="">
<br>
<input type="text" class="topcoat-text-input topcoat-text-input--transparent" placeholder="text" value="" disabled>
*/
/* topdoc
name: Text Input:Underbar Text Input
markup:
<input type="text" class="topcoat-text-input topcoat-text-input--underbar" placeholder="text" value="">
<br>
<input type="text" class="topcoat-text-input topcoat-text-input--underbar" placeholder="text" value="" disabled>
*/
.input,
.topcoat-text-input,
.topcoat-text-input--transparent {
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
vertical-align: top;
outline: none;
}
.input:disabled,
.topcoat-text-input:disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-text-input,
.topcoat-text-input--transparent {
line-height: 36px;
font-size: 16px;
letter-spacing: 1px;
padding: 4px 4px 4px 4px;
border: 1px solid #a64a97;
border: 1px solid #b3b3b3;
-webkit-border-radius: 4px;
border-radius: 4px;
background-color: #fff;
-webkit-box-shadow: none;
box-shadow: none;
color: #c6c8c8;
color: #000;
vertical-align: top;
}
.topcoat-text-input:focus {
background-color: #ececec;
color: #000;
color: var-color--text-input--focus;
border: none;
border: 1px solid #b3b3b3;
-webkit-box-shadow: none, none;
box-shadow: none, none;
}
.topcoat-text-input:disabled::-webkit-input-placeholder {
color: #000;
}
.topcoat-text-input:disabled::-moz-placeholder {
color: #000;
}
.topcoat-text-input:disabled:-ms-input-placeholder {
color: #000;
}
.topcoat-text-input:invalid {
border: 1px solid #f00;
color: #f00;
}
.topcoat-text-input--transparent {
border: none;
background: transparent;
padding-left: 0;
padding-right: 0;
}
.topcoat-text-input:focus {
border: none;
background: transparent;
}
.topcoat-text-input:disabled {
border: none;
background: transparent;
}
.topcoat-text-input:invalid {
border: none;
background: transparent;
}
/* topdoc
name: Textarea
description: A whole area, just for text.
modifiers:
:disabled: Disabled state
markup:
<textarea class="topcoat-textarea" rows="3" placeholder="Textarea"></textarea>
<br>
<textarea class="topcoat-textarea" rows="3" placeholder="Textarea" disabled></textarea>
showcase:
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Textarea</h1>
</div>
</div>
<div style="padding:8px">
<textarea class="topcoat-textarea" style="width:100%; height:80px; margin-bottom:8px" placeholder="Textarea"></textarea><br>
<button class="topcoat-button--large">Submit</button>
</div>
<br><br><br><br>
<div class="topcoat-list">
<ul class="topcoat-list__container">
<li class="topcoat-list__item">
<textarea class="topcoat-textarea--transparent" style="width:100%; height:80px; margin-bottom:4px" placeholder="Textarea"></textarea>
</li>
</ul>
</div>
<div style="padding:8px">
<button class="topcoat-button--large">Submit</button>
</div>
*/
/* topdoc
name: Textarea:Transparent Textarea
markup:
<textarea class="topcoat-textarea--transparent" rows="3" placeholder="Textarea"></textarea>
<br>
<textarea class="topcoat-textarea--transparent" rows="3" placeholder="Textarea" disabled></textarea>
*/
.textarea,
.topcoat-textarea,
.topcoat-textarea--transparent {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-background-clip: padding-box;
background-clip: padding-box;
padding: 0;
margin: 0;
font: inherit;
color: inherit;
background: transparent;
border: none;
vertical-align: top;
resize: none;
outline: none;
}
.textarea:disabled,
.topcoat-textarea:disabled,
.topcoat-textarea--transparent:disabled {
opacity: 0.3;
cursor: default;
pointer-events: none;
}
.topcoat-textarea,
.topcoat-textarea--transparent {
padding: 4px 4px 4px 4px;
font-size: 16px;
font-weight: 200;
-webkit-border-radius: 4px;
border-radius: 4px;
line-height: 36px;
border: 1px solid #a64a97;
border: 1px solid #b3b3b3;
background-color: #fff;
-webkit-box-shadow: none;
box-shadow: none;
color: #c6c8c8;
color: #b3b3b3;
letter-spacing: 1px;
}
.topcoat-textarea:focus,
.topcoat-textarea--transparent:focus {
background-color: #ececec;
color: #000;
color: var-color--textarea--focus;
border: none;
border: 1px solid #b3b3b3;
-webkit-box-shadow: none, none;
box-shadow: none, none;
}
.topcoat-textarea:disabled::-webkit-input-placeholder {
color: #000;
}
.topcoat-textarea:disabled::-moz-placeholder {
color: #000;
}
.topcoat-textarea:disabled:-ms-input-placeholder {
color: #000;
}
.topcoat-textarea--transparent {
border: none;
background: transparent;
padding-left: 0;
padding-right: 0;
}
.topcoat-textarea--transparent:focus {
border: none;
background: transparent;
}
.topcoat-textarea--transparent:disabled {
border: none;
background: transparent;
} |
Linux有问必答:如何检查Linux上的glibc版本
================================================================================
> **问题**:我需要找出我的Linux系统上的GNU C库(glibc)的版本,我怎样才能检查Linux上的glibc版本呢?
GNU C库(glibc)是标准C库的GNU实现。glibc是GNU工具链的关键组件,用于和二进制工具和编译器一起使用,为目标架构生成用户空间应用程序。
当从源码进行构建时,一些Linux程序可能需要链接到某个特定版本的glibc。在这种情况下,你可能想要检查已安装的glibc信息以查看是否满足依赖关系。
这里介绍几种简单的方法,方便你检查Linux上的glibc版本。
### 方法一 ###
下面给出了命令行下检查GNU C库的简单命令。
$ ldd --version

在本例中,**glibc**版本是**2.19**。
### 方法二 ###
另一个方法是在命令行“输入”**glibc 库的名称**(如,libc.so.6),就像命令一样执行。
输出结果会显示更多关于**glibc库**的详细信息,包括glibc的版本以及使用的GNU编译器,也提供了glibc扩展的信息。glibc变量的位置取决于Linux版本和处理器架构。
在基于Debian的64位系统上:
$ /lib/x86_64-linux-gnu/libc.so.6
在基于Debian的32位系统上:
$ /lib/i386-linux-gnu/libc.so.6
在基于Red Hat的64位系统上:
$ /lib64/libc.so.6
在基于Red Hat的32位系统上:
$ /lib/libc.so.6
下图中是输入glibc库后的输出结果样例。

--------------------------------------------------------------------------------
via: http://ask.xmodulo.com/check-glibc-version-linux.html
译者:[GOLinux](https://github.com/GOLinux)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="../../../" />
<script src="list.js"></script>
<script src="page.js"></script>
<link type="text/css" rel="stylesheet" href="page.css" />
</head>
<body>
[page:Curve] →
<h1>[name]</h1>
<div class="desc">
An abstract base class further extending [page:Curve]. A CurvePath is simply an array of connected curves,
but retains the api of a curve.
</div>
<h2>Constructor</h2>
<h3>[name]()</h3>
<div>
The constructor take no parameters.
</div>
<h2>Properties</h2>
<h3>[property:array curves]</h3>
<div>
The array of [page:Curve]s
</div>
<h3>[property:array bends]</h3>
<div>
An array of [page:Curve]s used to transform and bend the curve using [page:CurvePath.getWrapPoints].
</div>
<h3>[property:boolean autoClose]</h3>
<div>
Whether or not to automatically close the path.
</div>
<h2>Methods</h2>
<h3>[method:Array getWrapPoints]([page:Array vertices], [page:Curve curve])</h3>
<div>
vertices -- An array of [page:Vector2]s to modify<br />
curve -- An array of 2d [page:Curve]s
</div>
<div>
Modifies the array of vertices by warping it by the curve. The curve parameter also accepts objects with similar
interfaces such as [page:CurvePath], [page:Path], [page:SplineCurve], etc. Returns the original vertices after
modification.
</div>
<h3>[method:null addWrapPath]([page:Curve curve])</h3>
<div>
curve -- A [page:Curve] or object with a similar interface.
</div>
<div>
Pushes a curve onto the bends array.
</div>
<h3>[method:Geometry createGeometry]([page:Vector3 points])</h3>
<div>
points -- An array of [page:Vector3]s
</div>
<div>
Creates a geometry from points
</div>
<h3>[method:Geometry createPointsGeometry]([page:Integer divisions])</h3>
<div>
divisions -- How many segments to create with [page:Vector3]s. Defaults to 12.
</div>
<div>
Creates a [page:Geometry] object comprised of [page:Vector3]s
</div>
<h3>[method:Geometry createSpacedPointsGeometry]([page:Integer divisions])</h3>
<div>
divisions -- How many segments to create with [page:Vector3]s. Defaults to 12.
</div>
<div>
Creates a [page:Geometry] object comprised of [page:Vector3]s that are equidistant.
</div>
<h3>[method:null add]([page:Curve curve])</h3>
<div>
curve -- The [page:Curve curve] to add
</div>
<div>
Pushes a curve onto the curves array.
</div>
<h3>[method:null closePath]()</h3>
<div>
Adds a curve to close the path.
</div>
<h3>[method:Object getBoundingBox]()</h3>
<div>
Returns an object with the keys minX, minY, maxX, maxY, (if 3d: maxZ, minZ)
</div>
<h3>[method:Float getCurveLengths]()</h3>
<div>
Adds together the length of the curves
</div>
<h3>[method:Array getTransformedPoints]([page:Integer segments], [page:Array bends])</h3>
<div>
segments -- The number of segments to create using the getPoints()<br />
bends -- (optional) An array of [page:Curve]s used to transform the points. Defaults to this.bends if blank.
</div>
<div>
Uses this CurvePath to generate a series of points transformed by the curves in the bends array. Returns an
array of [page:Vector2]s.
</div>
<h3>[method:Array getTransformedSpacedPoints]([page:Integer segments], [page:Array bends])</h3>
<div>
segments -- The number of segments to create using the getPoints()<br />
bends -- (optional) Defaults to this.bends if blank. An array of [page:Curve]s used to transform the points.
</div>
<div>
Uses this CurvePath to generate a series equidistant points that are then transformed by the curves in the bends.
Returns an array of [page:Vector2]s.
</div>
<h2>Source</h2>
[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]
</body>
</html>
|
@echo off
REM
REM Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
REM DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
REM
REM This code is free software; you can redistribute it and/or modify it
REM under the terms of the GNU General Public License version 2 only, as
REM published by the Free Software Foundation.
REM
REM This code is distributed in the hope that it will be useful, but WITHOUT
REM ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
REM FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
REM version 2 for more details (a copy is included in the LICENSE file that
REM accompanied this code).
REM
REM You should have received a copy of the GNU General Public License version
REM 2 along with this work; if not, write to the Free Software Foundation,
REM Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
REM
REM Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
REM or visit www.oracle.com if you need additional information or have any
REM questions.
REM
REM
call saenv.bat
REM check for .\sa.jar, if it does not exist
REM assume that we are in build configuration.
if not exist .\sa.jar goto IN_BUILD_CONF
set SA_CLASSPATH=.\sa.jar
goto EXEC_CMD
:IN_BUILD_CONF
set SA_CLASSPATH=..\build\classes
:EXEC_CMD
%SA_JAVA% -classpath %SA_CLASSPATH% -Djava.rmi.server.codebase=file:/%SA_CLASSPATH% -Djava.security.policy=grantAll.policy -Djava.library.path=%SA_LIBPATH% %OPTIONS% sun.jvm.hotspot.DebugServer %1 %2 %3 %4 %5 %6 %7 %8 %9
|
/////////////////////////////////////////////////////////////////////////////
// Name: src/osx/artmac.cpp
// Purpose: wxArtProvider instance with native Mac stock icons
// Author: Alan Shouls
// Created: 2006-10-30
// Copyright: (c) wxWindows team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if defined(__BORLANDC__)
#pragma hdrstop
#endif
#include "wx/artprov.h"
#ifndef WX_PRECOMP
#include "wx/image.h"
#endif
#include "wx/osx/private.h"
// ----------------------------------------------------------------------------
// wxMacArtProvider
// ----------------------------------------------------------------------------
class wxMacArtProvider : public wxArtProvider
{
protected:
#if wxOSX_USE_COCOA_OR_CARBON
virtual wxIconBundle CreateIconBundle(const wxArtID& id,
const wxArtClient& client);
#endif
#if wxOSX_USE_COCOA_OR_IPHONE
virtual wxBitmap CreateBitmap(const wxArtID& id,
const wxArtClient& client,
const wxSize& size)
{
return wxOSXCreateSystemBitmap(id, client, size);
}
#endif
};
/* static */ void wxArtProvider::InitNativeProvider()
{
PushBack(new wxMacArtProvider);
}
#if wxOSX_USE_COCOA_OR_CARBON
// ----------------------------------------------------------------------------
// helper macros
// ----------------------------------------------------------------------------
#define CREATE_STD_ICON(iconId, xpmRc) \
{ \
wxIconBundle icon(wxT(iconId), wxBITMAP_TYPE_ICON_RESOURCE); \
return icon; \
}
// Macro used in CreateBitmap to get wxICON_FOO icons:
#define ART_MSGBOX(artId, iconId, xpmRc) \
if ( id == artId ) \
{ \
CREATE_STD_ICON(#iconId, xpmRc) \
}
static wxIconBundle wxMacArtProvider_CreateIconBundle(const wxArtID& id)
{
ART_MSGBOX(wxART_ERROR, wxICON_ERROR, error)
ART_MSGBOX(wxART_INFORMATION, wxICON_INFORMATION, info)
ART_MSGBOX(wxART_WARNING, wxICON_WARNING, warning)
ART_MSGBOX(wxART_QUESTION, wxICON_QUESTION, question)
ART_MSGBOX(wxART_FOLDER, wxICON_FOLDER, folder)
ART_MSGBOX(wxART_FOLDER_OPEN, wxICON_FOLDER_OPEN, folder_open)
ART_MSGBOX(wxART_NORMAL_FILE, wxICON_NORMAL_FILE, deffile)
ART_MSGBOX(wxART_EXECUTABLE_FILE, wxICON_EXECUTABLE_FILE, exefile)
ART_MSGBOX(wxART_CDROM, wxICON_CDROM, cdrom)
ART_MSGBOX(wxART_FLOPPY, wxICON_FLOPPY, floppy)
ART_MSGBOX(wxART_HARDDISK, wxICON_HARDDISK, harddisk)
ART_MSGBOX(wxART_REMOVABLE, wxICON_REMOVABLE, removable)
ART_MSGBOX(wxART_DELETE, wxICON_DELETE, delete)
ART_MSGBOX(wxART_GO_BACK, wxICON_GO_BACK, back)
ART_MSGBOX(wxART_GO_FORWARD, wxICON_GO_FORWARD, forward)
ART_MSGBOX(wxART_GO_HOME, wxICON_GO_HOME, home)
ART_MSGBOX(wxART_HELP_SETTINGS, wxICON_HELP_SETTINGS, htmoptns)
ART_MSGBOX(wxART_HELP_PAGE, wxICON_HELP_PAGE, htmpage)
return wxNullIconBundle;
}
// ----------------------------------------------------------------------------
// CreateIconBundle
// ----------------------------------------------------------------------------
wxIconBundle wxMacArtProvider::CreateIconBundle(const wxArtID& id, const wxArtClient& client)
{
// On the Mac folders in lists are always drawn closed, so if an open
// folder icon is asked for we will ask for a closed one in its place
if ( client == wxART_LIST && id == wxART_FOLDER_OPEN )
return wxMacArtProvider_CreateIconBundle(wxART_FOLDER);
return wxMacArtProvider_CreateIconBundle(id);
}
#endif
// ----------------------------------------------------------------------------
// wxArtProvider::GetNativeSizeHint()
// ----------------------------------------------------------------------------
/*static*/
wxSize wxArtProvider::GetNativeSizeHint(const wxArtClient& client)
{
if ( client == wxART_TOOLBAR )
{
// See http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIcons/chapter_15_section_9.html:
// "32 x 32 pixels is the recommended size"
return wxSize(32, 32);
}
else if ( client == wxART_BUTTON || client == wxART_MENU )
{
// Mac UI doesn't use any images in neither buttons nor menus in
// general but the code using wxArtProvider can use wxART_BUTTON to
// find the icons of a roughly appropriate size for the buttons and
// 16x16 seems to be the best choice for this kind of use
return wxSize(16, 16);
}
return wxDefaultSize;
}
|
<a href='https://github.com/angular/angular.js/edit/v1.5.x/docs/content/error/$sce/iequirks.ngdoc?message=docs(error%2Fiequirks)%3A%20describe%20your%20change...' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<h1>Error: $sce:iequirks
<div><span class='hint'>IE<11 in quirks mode is unsupported</span></div>
</h1>
<div>
<pre class="minerr-errmsg" error-display="Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks mode. You can fix this by adding the text <!doctype html> to the top of your HTML document. See http://docs.angularjs.org/api/ng.$sce for more information.">Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks mode. You can fix this by adding the text <!doctype html> to the top of your HTML document. See http://docs.angularjs.org/api/ng.$sce for more information.</pre>
</div>
<h2>Description</h2>
<div class="description">
<p>This error occurs when you are using AngularJS with <a href="api/ng/service/$sce">Strict Contextual Escaping (SCE)</a> mode enabled (the default) on IE10 or lower in quirks mode.</p>
<p>In this mode, IE<11 allow one to execute arbitrary javascript by the use of the <code>expression()</code> syntax and is not supported.
Refer
<a href="http://msdn.microsoft.com/en-us/library/ie/dn384050(v=vs.85">CSS expressions no longer supported for the Internet zone</a>.aspx)
to learn more about them.</p>
<p>To resolve this error please specify the proper doctype at the top of your main html document:</p>
<pre><code><!doctype html>
</code></pre>
</div>
|
/*
* max7359_keypad.c - MAX7359 Key Switch Controller Driver
*
* Copyright (C) 2009 Samsung Electronics
* Kim Kyuwon <q1.kim@samsung.com>
*
* Based on pxa27x_keypad.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Datasheet: http://www.maxim-ic.com/quick_view2.cfm/qv_pk/5456
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pm.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#define MAX7359_MAX_KEY_ROWS 8
#define MAX7359_MAX_KEY_COLS 8
#define MAX7359_MAX_KEY_NUM (MAX7359_MAX_KEY_ROWS * MAX7359_MAX_KEY_COLS)
#define MAX7359_ROW_SHIFT 3
/*
* MAX7359 registers
*/
#define MAX7359_REG_KEYFIFO 0x00
#define MAX7359_REG_CONFIG 0x01
#define MAX7359_REG_DEBOUNCE 0x02
#define MAX7359_REG_INTERRUPT 0x03
#define MAX7359_REG_PORTS 0x04
#define MAX7359_REG_KEYREP 0x05
#define MAX7359_REG_SLEEP 0x06
/*
* Configuration register bits
*/
#define MAX7359_CFG_SLEEP (1 << 7)
#define MAX7359_CFG_INTERRUPT (1 << 5)
#define MAX7359_CFG_KEY_RELEASE (1 << 3)
#define MAX7359_CFG_WAKEUP (1 << 1)
#define MAX7359_CFG_TIMEOUT (1 << 0)
/*
* Autosleep register values (ms)
*/
#define MAX7359_AUTOSLEEP_8192 0x01
#define MAX7359_AUTOSLEEP_4096 0x02
#define MAX7359_AUTOSLEEP_2048 0x03
#define MAX7359_AUTOSLEEP_1024 0x04
#define MAX7359_AUTOSLEEP_512 0x05
#define MAX7359_AUTOSLEEP_256 0x06
struct max7359_keypad {
/* matrix key code map */
unsigned short keycodes[MAX7359_MAX_KEY_NUM];
struct input_dev *input_dev;
struct i2c_client *client;
};
static int max7359_write_reg(struct i2c_client *client, u8 reg, u8 val)
{
int ret = i2c_smbus_write_byte_data(client, reg, val);
if (ret < 0)
dev_err(&client->dev, "%s: reg 0x%x, val 0x%x, err %d\n",
__func__, reg, val, ret);
return ret;
}
static int max7359_read_reg(struct i2c_client *client, int reg)
{
int ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
dev_err(&client->dev, "%s: reg 0x%x, err %d\n",
__func__, reg, ret);
return ret;
}
static void max7359_build_keycode(struct max7359_keypad *keypad,
const struct matrix_keymap_data *keymap_data)
{
struct input_dev *input_dev = keypad->input_dev;
int i;
for (i = 0; i < keymap_data->keymap_size; i++) {
unsigned int key = keymap_data->keymap[i];
unsigned int row = KEY_ROW(key);
unsigned int col = KEY_COL(key);
unsigned int scancode = MATRIX_SCAN_CODE(row, col,
MAX7359_ROW_SHIFT);
unsigned short keycode = KEY_VAL(key);
keypad->keycodes[scancode] = keycode;
__set_bit(keycode, input_dev->keybit);
}
__clear_bit(KEY_RESERVED, input_dev->keybit);
}
/* runs in an IRQ thread -- can (and will!) sleep */
static irqreturn_t max7359_interrupt(int irq, void *dev_id)
{
struct max7359_keypad *keypad = dev_id;
struct input_dev *input_dev = keypad->input_dev;
int val, row, col, release, code;
val = max7359_read_reg(keypad->client, MAX7359_REG_KEYFIFO);
row = val & 0x7;
col = (val >> 3) & 0x7;
release = val & 0x40;
code = MATRIX_SCAN_CODE(row, col, MAX7359_ROW_SHIFT);
dev_dbg(&keypad->client->dev,
"key[%d:%d] %s\n", row, col, release ? "release" : "press");
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad->keycodes[code], !release);
input_sync(input_dev);
return IRQ_HANDLED;
}
/*
* Let MAX7359 fall into a deep sleep:
* If no keys are pressed, enter sleep mode for 8192 ms. And if any
* key is pressed, the MAX7359 returns to normal operating mode.
*/
static inline void max7359_fall_deepsleep(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_8192);
}
/*
* Let MAX7359 take a catnap:
* Autosleep just for 256 ms.
*/
static inline void max7359_take_catnap(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_256);
}
static int max7359_open(struct input_dev *dev)
{
struct max7359_keypad *keypad = input_get_drvdata(dev);
max7359_take_catnap(keypad->client);
return 0;
}
static void max7359_close(struct input_dev *dev)
{
struct max7359_keypad *keypad = input_get_drvdata(dev);
max7359_fall_deepsleep(keypad->client);
}
static void max7359_initialize(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_CONFIG,
MAX7359_CFG_INTERRUPT | /* Irq clears after host read */
MAX7359_CFG_KEY_RELEASE | /* Key release enable */
MAX7359_CFG_WAKEUP); /* Key press wakeup enable */
/* Full key-scan functionality */
max7359_write_reg(client, MAX7359_REG_DEBOUNCE, 0x1F);
/* nINT asserts every debounce cycles */
max7359_write_reg(client, MAX7359_REG_INTERRUPT, 0x01);
max7359_fall_deepsleep(client);
}
static int max7359_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
const struct matrix_keymap_data *keymap_data =
dev_get_platdata(&client->dev);
struct max7359_keypad *keypad;
struct input_dev *input_dev;
int ret;
int error;
if (!client->irq) {
dev_err(&client->dev, "The irq number should not be zero\n");
return -EINVAL;
}
/* Detect MAX7359: The initial Keys FIFO value is '0x3F' */
ret = max7359_read_reg(client, MAX7359_REG_KEYFIFO);
if (ret < 0) {
dev_err(&client->dev, "failed to detect device\n");
return -ENODEV;
}
dev_dbg(&client->dev, "keys FIFO is 0x%02x\n", ret);
keypad = devm_kzalloc(&client->dev, sizeof(struct max7359_keypad),
GFP_KERNEL);
if (!keypad) {
dev_err(&client->dev, "failed to allocate memory\n");
return -ENOMEM;
}
input_dev = devm_input_allocate_device(&client->dev);
if (!input_dev) {
dev_err(&client->dev, "failed to allocate input device\n");
return -ENOMEM;
}
keypad->client = client;
keypad->input_dev = input_dev;
input_dev->name = client->name;
input_dev->id.bustype = BUS_I2C;
input_dev->open = max7359_open;
input_dev->close = max7359_close;
input_dev->dev.parent = &client->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_dev->keycodesize = sizeof(keypad->keycodes[0]);
input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes);
input_dev->keycode = keypad->keycodes;
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, keypad);
max7359_build_keycode(keypad, keymap_data);
error = devm_request_threaded_irq(&client->dev, client->irq, NULL,
max7359_interrupt,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
client->name, keypad);
if (error) {
dev_err(&client->dev, "failed to register interrupt\n");
return error;
}
/* Register the input device */
error = input_register_device(input_dev);
if (error) {
dev_err(&client->dev, "failed to register input device\n");
return error;
}
/* Initialize MAX7359 */
max7359_initialize(client);
i2c_set_clientdata(client, keypad);
device_init_wakeup(&client->dev, 1);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int max7359_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
max7359_fall_deepsleep(client);
if (device_may_wakeup(&client->dev))
enable_irq_wake(client->irq);
return 0;
}
static int max7359_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
if (device_may_wakeup(&client->dev))
disable_irq_wake(client->irq);
/* Restore the default setting */
max7359_take_catnap(client);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(max7359_pm, max7359_suspend, max7359_resume);
static const struct i2c_device_id max7359_ids[] = {
{ "max7359", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max7359_ids);
static struct i2c_driver max7359_i2c_driver = {
.driver = {
.name = "max7359",
.pm = &max7359_pm,
},
.probe = max7359_probe,
.id_table = max7359_ids,
};
module_i2c_driver(max7359_i2c_driver);
MODULE_AUTHOR("Kim Kyuwon <q1.kim@samsung.com>");
MODULE_DESCRIPTION("MAX7359 Key Switch Controller Driver");
MODULE_LICENSE("GPL v2");
|
/* crypto/evp/evp.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_ENVELOPE_H
#define HEADER_ENVELOPE_H
#ifdef OPENSSL_ALGORITHM_DEFINES
# include <openssl/opensslconf.h>
#else
# define OPENSSL_ALGORITHM_DEFINES
# include <openssl/opensslconf.h>
# undef OPENSSL_ALGORITHM_DEFINES
#endif
#include <openssl/ossl_typ.h>
#include <openssl/symhacks.h>
#ifndef OPENSSL_NO_BIO
#include <openssl/bio.h>
#endif
/*
#define EVP_RC2_KEY_SIZE 16
#define EVP_RC4_KEY_SIZE 16
#define EVP_BLOWFISH_KEY_SIZE 16
#define EVP_CAST5_KEY_SIZE 16
#define EVP_RC5_32_12_16_KEY_SIZE 16
*/
#define EVP_MAX_MD_SIZE 64 /* longest known is SHA512 */
#define EVP_MAX_KEY_LENGTH 64
#define EVP_MAX_IV_LENGTH 16
#define EVP_MAX_BLOCK_LENGTH 32
#define PKCS5_SALT_LEN 8
/* Default PKCS#5 iteration count */
#define PKCS5_DEFAULT_ITER 2048
#include <openssl/objects.h>
#define EVP_PK_RSA 0x0001
#define EVP_PK_DSA 0x0002
#define EVP_PK_DH 0x0004
#define EVP_PK_EC 0x0008
#define EVP_PKT_SIGN 0x0010
#define EVP_PKT_ENC 0x0020
#define EVP_PKT_EXCH 0x0040
#define EVP_PKS_RSA 0x0100
#define EVP_PKS_DSA 0x0200
#define EVP_PKS_EC 0x0400
#define EVP_PKT_EXP 0x1000 /* <= 512 bit key */
#define EVP_PKEY_NONE NID_undef
#define EVP_PKEY_RSA NID_rsaEncryption
#define EVP_PKEY_RSA2 NID_rsa
#define EVP_PKEY_DSA NID_dsa
#define EVP_PKEY_DSA1 NID_dsa_2
#define EVP_PKEY_DSA2 NID_dsaWithSHA
#define EVP_PKEY_DSA3 NID_dsaWithSHA1
#define EVP_PKEY_DSA4 NID_dsaWithSHA1_2
#define EVP_PKEY_DH NID_dhKeyAgreement
#define EVP_PKEY_EC NID_X9_62_id_ecPublicKey
#define EVP_PKEY_HMAC NID_hmac
#define EVP_PKEY_CMAC NID_cmac
#ifdef __cplusplus
extern "C" {
#endif
/* Type needs to be a bit field
* Sub-type needs to be for variations on the method, as in, can it do
* arbitrary encryption.... */
struct evp_pkey_st
{
int type;
int save_type;
int references;
const EVP_PKEY_ASN1_METHOD *ameth;
ENGINE *engine;
union {
char *ptr;
#ifndef OPENSSL_NO_RSA
struct rsa_st *rsa; /* RSA */
#endif
#ifndef OPENSSL_NO_DSA
struct dsa_st *dsa; /* DSA */
#endif
#ifndef OPENSSL_NO_DH
struct dh_st *dh; /* DH */
#endif
#ifndef OPENSSL_NO_EC
struct ec_key_st *ec; /* ECC */
#endif
} pkey;
int save_parameters;
STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */
} /* EVP_PKEY */;
#define EVP_PKEY_MO_SIGN 0x0001
#define EVP_PKEY_MO_VERIFY 0x0002
#define EVP_PKEY_MO_ENCRYPT 0x0004
#define EVP_PKEY_MO_DECRYPT 0x0008
#ifndef EVP_MD
struct env_md_st
{
int type;
int pkey_type;
int md_size;
unsigned long flags;
int (*init)(EVP_MD_CTX *ctx);
int (*update)(EVP_MD_CTX *ctx,const void *data,size_t count);
int (*final)(EVP_MD_CTX *ctx,unsigned char *md);
int (*copy)(EVP_MD_CTX *to,const EVP_MD_CTX *from);
int (*cleanup)(EVP_MD_CTX *ctx);
/* FIXME: prototype these some day */
int (*sign)(int type, const unsigned char *m, unsigned int m_length,
unsigned char *sigret, unsigned int *siglen, void *key);
int (*verify)(int type, const unsigned char *m, unsigned int m_length,
const unsigned char *sigbuf, unsigned int siglen,
void *key);
int required_pkey_type[5]; /*EVP_PKEY_xxx */
int block_size;
int ctx_size; /* how big does the ctx->md_data need to be */
/* control function */
int (*md_ctrl)(EVP_MD_CTX *ctx, int cmd, int p1, void *p2);
} /* EVP_MD */;
typedef int evp_sign_method(int type,const unsigned char *m,
unsigned int m_length,unsigned char *sigret,
unsigned int *siglen, void *key);
typedef int evp_verify_method(int type,const unsigned char *m,
unsigned int m_length,const unsigned char *sigbuf,
unsigned int siglen, void *key);
#define EVP_MD_FLAG_ONESHOT 0x0001 /* digest can only handle a single
* block */
#define EVP_MD_FLAG_PKEY_DIGEST 0x0002 /* digest is a "clone" digest used
* which is a copy of an existing
* one for a specific public key type.
* EVP_dss1() etc */
/* Digest uses EVP_PKEY_METHOD for signing instead of MD specific signing */
#define EVP_MD_FLAG_PKEY_METHOD_SIGNATURE 0x0004
/* DigestAlgorithmIdentifier flags... */
#define EVP_MD_FLAG_DIGALGID_MASK 0x0018
/* NULL or absent parameter accepted. Use NULL */
#define EVP_MD_FLAG_DIGALGID_NULL 0x0000
/* NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent */
#define EVP_MD_FLAG_DIGALGID_ABSENT 0x0008
/* Custom handling via ctrl */
#define EVP_MD_FLAG_DIGALGID_CUSTOM 0x0018
#define EVP_MD_FLAG_FIPS 0x0400 /* Note if suitable for use in FIPS mode */
/* Digest ctrls */
#define EVP_MD_CTRL_DIGALGID 0x1
#define EVP_MD_CTRL_MICALG 0x2
/* Minimum Algorithm specific ctrl value */
#define EVP_MD_CTRL_ALG_CTRL 0x1000
#define EVP_PKEY_NULL_method NULL,NULL,{0,0,0,0}
#ifndef OPENSSL_NO_DSA
#define EVP_PKEY_DSA_method (evp_sign_method *)DSA_sign, \
(evp_verify_method *)DSA_verify, \
{EVP_PKEY_DSA,EVP_PKEY_DSA2,EVP_PKEY_DSA3, \
EVP_PKEY_DSA4,0}
#else
#define EVP_PKEY_DSA_method EVP_PKEY_NULL_method
#endif
#ifndef OPENSSL_NO_ECDSA
#define EVP_PKEY_ECDSA_method (evp_sign_method *)ECDSA_sign, \
(evp_verify_method *)ECDSA_verify, \
{EVP_PKEY_EC,0,0,0}
#else
#define EVP_PKEY_ECDSA_method EVP_PKEY_NULL_method
#endif
#ifndef OPENSSL_NO_RSA
#define EVP_PKEY_RSA_method (evp_sign_method *)RSA_sign, \
(evp_verify_method *)RSA_verify, \
{EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0}
#define EVP_PKEY_RSA_ASN1_OCTET_STRING_method \
(evp_sign_method *)RSA_sign_ASN1_OCTET_STRING, \
(evp_verify_method *)RSA_verify_ASN1_OCTET_STRING, \
{EVP_PKEY_RSA,EVP_PKEY_RSA2,0,0}
#else
#define EVP_PKEY_RSA_method EVP_PKEY_NULL_method
#define EVP_PKEY_RSA_ASN1_OCTET_STRING_method EVP_PKEY_NULL_method
#endif
#endif /* !EVP_MD */
struct env_md_ctx_st
{
const EVP_MD *digest;
ENGINE *engine; /* functional reference if 'digest' is ENGINE-provided */
unsigned long flags;
void *md_data;
/* Public key context for sign/verify */
EVP_PKEY_CTX *pctx;
/* Update function: usually copied from EVP_MD */
int (*update)(EVP_MD_CTX *ctx,const void *data,size_t count);
} /* EVP_MD_CTX */;
/* values for EVP_MD_CTX flags */
#define EVP_MD_CTX_FLAG_ONESHOT 0x0001 /* digest update will be called
* once only */
#define EVP_MD_CTX_FLAG_CLEANED 0x0002 /* context has already been
* cleaned */
#define EVP_MD_CTX_FLAG_REUSE 0x0004 /* Don't free up ctx->md_data
* in EVP_MD_CTX_cleanup */
/* FIPS and pad options are ignored in 1.0.0, definitions are here
* so we don't accidentally reuse the values for other purposes.
*/
#define EVP_MD_CTX_FLAG_NON_FIPS_ALLOW 0x0008 /* Allow use of non FIPS digest
* in FIPS mode */
/* The following PAD options are also currently ignored in 1.0.0, digest
* parameters are handled through EVP_DigestSign*() and EVP_DigestVerify*()
* instead.
*/
#define EVP_MD_CTX_FLAG_PAD_MASK 0xF0 /* RSA mode to use */
#define EVP_MD_CTX_FLAG_PAD_PKCS1 0x00 /* PKCS#1 v1.5 mode */
#define EVP_MD_CTX_FLAG_PAD_X931 0x10 /* X9.31 mode */
#define EVP_MD_CTX_FLAG_PAD_PSS 0x20 /* PSS mode */
#define EVP_MD_CTX_FLAG_NO_INIT 0x0100 /* Don't initialize md_data */
struct evp_cipher_st
{
int nid;
int block_size;
int key_len; /* Default value for variable length ciphers */
int iv_len;
unsigned long flags; /* Various flags */
int (*init)(EVP_CIPHER_CTX *ctx, const unsigned char *key,
const unsigned char *iv, int enc); /* init key */
int (*do_cipher)(EVP_CIPHER_CTX *ctx, unsigned char *out,
const unsigned char *in, size_t inl);/* encrypt/decrypt data */
int (*cleanup)(EVP_CIPHER_CTX *); /* cleanup ctx */
int ctx_size; /* how big ctx->cipher_data needs to be */
int (*set_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); /* Populate a ASN1_TYPE with parameters */
int (*get_asn1_parameters)(EVP_CIPHER_CTX *, ASN1_TYPE *); /* Get parameters from a ASN1_TYPE */
int (*ctrl)(EVP_CIPHER_CTX *, int type, int arg, void *ptr); /* Miscellaneous operations */
void *app_data; /* Application data */
} /* EVP_CIPHER */;
/* Values for cipher flags */
/* Modes for ciphers */
#define EVP_CIPH_STREAM_CIPHER 0x0
#define EVP_CIPH_ECB_MODE 0x1
#define EVP_CIPH_CBC_MODE 0x2
#define EVP_CIPH_CFB_MODE 0x3
#define EVP_CIPH_OFB_MODE 0x4
#define EVP_CIPH_CTR_MODE 0x5
#define EVP_CIPH_GCM_MODE 0x6
#define EVP_CIPH_CCM_MODE 0x7
#define EVP_CIPH_XTS_MODE 0x10001
#define EVP_CIPH_MODE 0xF0007
/* Set if variable length cipher */
#define EVP_CIPH_VARIABLE_LENGTH 0x8
/* Set if the iv handling should be done by the cipher itself */
#define EVP_CIPH_CUSTOM_IV 0x10
/* Set if the cipher's init() function should be called if key is NULL */
#define EVP_CIPH_ALWAYS_CALL_INIT 0x20
/* Call ctrl() to init cipher parameters */
#define EVP_CIPH_CTRL_INIT 0x40
/* Don't use standard key length function */
#define EVP_CIPH_CUSTOM_KEY_LENGTH 0x80
/* Don't use standard block padding */
#define EVP_CIPH_NO_PADDING 0x100
/* cipher handles random key generation */
#define EVP_CIPH_RAND_KEY 0x200
/* cipher has its own additional copying logic */
#define EVP_CIPH_CUSTOM_COPY 0x400
/* Allow use default ASN1 get/set iv */
#define EVP_CIPH_FLAG_DEFAULT_ASN1 0x1000
/* Buffer length in bits not bytes: CFB1 mode only */
#define EVP_CIPH_FLAG_LENGTH_BITS 0x2000
/* Note if suitable for use in FIPS mode */
#define EVP_CIPH_FLAG_FIPS 0x4000
/* Allow non FIPS cipher in FIPS mode */
#define EVP_CIPH_FLAG_NON_FIPS_ALLOW 0x8000
/* Cipher handles any and all padding logic as well
* as finalisation.
*/
#define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x100000
#define EVP_CIPH_FLAG_AEAD_CIPHER 0x200000
/* ctrl() values */
#define EVP_CTRL_INIT 0x0
#define EVP_CTRL_SET_KEY_LENGTH 0x1
#define EVP_CTRL_GET_RC2_KEY_BITS 0x2
#define EVP_CTRL_SET_RC2_KEY_BITS 0x3
#define EVP_CTRL_GET_RC5_ROUNDS 0x4
#define EVP_CTRL_SET_RC5_ROUNDS 0x5
#define EVP_CTRL_RAND_KEY 0x6
#define EVP_CTRL_PBE_PRF_NID 0x7
#define EVP_CTRL_COPY 0x8
#define EVP_CTRL_GCM_SET_IVLEN 0x9
#define EVP_CTRL_GCM_GET_TAG 0x10
#define EVP_CTRL_GCM_SET_TAG 0x11
#define EVP_CTRL_GCM_SET_IV_FIXED 0x12
#define EVP_CTRL_GCM_IV_GEN 0x13
#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN
#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG
#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG
#define EVP_CTRL_CCM_SET_L 0x14
#define EVP_CTRL_CCM_SET_MSGLEN 0x15
/* AEAD cipher deduces payload length and returns number of bytes
* required to store MAC and eventual padding. Subsequent call to
* EVP_Cipher even appends/verifies MAC.
*/
#define EVP_CTRL_AEAD_TLS1_AAD 0x16
/* Used by composite AEAD ciphers, no-op in GCM, CCM... */
#define EVP_CTRL_AEAD_SET_MAC_KEY 0x17
/* Set the GCM invocation field, decrypt only */
#define EVP_CTRL_GCM_SET_IV_INV 0x18
/* GCM TLS constants */
/* Length of fixed part of IV derived from PRF */
#define EVP_GCM_TLS_FIXED_IV_LEN 4
/* Length of explicit part of IV part of TLS records */
#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8
/* Length of tag for TLS */
#define EVP_GCM_TLS_TAG_LEN 16
typedef struct evp_cipher_info_st
{
const EVP_CIPHER *cipher;
unsigned char iv[EVP_MAX_IV_LENGTH];
} EVP_CIPHER_INFO;
struct evp_cipher_ctx_st
{
const EVP_CIPHER *cipher;
ENGINE *engine; /* functional reference if 'cipher' is ENGINE-provided */
int encrypt; /* encrypt or decrypt */
int buf_len; /* number we have left */
unsigned char oiv[EVP_MAX_IV_LENGTH]; /* original iv */
unsigned char iv[EVP_MAX_IV_LENGTH]; /* working iv */
unsigned char buf[EVP_MAX_BLOCK_LENGTH];/* saved partial block */
int num; /* used by cfb/ofb/ctr mode */
void *app_data; /* application stuff */
int key_len; /* May change for variable length cipher */
unsigned long flags; /* Various flags */
void *cipher_data; /* per EVP data */
int final_used;
int block_mask;
unsigned char final[EVP_MAX_BLOCK_LENGTH];/* possible final block */
} /* EVP_CIPHER_CTX */;
typedef struct evp_Encode_Ctx_st
{
int num; /* number saved in a partial encode/decode */
int length; /* The length is either the output line length
* (in input bytes) or the shortest input line
* length that is ok. Once decoding begins,
* the length is adjusted up each time a longer
* line is decoded */
unsigned char enc_data[80]; /* data to encode */
int line_num; /* number read on current line */
int expect_nl;
} EVP_ENCODE_CTX;
/* Password based encryption function */
typedef int (EVP_PBE_KEYGEN)(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
ASN1_TYPE *param, const EVP_CIPHER *cipher,
const EVP_MD *md, int en_de);
#ifndef OPENSSL_NO_RSA
#define EVP_PKEY_assign_RSA(pkey,rsa) EVP_PKEY_assign((pkey),EVP_PKEY_RSA,\
(char *)(rsa))
#endif
#ifndef OPENSSL_NO_DSA
#define EVP_PKEY_assign_DSA(pkey,dsa) EVP_PKEY_assign((pkey),EVP_PKEY_DSA,\
(char *)(dsa))
#endif
#ifndef OPENSSL_NO_DH
#define EVP_PKEY_assign_DH(pkey,dh) EVP_PKEY_assign((pkey),EVP_PKEY_DH,\
(char *)(dh))
#endif
#ifndef OPENSSL_NO_EC
#define EVP_PKEY_assign_EC_KEY(pkey,eckey) EVP_PKEY_assign((pkey),EVP_PKEY_EC,\
(char *)(eckey))
#endif
/* Add some extra combinations */
#define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a))
#define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a))
#define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a))
#define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a))
int EVP_MD_type(const EVP_MD *md);
#define EVP_MD_nid(e) EVP_MD_type(e)
#define EVP_MD_name(e) OBJ_nid2sn(EVP_MD_nid(e))
int EVP_MD_pkey_type(const EVP_MD *md);
int EVP_MD_size(const EVP_MD *md);
int EVP_MD_block_size(const EVP_MD *md);
unsigned long EVP_MD_flags(const EVP_MD *md);
const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx);
#define EVP_MD_CTX_size(e) EVP_MD_size(EVP_MD_CTX_md(e))
#define EVP_MD_CTX_block_size(e) EVP_MD_block_size(EVP_MD_CTX_md(e))
#define EVP_MD_CTX_type(e) EVP_MD_type(EVP_MD_CTX_md(e))
int EVP_CIPHER_nid(const EVP_CIPHER *cipher);
#define EVP_CIPHER_name(e) OBJ_nid2sn(EVP_CIPHER_nid(e))
int EVP_CIPHER_block_size(const EVP_CIPHER *cipher);
int EVP_CIPHER_key_length(const EVP_CIPHER *cipher);
int EVP_CIPHER_iv_length(const EVP_CIPHER *cipher);
unsigned long EVP_CIPHER_flags(const EVP_CIPHER *cipher);
#define EVP_CIPHER_mode(e) (EVP_CIPHER_flags(e) & EVP_CIPH_MODE)
const EVP_CIPHER * EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in);
void * EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx);
void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data);
#define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c))
unsigned long EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx);
#define EVP_CIPHER_CTX_mode(e) (EVP_CIPHER_CTX_flags(e) & EVP_CIPH_MODE)
#define EVP_ENCODE_LENGTH(l) (((l+2)/3*4)+(l/48+1)*2+80)
#define EVP_DECODE_LENGTH(l) ((l+3)/4*3+80)
#define EVP_SignInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c)
#define EVP_SignInit(a,b) EVP_DigestInit(a,b)
#define EVP_SignUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
#define EVP_VerifyInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c)
#define EVP_VerifyInit(a,b) EVP_DigestInit(a,b)
#define EVP_VerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
#define EVP_OpenUpdate(a,b,c,d,e) EVP_DecryptUpdate(a,b,c,d,e)
#define EVP_SealUpdate(a,b,c,d,e) EVP_EncryptUpdate(a,b,c,d,e)
#define EVP_DigestSignUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
#define EVP_DigestVerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
#ifdef CONST_STRICT
void BIO_set_md(BIO *,const EVP_MD *md);
#else
# define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,0,(char *)md)
#endif
#define BIO_get_md(b,mdp) BIO_ctrl(b,BIO_C_GET_MD,0,(char *)mdp)
#define BIO_get_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_GET_MD_CTX,0,(char *)mdcp)
#define BIO_set_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_SET_MD_CTX,0,(char *)mdcp)
#define BIO_get_cipher_status(b) BIO_ctrl(b,BIO_C_GET_CIPHER_STATUS,0,NULL)
#define BIO_get_cipher_ctx(b,c_pp) BIO_ctrl(b,BIO_C_GET_CIPHER_CTX,0,(char *)c_pp)
int EVP_Cipher(EVP_CIPHER_CTX *c,
unsigned char *out,
const unsigned char *in,
unsigned int inl);
#define EVP_add_cipher_alias(n,alias) \
OBJ_NAME_add((alias),OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS,(n))
#define EVP_add_digest_alias(n,alias) \
OBJ_NAME_add((alias),OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,(n))
#define EVP_delete_cipher_alias(alias) \
OBJ_NAME_remove(alias,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS);
#define EVP_delete_digest_alias(alias) \
OBJ_NAME_remove(alias,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS);
void EVP_MD_CTX_init(EVP_MD_CTX *ctx);
int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx);
EVP_MD_CTX *EVP_MD_CTX_create(void);
void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx);
int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out,const EVP_MD_CTX *in);
void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags);
void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags);
int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx,int flags);
int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl);
int EVP_DigestUpdate(EVP_MD_CTX *ctx,const void *d,
size_t cnt);
int EVP_DigestFinal_ex(EVP_MD_CTX *ctx,unsigned char *md,unsigned int *s);
int EVP_Digest(const void *data, size_t count,
unsigned char *md, unsigned int *size, const EVP_MD *type, ENGINE *impl);
int EVP_MD_CTX_copy(EVP_MD_CTX *out,const EVP_MD_CTX *in);
int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type);
int EVP_DigestFinal(EVP_MD_CTX *ctx,unsigned char *md,unsigned int *s);
int EVP_read_pw_string(char *buf,int length,const char *prompt,int verify);
int EVP_read_pw_string_min(char *buf,int minlen,int maxlen,const char *prompt,int verify);
void EVP_set_pw_prompt(const char *prompt);
char * EVP_get_pw_prompt(void);
int EVP_BytesToKey(const EVP_CIPHER *type,const EVP_MD *md,
const unsigned char *salt, const unsigned char *data,
int datal, int count, unsigned char *key,unsigned char *iv);
void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags);
void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags);
int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx,int flags);
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key, const unsigned char *iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher,
const unsigned char *key, const unsigned char *iv);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key, const unsigned char *iv);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherInit(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher,
const unsigned char *key,const unsigned char *iv,
int enc);
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
const unsigned char *key,const unsigned char *iv,
int enc);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in, int inl);
int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl);
int EVP_SignFinal(EVP_MD_CTX *ctx,unsigned char *md,unsigned int *s,
EVP_PKEY *pkey);
int EVP_VerifyFinal(EVP_MD_CTX *ctx,const unsigned char *sigbuf,
unsigned int siglen,EVP_PKEY *pkey);
int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey);
int EVP_DigestSignFinal(EVP_MD_CTX *ctx,
unsigned char *sigret, size_t *siglen);
int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey);
int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx,
unsigned char *sig, size_t siglen);
int EVP_OpenInit(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *type,
const unsigned char *ek, int ekl, const unsigned char *iv,
EVP_PKEY *priv);
int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
unsigned char **ek, int *ekl, unsigned char *iv,
EVP_PKEY **pubk, int npubk);
int EVP_SealFinal(EVP_CIPHER_CTX *ctx,unsigned char *out,int *outl);
void EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
const unsigned char *in,int inl);
void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl);
int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int n);
void EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
const unsigned char *in, int inl);
int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
char *out, int *outl);
int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a);
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a);
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void);
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *a);
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key);
#ifndef OPENSSL_NO_BIO
BIO_METHOD *BIO_f_md(void);
BIO_METHOD *BIO_f_base64(void);
BIO_METHOD *BIO_f_cipher(void);
BIO_METHOD *BIO_f_reliable(void);
void BIO_set_cipher(BIO *b,const EVP_CIPHER *c,const unsigned char *k,
const unsigned char *i, int enc);
#endif
const EVP_MD *EVP_md_null(void);
#ifndef OPENSSL_NO_MD2
const EVP_MD *EVP_md2(void);
#endif
#ifndef OPENSSL_NO_MD4
const EVP_MD *EVP_md4(void);
#endif
#ifndef OPENSSL_NO_MD5
const EVP_MD *EVP_md5(void);
#endif
#ifndef OPENSSL_NO_SHA
const EVP_MD *EVP_sha(void);
const EVP_MD *EVP_sha1(void);
const EVP_MD *EVP_dss(void);
const EVP_MD *EVP_dss1(void);
const EVP_MD *EVP_ecdsa(void);
#endif
#ifndef OPENSSL_NO_SHA256
const EVP_MD *EVP_sha224(void);
const EVP_MD *EVP_sha256(void);
#endif
#ifndef OPENSSL_NO_SHA512
const EVP_MD *EVP_sha384(void);
const EVP_MD *EVP_sha512(void);
#endif
#ifndef OPENSSL_NO_MDC2
const EVP_MD *EVP_mdc2(void);
#endif
#ifndef OPENSSL_NO_RIPEMD
const EVP_MD *EVP_ripemd160(void);
#endif
#ifndef OPENSSL_NO_WHIRLPOOL
const EVP_MD *EVP_whirlpool(void);
#endif
const EVP_CIPHER *EVP_enc_null(void); /* does nothing :-) */
#ifndef OPENSSL_NO_DES
const EVP_CIPHER *EVP_des_ecb(void);
const EVP_CIPHER *EVP_des_ede(void);
const EVP_CIPHER *EVP_des_ede3(void);
const EVP_CIPHER *EVP_des_ede_ecb(void);
const EVP_CIPHER *EVP_des_ede3_ecb(void);
const EVP_CIPHER *EVP_des_cfb64(void);
# define EVP_des_cfb EVP_des_cfb64
const EVP_CIPHER *EVP_des_cfb1(void);
const EVP_CIPHER *EVP_des_cfb8(void);
const EVP_CIPHER *EVP_des_ede_cfb64(void);
# define EVP_des_ede_cfb EVP_des_ede_cfb64
#if 0
const EVP_CIPHER *EVP_des_ede_cfb1(void);
const EVP_CIPHER *EVP_des_ede_cfb8(void);
#endif
const EVP_CIPHER *EVP_des_ede3_cfb64(void);
# define EVP_des_ede3_cfb EVP_des_ede3_cfb64
const EVP_CIPHER *EVP_des_ede3_cfb1(void);
const EVP_CIPHER *EVP_des_ede3_cfb8(void);
const EVP_CIPHER *EVP_des_ofb(void);
const EVP_CIPHER *EVP_des_ede_ofb(void);
const EVP_CIPHER *EVP_des_ede3_ofb(void);
const EVP_CIPHER *EVP_des_cbc(void);
const EVP_CIPHER *EVP_des_ede_cbc(void);
const EVP_CIPHER *EVP_des_ede3_cbc(void);
const EVP_CIPHER *EVP_desx_cbc(void);
/* This should now be supported through the dev_crypto ENGINE. But also, why are
* rc4 and md5 declarations made here inside a "NO_DES" precompiler branch? */
#if 0
# ifdef OPENSSL_OPENBSD_DEV_CRYPTO
const EVP_CIPHER *EVP_dev_crypto_des_ede3_cbc(void);
const EVP_CIPHER *EVP_dev_crypto_rc4(void);
const EVP_MD *EVP_dev_crypto_md5(void);
# endif
#endif
#endif
#ifndef OPENSSL_NO_RC4
const EVP_CIPHER *EVP_rc4(void);
const EVP_CIPHER *EVP_rc4_40(void);
#ifndef OPENSSL_NO_MD5
const EVP_CIPHER *EVP_rc4_hmac_md5(void);
#endif
#endif
#ifndef OPENSSL_NO_IDEA
const EVP_CIPHER *EVP_idea_ecb(void);
const EVP_CIPHER *EVP_idea_cfb64(void);
# define EVP_idea_cfb EVP_idea_cfb64
const EVP_CIPHER *EVP_idea_ofb(void);
const EVP_CIPHER *EVP_idea_cbc(void);
#endif
#ifndef OPENSSL_NO_RC2
const EVP_CIPHER *EVP_rc2_ecb(void);
const EVP_CIPHER *EVP_rc2_cbc(void);
const EVP_CIPHER *EVP_rc2_40_cbc(void);
const EVP_CIPHER *EVP_rc2_64_cbc(void);
const EVP_CIPHER *EVP_rc2_cfb64(void);
# define EVP_rc2_cfb EVP_rc2_cfb64
const EVP_CIPHER *EVP_rc2_ofb(void);
#endif
#ifndef OPENSSL_NO_BF
const EVP_CIPHER *EVP_bf_ecb(void);
const EVP_CIPHER *EVP_bf_cbc(void);
const EVP_CIPHER *EVP_bf_cfb64(void);
# define EVP_bf_cfb EVP_bf_cfb64
const EVP_CIPHER *EVP_bf_ofb(void);
#endif
#ifndef OPENSSL_NO_CAST
const EVP_CIPHER *EVP_cast5_ecb(void);
const EVP_CIPHER *EVP_cast5_cbc(void);
const EVP_CIPHER *EVP_cast5_cfb64(void);
# define EVP_cast5_cfb EVP_cast5_cfb64
const EVP_CIPHER *EVP_cast5_ofb(void);
#endif
#ifndef OPENSSL_NO_RC5
const EVP_CIPHER *EVP_rc5_32_12_16_cbc(void);
const EVP_CIPHER *EVP_rc5_32_12_16_ecb(void);
const EVP_CIPHER *EVP_rc5_32_12_16_cfb64(void);
# define EVP_rc5_32_12_16_cfb EVP_rc5_32_12_16_cfb64
const EVP_CIPHER *EVP_rc5_32_12_16_ofb(void);
#endif
#ifndef OPENSSL_NO_AES
const EVP_CIPHER *EVP_aes_128_ecb(void);
const EVP_CIPHER *EVP_aes_128_cbc(void);
const EVP_CIPHER *EVP_aes_128_cfb1(void);
const EVP_CIPHER *EVP_aes_128_cfb8(void);
const EVP_CIPHER *EVP_aes_128_cfb128(void);
# define EVP_aes_128_cfb EVP_aes_128_cfb128
const EVP_CIPHER *EVP_aes_128_ofb(void);
const EVP_CIPHER *EVP_aes_128_ctr(void);
const EVP_CIPHER *EVP_aes_128_ccm(void);
const EVP_CIPHER *EVP_aes_128_gcm(void);
const EVP_CIPHER *EVP_aes_128_xts(void);
const EVP_CIPHER *EVP_aes_192_ecb(void);
const EVP_CIPHER *EVP_aes_192_cbc(void);
const EVP_CIPHER *EVP_aes_192_cfb1(void);
const EVP_CIPHER *EVP_aes_192_cfb8(void);
const EVP_CIPHER *EVP_aes_192_cfb128(void);
# define EVP_aes_192_cfb EVP_aes_192_cfb128
const EVP_CIPHER *EVP_aes_192_ofb(void);
const EVP_CIPHER *EVP_aes_192_ctr(void);
const EVP_CIPHER *EVP_aes_192_ccm(void);
const EVP_CIPHER *EVP_aes_192_gcm(void);
const EVP_CIPHER *EVP_aes_256_ecb(void);
const EVP_CIPHER *EVP_aes_256_cbc(void);
const EVP_CIPHER *EVP_aes_256_cfb1(void);
const EVP_CIPHER *EVP_aes_256_cfb8(void);
const EVP_CIPHER *EVP_aes_256_cfb128(void);
# define EVP_aes_256_cfb EVP_aes_256_cfb128
const EVP_CIPHER *EVP_aes_256_ofb(void);
const EVP_CIPHER *EVP_aes_256_ctr(void);
const EVP_CIPHER *EVP_aes_256_ccm(void);
const EVP_CIPHER *EVP_aes_256_gcm(void);
const EVP_CIPHER *EVP_aes_256_xts(void);
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void);
const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void);
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
const EVP_CIPHER *EVP_camellia_128_ecb(void);
const EVP_CIPHER *EVP_camellia_128_cbc(void);
const EVP_CIPHER *EVP_camellia_128_cfb1(void);
const EVP_CIPHER *EVP_camellia_128_cfb8(void);
const EVP_CIPHER *EVP_camellia_128_cfb128(void);
# define EVP_camellia_128_cfb EVP_camellia_128_cfb128
const EVP_CIPHER *EVP_camellia_128_ofb(void);
const EVP_CIPHER *EVP_camellia_192_ecb(void);
const EVP_CIPHER *EVP_camellia_192_cbc(void);
const EVP_CIPHER *EVP_camellia_192_cfb1(void);
const EVP_CIPHER *EVP_camellia_192_cfb8(void);
const EVP_CIPHER *EVP_camellia_192_cfb128(void);
# define EVP_camellia_192_cfb EVP_camellia_192_cfb128
const EVP_CIPHER *EVP_camellia_192_ofb(void);
const EVP_CIPHER *EVP_camellia_256_ecb(void);
const EVP_CIPHER *EVP_camellia_256_cbc(void);
const EVP_CIPHER *EVP_camellia_256_cfb1(void);
const EVP_CIPHER *EVP_camellia_256_cfb8(void);
const EVP_CIPHER *EVP_camellia_256_cfb128(void);
# define EVP_camellia_256_cfb EVP_camellia_256_cfb128
const EVP_CIPHER *EVP_camellia_256_ofb(void);
#endif
#ifndef OPENSSL_NO_SEED
const EVP_CIPHER *EVP_seed_ecb(void);
const EVP_CIPHER *EVP_seed_cbc(void);
const EVP_CIPHER *EVP_seed_cfb128(void);
# define EVP_seed_cfb EVP_seed_cfb128
const EVP_CIPHER *EVP_seed_ofb(void);
#endif
void OPENSSL_add_all_algorithms_noconf(void);
void OPENSSL_add_all_algorithms_conf(void);
#ifdef OPENSSL_LOAD_CONF
#define OpenSSL_add_all_algorithms() \
OPENSSL_add_all_algorithms_conf()
#else
#define OpenSSL_add_all_algorithms() \
OPENSSL_add_all_algorithms_noconf()
#endif
void OpenSSL_add_all_ciphers(void);
void OpenSSL_add_all_digests(void);
#define SSLeay_add_all_algorithms() OpenSSL_add_all_algorithms()
#define SSLeay_add_all_ciphers() OpenSSL_add_all_ciphers()
#define SSLeay_add_all_digests() OpenSSL_add_all_digests()
int EVP_add_cipher(const EVP_CIPHER *cipher);
int EVP_add_digest(const EVP_MD *digest);
const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
const EVP_MD *EVP_get_digestbyname(const char *name);
void EVP_cleanup(void);
void EVP_CIPHER_do_all(void (*fn)(const EVP_CIPHER *ciph,
const char *from, const char *to, void *x), void *arg);
void EVP_CIPHER_do_all_sorted(void (*fn)(const EVP_CIPHER *ciph,
const char *from, const char *to, void *x), void *arg);
void EVP_MD_do_all(void (*fn)(const EVP_MD *ciph,
const char *from, const char *to, void *x), void *arg);
void EVP_MD_do_all_sorted(void (*fn)(const EVP_MD *ciph,
const char *from, const char *to, void *x), void *arg);
int EVP_PKEY_decrypt_old(unsigned char *dec_key,
const unsigned char *enc_key,int enc_key_len,
EVP_PKEY *private_key);
int EVP_PKEY_encrypt_old(unsigned char *enc_key,
const unsigned char *key,int key_len,
EVP_PKEY *pub_key);
int EVP_PKEY_type(int type);
int EVP_PKEY_id(const EVP_PKEY *pkey);
int EVP_PKEY_base_id(const EVP_PKEY *pkey);
int EVP_PKEY_bits(EVP_PKEY *pkey);
int EVP_PKEY_size(EVP_PKEY *pkey);
int EVP_PKEY_set_type(EVP_PKEY *pkey,int type);
int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len);
int EVP_PKEY_assign(EVP_PKEY *pkey,int type,void *key);
void * EVP_PKEY_get0(EVP_PKEY *pkey);
#ifndef OPENSSL_NO_RSA
struct rsa_st;
int EVP_PKEY_set1_RSA(EVP_PKEY *pkey,struct rsa_st *key);
struct rsa_st *EVP_PKEY_get1_RSA(EVP_PKEY *pkey);
#endif
#ifndef OPENSSL_NO_DSA
struct dsa_st;
int EVP_PKEY_set1_DSA(EVP_PKEY *pkey,struct dsa_st *key);
struct dsa_st *EVP_PKEY_get1_DSA(EVP_PKEY *pkey);
#endif
#ifndef OPENSSL_NO_DH
struct dh_st;
int EVP_PKEY_set1_DH(EVP_PKEY *pkey,struct dh_st *key);
struct dh_st *EVP_PKEY_get1_DH(EVP_PKEY *pkey);
#endif
#ifndef OPENSSL_NO_EC
struct ec_key_st;
int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey,struct ec_key_st *key);
struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey);
#endif
EVP_PKEY * EVP_PKEY_new(void);
void EVP_PKEY_free(EVP_PKEY *pkey);
EVP_PKEY * d2i_PublicKey(int type,EVP_PKEY **a, const unsigned char **pp,
long length);
int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp);
EVP_PKEY * d2i_PrivateKey(int type,EVP_PKEY **a, const unsigned char **pp,
long length);
EVP_PKEY * d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp,
long length);
int i2d_PrivateKey(EVP_PKEY *a, unsigned char **pp);
int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from);
int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey);
int EVP_PKEY_save_parameters(EVP_PKEY *pkey,int mode);
int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b);
int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b);
int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx);
int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx);
int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx);
int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid);
int EVP_CIPHER_type(const EVP_CIPHER *ctx);
/* calls methods */
int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
/* These are used by EVP_CIPHER methods */
int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c,ASN1_TYPE *type);
int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c,ASN1_TYPE *type);
/* PKCS5 password based encryption */
int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md,
int en_de);
int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen,
const unsigned char *salt, int saltlen, int iter,
int keylen, unsigned char *out);
int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
const unsigned char *salt, int saltlen, int iter,
const EVP_MD *digest,
int keylen, unsigned char *out);
int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md,
int en_de);
void PKCS5_PBE_add(void);
int EVP_PBE_CipherInit (ASN1_OBJECT *pbe_obj, const char *pass, int passlen,
ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de);
/* PBE type */
/* Can appear as the outermost AlgorithmIdentifier */
#define EVP_PBE_TYPE_OUTER 0x0
/* Is an PRF type OID */
#define EVP_PBE_TYPE_PRF 0x1
int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid, int md_nid,
EVP_PBE_KEYGEN *keygen);
int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md,
EVP_PBE_KEYGEN *keygen);
int EVP_PBE_find(int type, int pbe_nid,
int *pcnid, int *pmnid, EVP_PBE_KEYGEN **pkeygen);
void EVP_PBE_cleanup(void);
#define ASN1_PKEY_ALIAS 0x1
#define ASN1_PKEY_DYNAMIC 0x2
#define ASN1_PKEY_SIGPARAM_NULL 0x4
#define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1
#define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2
#define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3
#define ASN1_PKEY_CTRL_CMS_SIGN 0x5
#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7
int EVP_PKEY_asn1_get_count(void);
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx);
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type);
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe,
const char *str, int len);
int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth);
int EVP_PKEY_asn1_add_alias(int to, int from);
int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *pkey_base_id, int *ppkey_flags,
const char **pinfo, const char **ppem_str,
const EVP_PKEY_ASN1_METHOD *ameth);
const EVP_PKEY_ASN1_METHOD* EVP_PKEY_get0_asn1(EVP_PKEY *pkey);
EVP_PKEY_ASN1_METHOD* EVP_PKEY_asn1_new(int id, int flags,
const char *pem_str, const char *info);
void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst,
const EVP_PKEY_ASN1_METHOD *src);
void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth);
void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth,
int (*pub_decode)(EVP_PKEY *pk, X509_PUBKEY *pub),
int (*pub_encode)(X509_PUBKEY *pub, const EVP_PKEY *pk),
int (*pub_cmp)(const EVP_PKEY *a, const EVP_PKEY *b),
int (*pub_print)(BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx),
int (*pkey_size)(const EVP_PKEY *pk),
int (*pkey_bits)(const EVP_PKEY *pk));
void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth,
int (*priv_decode)(EVP_PKEY *pk, PKCS8_PRIV_KEY_INFO *p8inf),
int (*priv_encode)(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk),
int (*priv_print)(BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx));
void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth,
int (*param_decode)(EVP_PKEY *pkey,
const unsigned char **pder, int derlen),
int (*param_encode)(const EVP_PKEY *pkey, unsigned char **pder),
int (*param_missing)(const EVP_PKEY *pk),
int (*param_copy)(EVP_PKEY *to, const EVP_PKEY *from),
int (*param_cmp)(const EVP_PKEY *a, const EVP_PKEY *b),
int (*param_print)(BIO *out, const EVP_PKEY *pkey, int indent,
ASN1_PCTX *pctx));
void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth,
void (*pkey_free)(EVP_PKEY *pkey));
void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_ctrl)(EVP_PKEY *pkey, int op,
long arg1, void *arg2));
#define EVP_PKEY_OP_UNDEFINED 0
#define EVP_PKEY_OP_PARAMGEN (1<<1)
#define EVP_PKEY_OP_KEYGEN (1<<2)
#define EVP_PKEY_OP_SIGN (1<<3)
#define EVP_PKEY_OP_VERIFY (1<<4)
#define EVP_PKEY_OP_VERIFYRECOVER (1<<5)
#define EVP_PKEY_OP_SIGNCTX (1<<6)
#define EVP_PKEY_OP_VERIFYCTX (1<<7)
#define EVP_PKEY_OP_ENCRYPT (1<<8)
#define EVP_PKEY_OP_DECRYPT (1<<9)
#define EVP_PKEY_OP_DERIVE (1<<10)
#define EVP_PKEY_OP_TYPE_SIG \
(EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER \
| EVP_PKEY_OP_SIGNCTX | EVP_PKEY_OP_VERIFYCTX)
#define EVP_PKEY_OP_TYPE_CRYPT \
(EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT)
#define EVP_PKEY_OP_TYPE_NOGEN \
(EVP_PKEY_OP_SIG | EVP_PKEY_OP_CRYPT | EVP_PKEY_OP_DERIVE)
#define EVP_PKEY_OP_TYPE_GEN \
(EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN)
#define EVP_PKEY_CTX_set_signature_md(ctx, md) \
EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, \
EVP_PKEY_CTRL_MD, 0, (void *)md)
#define EVP_PKEY_CTRL_MD 1
#define EVP_PKEY_CTRL_PEER_KEY 2
#define EVP_PKEY_CTRL_PKCS7_ENCRYPT 3
#define EVP_PKEY_CTRL_PKCS7_DECRYPT 4
#define EVP_PKEY_CTRL_PKCS7_SIGN 5
#define EVP_PKEY_CTRL_SET_MAC_KEY 6
#define EVP_PKEY_CTRL_DIGESTINIT 7
/* Used by GOST key encryption in TLS */
#define EVP_PKEY_CTRL_SET_IV 8
#define EVP_PKEY_CTRL_CMS_ENCRYPT 9
#define EVP_PKEY_CTRL_CMS_DECRYPT 10
#define EVP_PKEY_CTRL_CMS_SIGN 11
#define EVP_PKEY_CTRL_CIPHER 12
#define EVP_PKEY_ALG_CTRL 0x1000
#define EVP_PKEY_FLAG_AUTOARGLEN 2
/* Method handles all operations: don't assume any digest related
* defaults.
*/
#define EVP_PKEY_FLAG_SIGCTX_CUSTOM 4
const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type);
EVP_PKEY_METHOD* EVP_PKEY_meth_new(int id, int flags);
void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags,
const EVP_PKEY_METHOD *meth);
void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src);
void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth);
int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth);
EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e);
EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e);
EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx);
void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx);
int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype,
int cmd, int p1, void *p2);
int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
const char *value);
int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx);
void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen);
EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e,
const unsigned char *key, int keylen);
void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data);
void *EVP_PKEY_CTX_get_data(EVP_PKEY_CTX *ctx);
EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx);
EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx);
void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data);
void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx);
int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_sign(EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen);
int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_verify(EVP_PKEY_CTX *ctx,
const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen);
int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx,
unsigned char *rout, size_t *routlen,
const unsigned char *sig, size_t siglen);
int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx,
unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen);
int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx,
unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen);
int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer);
int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
typedef int EVP_PKEY_gen_cb(EVP_PKEY_CTX *ctx);
int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey);
int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx);
int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey);
void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb);
EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx);
int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx);
void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth,
int (*init)(EVP_PKEY_CTX *ctx));
void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth,
int (*copy)(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src));
void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth,
void (*cleanup)(EVP_PKEY_CTX *ctx));
void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth,
int (*paramgen_init)(EVP_PKEY_CTX *ctx),
int (*paramgen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth,
int (*keygen_init)(EVP_PKEY_CTX *ctx),
int (*keygen)(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth,
int (*sign_init)(EVP_PKEY_CTX *ctx),
int (*sign)(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen));
void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth,
int (*verify_init)(EVP_PKEY_CTX *ctx),
int (*verify)(EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen,
const unsigned char *tbs, size_t tbslen));
void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth,
int (*verify_recover_init)(EVP_PKEY_CTX *ctx),
int (*verify_recover)(EVP_PKEY_CTX *ctx,
unsigned char *sig, size_t *siglen,
const unsigned char *tbs, size_t tbslen));
void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth,
int (*signctx_init)(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx),
int (*signctx)(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
EVP_MD_CTX *mctx));
void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth,
int (*verifyctx_init)(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx),
int (*verifyctx)(EVP_PKEY_CTX *ctx, const unsigned char *sig,int siglen,
EVP_MD_CTX *mctx));
void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth,
int (*encrypt_init)(EVP_PKEY_CTX *ctx),
int (*encryptfn)(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen));
void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth,
int (*decrypt_init)(EVP_PKEY_CTX *ctx),
int (*decrypt)(EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
const unsigned char *in, size_t inlen));
void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth,
int (*derive_init)(EVP_PKEY_CTX *ctx),
int (*derive)(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen));
void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth,
int (*ctrl)(EVP_PKEY_CTX *ctx, int type, int p1, void *p2),
int (*ctrl_str)(EVP_PKEY_CTX *ctx,
const char *type, const char *value));
void EVP_add_alg_module(void);
/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_EVP_strings(void);
/* Error codes for the EVP functions. */
/* Function codes. */
#define EVP_F_AESNI_INIT_KEY 165
#define EVP_F_AESNI_XTS_CIPHER 176
#define EVP_F_AES_INIT_KEY 133
#define EVP_F_AES_XTS 172
#define EVP_F_AES_XTS_CIPHER 175
#define EVP_F_ALG_MODULE_INIT 177
#define EVP_F_CAMELLIA_INIT_KEY 159
#define EVP_F_CMAC_INIT 173
#define EVP_F_D2I_PKEY 100
#define EVP_F_DO_SIGVER_INIT 161
#define EVP_F_DSAPKEY2PKCS8 134
#define EVP_F_DSA_PKEY2PKCS8 135
#define EVP_F_ECDSA_PKEY2PKCS8 129
#define EVP_F_ECKEY_PKEY2PKCS8 132
#define EVP_F_EVP_CIPHERINIT_EX 123
#define EVP_F_EVP_CIPHER_CTX_COPY 163
#define EVP_F_EVP_CIPHER_CTX_CTRL 124
#define EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH 122
#define EVP_F_EVP_DECRYPTFINAL_EX 101
#define EVP_F_EVP_DIGESTINIT_EX 128
#define EVP_F_EVP_ENCRYPTFINAL_EX 127
#define EVP_F_EVP_MD_CTX_COPY_EX 110
#define EVP_F_EVP_MD_SIZE 162
#define EVP_F_EVP_OPENINIT 102
#define EVP_F_EVP_PBE_ALG_ADD 115
#define EVP_F_EVP_PBE_ALG_ADD_TYPE 160
#define EVP_F_EVP_PBE_CIPHERINIT 116
#define EVP_F_EVP_PKCS82PKEY 111
#define EVP_F_EVP_PKCS82PKEY_BROKEN 136
#define EVP_F_EVP_PKEY2PKCS8_BROKEN 113
#define EVP_F_EVP_PKEY_COPY_PARAMETERS 103
#define EVP_F_EVP_PKEY_CTX_CTRL 137
#define EVP_F_EVP_PKEY_CTX_CTRL_STR 150
#define EVP_F_EVP_PKEY_CTX_DUP 156
#define EVP_F_EVP_PKEY_DECRYPT 104
#define EVP_F_EVP_PKEY_DECRYPT_INIT 138
#define EVP_F_EVP_PKEY_DECRYPT_OLD 151
#define EVP_F_EVP_PKEY_DERIVE 153
#define EVP_F_EVP_PKEY_DERIVE_INIT 154
#define EVP_F_EVP_PKEY_DERIVE_SET_PEER 155
#define EVP_F_EVP_PKEY_ENCRYPT 105
#define EVP_F_EVP_PKEY_ENCRYPT_INIT 139
#define EVP_F_EVP_PKEY_ENCRYPT_OLD 152
#define EVP_F_EVP_PKEY_GET1_DH 119
#define EVP_F_EVP_PKEY_GET1_DSA 120
#define EVP_F_EVP_PKEY_GET1_ECDSA 130
#define EVP_F_EVP_PKEY_GET1_EC_KEY 131
#define EVP_F_EVP_PKEY_GET1_RSA 121
#define EVP_F_EVP_PKEY_KEYGEN 146
#define EVP_F_EVP_PKEY_KEYGEN_INIT 147
#define EVP_F_EVP_PKEY_NEW 106
#define EVP_F_EVP_PKEY_PARAMGEN 148
#define EVP_F_EVP_PKEY_PARAMGEN_INIT 149
#define EVP_F_EVP_PKEY_SIGN 140
#define EVP_F_EVP_PKEY_SIGN_INIT 141
#define EVP_F_EVP_PKEY_VERIFY 142
#define EVP_F_EVP_PKEY_VERIFY_INIT 143
#define EVP_F_EVP_PKEY_VERIFY_RECOVER 144
#define EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT 145
#define EVP_F_EVP_RIJNDAEL 126
#define EVP_F_EVP_SIGNFINAL 107
#define EVP_F_EVP_VERIFYFINAL 108
#define EVP_F_FIPS_CIPHERINIT 166
#define EVP_F_FIPS_CIPHER_CTX_COPY 170
#define EVP_F_FIPS_CIPHER_CTX_CTRL 167
#define EVP_F_FIPS_CIPHER_CTX_SET_KEY_LENGTH 171
#define EVP_F_FIPS_DIGESTINIT 168
#define EVP_F_FIPS_MD_CTX_COPY 169
#define EVP_F_HMAC_INIT_EX 174
#define EVP_F_INT_CTX_NEW 157
#define EVP_F_PKCS5_PBE_KEYIVGEN 117
#define EVP_F_PKCS5_V2_PBE_KEYIVGEN 118
#define EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN 164
#define EVP_F_PKCS8_SET_BROKEN 112
#define EVP_F_PKEY_SET_TYPE 158
#define EVP_F_RC2_MAGIC_TO_METH 109
#define EVP_F_RC5_CTRL 125
/* Reason codes. */
#define EVP_R_AES_IV_SETUP_FAILED 162
#define EVP_R_AES_KEY_SETUP_FAILED 143
#define EVP_R_ASN1_LIB 140
#define EVP_R_BAD_BLOCK_LENGTH 136
#define EVP_R_BAD_DECRYPT 100
#define EVP_R_BAD_KEY_LENGTH 137
#define EVP_R_BN_DECODE_ERROR 112
#define EVP_R_BN_PUBKEY_ERROR 113
#define EVP_R_BUFFER_TOO_SMALL 155
#define EVP_R_CAMELLIA_KEY_SETUP_FAILED 157
#define EVP_R_CIPHER_PARAMETER_ERROR 122
#define EVP_R_COMMAND_NOT_SUPPORTED 147
#define EVP_R_CTRL_NOT_IMPLEMENTED 132
#define EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED 133
#define EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH 138
#define EVP_R_DECODE_ERROR 114
#define EVP_R_DIFFERENT_KEY_TYPES 101
#define EVP_R_DIFFERENT_PARAMETERS 153
#define EVP_R_DISABLED_FOR_FIPS 163
#define EVP_R_ENCODE_ERROR 115
#define EVP_R_ERROR_LOADING_SECTION 165
#define EVP_R_ERROR_SETTING_FIPS_MODE 166
#define EVP_R_EVP_PBE_CIPHERINIT_ERROR 119
#define EVP_R_EXPECTING_AN_RSA_KEY 127
#define EVP_R_EXPECTING_A_DH_KEY 128
#define EVP_R_EXPECTING_A_DSA_KEY 129
#define EVP_R_EXPECTING_A_ECDSA_KEY 141
#define EVP_R_EXPECTING_A_EC_KEY 142
#define EVP_R_FIPS_MODE_NOT_SUPPORTED 167
#define EVP_R_INITIALIZATION_ERROR 134
#define EVP_R_INPUT_NOT_INITIALIZED 111
#define EVP_R_INVALID_DIGEST 152
#define EVP_R_INVALID_FIPS_MODE 168
#define EVP_R_INVALID_KEY_LENGTH 130
#define EVP_R_INVALID_OPERATION 148
#define EVP_R_IV_TOO_LARGE 102
#define EVP_R_KEYGEN_FAILURE 120
#define EVP_R_MESSAGE_DIGEST_IS_NULL 159
#define EVP_R_METHOD_NOT_SUPPORTED 144
#define EVP_R_MISSING_PARAMETERS 103
#define EVP_R_NO_CIPHER_SET 131
#define EVP_R_NO_DEFAULT_DIGEST 158
#define EVP_R_NO_DIGEST_SET 139
#define EVP_R_NO_DSA_PARAMETERS 116
#define EVP_R_NO_KEY_SET 154
#define EVP_R_NO_OPERATION_SET 149
#define EVP_R_NO_SIGN_FUNCTION_CONFIGURED 104
#define EVP_R_NO_VERIFY_FUNCTION_CONFIGURED 105
#define EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 150
#define EVP_R_OPERATON_NOT_INITIALIZED 151
#define EVP_R_PKCS8_UNKNOWN_BROKEN_TYPE 117
#define EVP_R_PRIVATE_KEY_DECODE_ERROR 145
#define EVP_R_PRIVATE_KEY_ENCODE_ERROR 146
#define EVP_R_PUBLIC_KEY_NOT_RSA 106
#define EVP_R_TOO_LARGE 164
#define EVP_R_UNKNOWN_CIPHER 160
#define EVP_R_UNKNOWN_DIGEST 161
#define EVP_R_UNKNOWN_OPTION 169
#define EVP_R_UNKNOWN_PBE_ALGORITHM 121
#define EVP_R_UNSUPORTED_NUMBER_OF_ROUNDS 135
#define EVP_R_UNSUPPORTED_ALGORITHM 156
#define EVP_R_UNSUPPORTED_CIPHER 107
#define EVP_R_UNSUPPORTED_KEYLENGTH 123
#define EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION 124
#define EVP_R_UNSUPPORTED_KEY_SIZE 108
#define EVP_R_UNSUPPORTED_PRF 125
#define EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM 118
#define EVP_R_UNSUPPORTED_SALT_TYPE 126
#define EVP_R_WRONG_FINAL_BLOCK_LENGTH 109
#define EVP_R_WRONG_PUBLIC_KEY_TYPE 110
#ifdef __cplusplus
}
#endif
#endif
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<link rel='stylesheet' type='text/css' href='cupertino/theme.css' />
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.css' />
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.print.css' media='print' />
<script type='text/javascript' src='../jquery/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='../jquery/jquery-ui-1.8.17.custom.min.js'></script>
<script type='text/javascript' src='../fullcalendar/fullcalendar.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d-3, 16, 0),
allDay: false
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+4, 16, 0),
allDay: false
},
{
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, 22, 30),
allDay: false
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}
]
});
});
</script>
<style type='text/css'>
body {
margin-top: 40px;
text-align: center;
font-size: 13px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#calendar {
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
|
import java.util.*;
abstract class GenericPanelControl {
protected abstract void _performAction(List<?> rowVector);
}
class WorkflowPanelControl extends GenericPanelControl {
protected void _performAction(List rowVector) {
}
}
class WorkflowSubPanelControl extends WorkflowPanelControl {
protected void _performAction(List rowVector) {
super._performAction();
}
} |
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*
* USB HIDBP Keyboard support
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <linux/hid.h>
/*
* Version Information
*/
#define DRIVER_VERSION ""
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@ucw.cz>"
#define DRIVER_DESC "USB HID Boot Protocol keyboard driver"
#define DRIVER_LICENSE "GPL"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
static const unsigned char usb_kbd_keycode[256] = {
0, 0, 0, 0, 30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38,
50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11, 28, 1, 14, 15, 57, 12, 13, 26,
27, 43, 43, 39, 40, 41, 51, 52, 53, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 87, 88, 99, 70,119,110,102,104,111,107,109,106,
105,108,103, 69, 98, 55, 74, 78, 96, 79, 80, 81, 75, 76, 77, 71,
72, 73, 82, 83, 86,127,116,117,183,184,185,186,187,188,189,190,
191,192,193,194,134,138,130,132,128,129,131,137,133,135,136,113,
115,114, 0, 0, 0,121, 0, 89, 93,124, 92, 94, 95, 0, 0, 0,
122,123, 90, 91, 85, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
29, 42, 56,125, 97, 54,100,126,164,166,165,163,161,115,114,113,
150,158,159,128,136,177,178,176,142,152,173,140
};
/**
* struct usb_kbd - state of each attached keyboard
* @dev: input device associated with this keyboard
* @usbdev: usb device associated with this keyboard
* @old: data received in the past from the @irq URB representing which
* keys were pressed. By comparing with the current list of keys
* that are pressed, we are able to see key releases.
* @irq: URB for receiving a list of keys that are pressed when a
* new key is pressed or a key that was pressed is released.
* @led: URB for sending LEDs (e.g. numlock, ...)
* @newleds: data that will be sent with the @led URB representing which LEDs
should be on
* @name: Name of the keyboard. @dev's name field points to this buffer
* @phys: Physical path of the keyboard. @dev's phys field points to this
* buffer
* @new: Buffer for the @irq URB
* @cr: Control request for @led URB
* @leds: Buffer for the @led URB
* @new_dma: DMA address for @irq URB
* @leds_dma: DMA address for @led URB
* @leds_lock: spinlock that protects @leds, @newleds, and @led_urb_submitted
* @led_urb_submitted: indicates whether @led is in progress, i.e. it has been
* submitted and its completion handler has not returned yet
* without resubmitting @led
*/
struct usb_kbd {
struct input_dev *dev;
struct usb_device *usbdev;
unsigned char old[8];
struct urb *irq, *led;
unsigned char newleds;
char name[128];
char phys[64];
unsigned char *new;
struct usb_ctrlrequest *cr;
unsigned char *leds;
dma_addr_t new_dma;
dma_addr_t leds_dma;
spinlock_t leds_lock;
bool led_urb_submitted;
};
static void usb_kbd_irq(struct urb *urb)
{
struct usb_kbd *kbd = urb->context;
int i;
switch (urb->status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
goto resubmit;
}
for (i = 0; i < 8; i++)
input_report_key(kbd->dev, usb_kbd_keycode[i + 224], (kbd->new[0] >> i) & 1);
for (i = 2; i < 8; i++) {
if (kbd->old[i] > 3 && memscan(kbd->new + 2, kbd->old[i], 6) == kbd->new + 8) {
if (usb_kbd_keycode[kbd->old[i]])
input_report_key(kbd->dev, usb_kbd_keycode[kbd->old[i]], 0);
else
hid_info(urb->dev,
"Unknown key (scancode %#x) released.\n",
kbd->old[i]);
}
if (kbd->new[i] > 3 && memscan(kbd->old + 2, kbd->new[i], 6) == kbd->old + 8) {
if (usb_kbd_keycode[kbd->new[i]])
input_report_key(kbd->dev, usb_kbd_keycode[kbd->new[i]], 1);
else
hid_info(urb->dev,
"Unknown key (scancode %#x) released.\n",
kbd->new[i]);
}
}
input_sync(kbd->dev);
memcpy(kbd->old, kbd->new, 8);
resubmit:
i = usb_submit_urb (urb, GFP_ATOMIC);
if (i)
hid_err(urb->dev, "can't resubmit intr, %s-%s/input0, status %d",
kbd->usbdev->bus->bus_name,
kbd->usbdev->devpath, i);
}
static int usb_kbd_event(struct input_dev *dev, unsigned int type,
unsigned int code, int value)
{
unsigned long flags;
struct usb_kbd *kbd = input_get_drvdata(dev);
if (type != EV_LED)
return -1;
spin_lock_irqsave(&kbd->leds_lock, flags);
kbd->newleds = (!!test_bit(LED_KANA, dev->led) << 3) | (!!test_bit(LED_COMPOSE, dev->led) << 3) |
(!!test_bit(LED_SCROLLL, dev->led) << 2) | (!!test_bit(LED_CAPSL, dev->led) << 1) |
(!!test_bit(LED_NUML, dev->led));
if (kbd->led_urb_submitted){
spin_unlock_irqrestore(&kbd->leds_lock, flags);
return 0;
}
if (*(kbd->leds) == kbd->newleds){
spin_unlock_irqrestore(&kbd->leds_lock, flags);
return 0;
}
*(kbd->leds) = kbd->newleds;
kbd->led->dev = kbd->usbdev;
if (usb_submit_urb(kbd->led, GFP_ATOMIC))
pr_err("usb_submit_urb(leds) failed\n");
else
kbd->led_urb_submitted = true;
spin_unlock_irqrestore(&kbd->leds_lock, flags);
return 0;
}
static void usb_kbd_led(struct urb *urb)
{
unsigned long flags;
struct usb_kbd *kbd = urb->context;
if (urb->status)
hid_warn(urb->dev, "led urb status %d received\n",
urb->status);
spin_lock_irqsave(&kbd->leds_lock, flags);
if (*(kbd->leds) == kbd->newleds){
kbd->led_urb_submitted = false;
spin_unlock_irqrestore(&kbd->leds_lock, flags);
return;
}
*(kbd->leds) = kbd->newleds;
kbd->led->dev = kbd->usbdev;
if (usb_submit_urb(kbd->led, GFP_ATOMIC)){
hid_err(urb->dev, "usb_submit_urb(leds) failed\n");
kbd->led_urb_submitted = false;
}
spin_unlock_irqrestore(&kbd->leds_lock, flags);
}
static int usb_kbd_open(struct input_dev *dev)
{
struct usb_kbd *kbd = input_get_drvdata(dev);
kbd->irq->dev = kbd->usbdev;
if (usb_submit_urb(kbd->irq, GFP_KERNEL))
return -EIO;
return 0;
}
static void usb_kbd_close(struct input_dev *dev)
{
struct usb_kbd *kbd = input_get_drvdata(dev);
usb_kill_urb(kbd->irq);
}
static int usb_kbd_alloc_mem(struct usb_device *dev, struct usb_kbd *kbd)
{
if (!(kbd->irq = usb_alloc_urb(0, GFP_KERNEL)))
return -1;
if (!(kbd->led = usb_alloc_urb(0, GFP_KERNEL)))
return -1;
if (!(kbd->new = usb_alloc_coherent(dev, 8, GFP_ATOMIC, &kbd->new_dma)))
return -1;
if (!(kbd->cr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL)))
return -1;
if (!(kbd->leds = usb_alloc_coherent(dev, 1, GFP_ATOMIC, &kbd->leds_dma)))
return -1;
return 0;
}
static void usb_kbd_free_mem(struct usb_device *dev, struct usb_kbd *kbd)
{
usb_free_urb(kbd->irq);
usb_free_urb(kbd->led);
usb_free_coherent(dev, 8, kbd->new, kbd->new_dma);
kfree(kbd->cr);
usb_free_coherent(dev, 1, kbd->leds, kbd->leds_dma);
}
static int usb_kbd_probe(struct usb_interface *iface,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(iface);
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
struct usb_kbd *kbd;
struct input_dev *input_dev;
int i, pipe, maxp;
int error = -ENOMEM;
interface = iface->cur_altsetting;
if (interface->desc.bNumEndpoints != 1)
return -ENODEV;
endpoint = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(endpoint))
return -ENODEV;
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
kbd = kzalloc(sizeof(struct usb_kbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!kbd || !input_dev)
goto fail1;
if (usb_kbd_alloc_mem(dev, kbd))
goto fail2;
kbd->usbdev = dev;
kbd->dev = input_dev;
spin_lock_init(&kbd->leds_lock);
if (dev->manufacturer)
strlcpy(kbd->name, dev->manufacturer, sizeof(kbd->name));
if (dev->product) {
if (dev->manufacturer)
strlcat(kbd->name, " ", sizeof(kbd->name));
strlcat(kbd->name, dev->product, sizeof(kbd->name));
}
if (!strlen(kbd->name))
snprintf(kbd->name, sizeof(kbd->name),
"USB HIDBP Keyboard %04x:%04x",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
usb_make_path(dev, kbd->phys, sizeof(kbd->phys));
strlcat(kbd->phys, "/input0", sizeof(kbd->phys));
input_dev->name = kbd->name;
input_dev->phys = kbd->phys;
usb_to_input_id(dev, &input_dev->id);
input_dev->dev.parent = &iface->dev;
input_set_drvdata(input_dev, kbd);
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) |
BIT_MASK(EV_REP);
input_dev->ledbit[0] = BIT_MASK(LED_NUML) | BIT_MASK(LED_CAPSL) |
BIT_MASK(LED_SCROLLL) | BIT_MASK(LED_COMPOSE) |
BIT_MASK(LED_KANA);
for (i = 0; i < 255; i++)
set_bit(usb_kbd_keycode[i], input_dev->keybit);
clear_bit(0, input_dev->keybit);
input_dev->event = usb_kbd_event;
input_dev->open = usb_kbd_open;
input_dev->close = usb_kbd_close;
usb_fill_int_urb(kbd->irq, dev, pipe,
kbd->new, (maxp > 8 ? 8 : maxp),
usb_kbd_irq, kbd, endpoint->bInterval);
kbd->irq->transfer_dma = kbd->new_dma;
kbd->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
kbd->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
kbd->cr->bRequest = 0x09;
kbd->cr->wValue = cpu_to_le16(0x200);
kbd->cr->wIndex = cpu_to_le16(interface->desc.bInterfaceNumber);
kbd->cr->wLength = cpu_to_le16(1);
usb_fill_control_urb(kbd->led, dev, usb_sndctrlpipe(dev, 0),
(void *) kbd->cr, kbd->leds, 1,
usb_kbd_led, kbd);
kbd->led->transfer_dma = kbd->leds_dma;
kbd->led->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(kbd->dev);
if (error)
goto fail2;
usb_set_intfdata(iface, kbd);
device_set_wakeup_enable(&dev->dev, 1);
return 0;
fail2:
usb_kbd_free_mem(dev, kbd);
fail1:
input_free_device(input_dev);
kfree(kbd);
return error;
}
static void usb_kbd_disconnect(struct usb_interface *intf)
{
struct usb_kbd *kbd = usb_get_intfdata (intf);
usb_set_intfdata(intf, NULL);
if (kbd) {
usb_kill_urb(kbd->irq);
input_unregister_device(kbd->dev);
usb_kill_urb(kbd->led);
usb_kbd_free_mem(interface_to_usbdev(intf), kbd);
kfree(kbd);
}
}
static struct usb_device_id usb_kbd_id_table [] = {
{ USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS_BOOT,
USB_INTERFACE_PROTOCOL_KEYBOARD) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, usb_kbd_id_table);
static struct usb_driver usb_kbd_driver = {
.name = "usbkbd",
.probe = usb_kbd_probe,
.disconnect = usb_kbd_disconnect,
.id_table = usb_kbd_id_table,
};
module_usb_driver(usb_kbd_driver);
|
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdHdrStrong extends React.Component<IconBaseProps> { }
|
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.geom;
import java.awt.geom.Rectangle2D;
import java.awt.geom.PathIterator;
import java.util.Vector;
final class Order0 extends Curve {
private double x;
private double y;
public Order0(double x, double y) {
super(INCREASING);
this.x = x;
this.y = y;
}
public int getOrder() {
return 0;
}
public double getXTop() {
return x;
}
public double getYTop() {
return y;
}
public double getXBot() {
return x;
}
public double getYBot() {
return y;
}
public double getXMin() {
return x;
}
public double getXMax() {
return x;
}
public double getX0() {
return x;
}
public double getY0() {
return y;
}
public double getX1() {
return x;
}
public double getY1() {
return y;
}
public double XforY(double y) {
return y;
}
public double TforY(double y) {
return 0;
}
public double XforT(double t) {
return x;
}
public double YforT(double t) {
return y;
}
public double dXforT(double t, int deriv) {
return 0;
}
public double dYforT(double t, int deriv) {
return 0;
}
public double nextVertical(double t0, double t1) {
return t1;
}
public int crossingsFor(double x, double y) {
return 0;
}
public boolean accumulateCrossings(Crossings c) {
return (x > c.getXLo() &&
x < c.getXHi() &&
y > c.getYLo() &&
y < c.getYHi());
}
public void enlarge(Rectangle2D r) {
r.add(x, y);
}
public Curve getSubCurve(double ystart, double yend, int dir) {
return this;
}
public Curve getReversedCurve() {
return this;
}
public int getSegment(double coords[]) {
coords[0] = x;
coords[1] = y;
return PathIterator.SEG_MOVETO;
}
}
|
# Create a virtual machine from two disks (OS + data disk) in an existing virtual network
<a href="https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Fazure%2Fazure-quickstart-templates%2Fmaster%2F201-os-disk-and-data-disk-existing-vnet%2Fazuredeploy.json" target="_blank">
<img src="http://azuredeploy.net/deploybutton.png"/>
</a>
<a href="http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-os-disk-and-data-disk-existing-vnet%2Fazuredeploy.json" target="_blank">
<img src="http://armviz.io/visualizebutton.png"/>
</a>
## Prerequisites
- VHD files that you want to create a VM from already exists in a storage account.
- Name of the existing VNET and subnet you want to connect the new virtual machine to.
- Name of the Resource Group that the VNET resides in.
```
NOTE
This template will create an additional Standard_LRS storage account for enabling boot diagnostics each time you execute this template. To avoid running into storage account limits, it's best to delete the storage account when the VM is deleted.
```
This template creates a VM from a specialized VHD and a data disk and let you connect it to an existing VNET that can reside in another Resource Group then the virtual machine.
Plese note: This deployment template does not create or attach an existing Network Security Group to the virtual machine.
|
<html>
<head>
<title>Profiler: test console controlling of CPU profiling</title>
<script type="text/javascript" src="resources/fib.js"></script>
<script type="text/javascript">
function profile_fib() {
console.profile();
run_fib();
window.setTimeout('console.profileEnd();', 5000);
}
</script>
</head>
<body onload="profile_fib()">
This test runs and profiles a simple looped computation.
<br>
<br>
TEST
<ul>
<li>load file in the browser;
<li>open DevTools with console (Ctrl+Shift+I on Win/Linux, Command+Option+I on Mac);
<li>go to 'Profiles' page;
<li>observe that 'Profile 1' item has appeared under 'CPU profiles' section;
<li>check for presence of 'eternal_fib' entry in the profile view.
</ul>
<br>
</body>
</html>
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains the string_title class of value object, which provides access to a simple string.
*
* @package core
* @subpackage course
* @copyright 2020 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_course\local\entity;
defined('MOODLE_INTERNAL') || die();
/**
* The string_title class of value object, which provides access to a simple string.
*
* @copyright 2020 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class string_title implements title {
/** @var string $title the title string. */
private $title;
/**
* The string_title constructor.
*
* @param string $title a string.
*/
public function __construct(string $title) {
$this->title = $title;
}
/**
* Return the value of the wrapped string.
*
* @return string
*/
public function get_value(): string {
return $this->title;
}
}
|
/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This is a pure C wrapper of the DataLog class. The functions are directly
// mapped here except for InsertCell as C does not support templates.
// See data_log.h for a description of the functions.
#ifndef SRC_SYSTEM_WRAPPERS_INTERFACE_DATA_LOG_C_H_
#define SRC_SYSTEM_WRAPPERS_INTERFACE_DATA_LOG_C_H_
#include <stddef.h> // size_t
#include "webrtc/typedefs.h"
#ifdef __cplusplus
extern "C" {
#endif
// All char* parameters in this file are expected to be null-terminated
// character sequences.
int WebRtcDataLog_CreateLog();
void WebRtcDataLog_ReturnLog();
char* WebRtcDataLog_Combine(char* combined_name, size_t combined_len,
const char* table_name, int table_id);
int WebRtcDataLog_AddTable(const char* table_name);
int WebRtcDataLog_AddColumn(const char* table_name, const char* column_name,
int multi_value_length);
int WebRtcDataLog_InsertCell_int(const char* table_name,
const char* column_name,
int value);
int WebRtcDataLog_InsertArray_int(const char* table_name,
const char* column_name,
const int* values,
int length);
int WebRtcDataLog_InsertCell_float(const char* table_name,
const char* column_name,
float value);
int WebRtcDataLog_InsertArray_float(const char* table_name,
const char* column_name,
const float* values,
int length);
int WebRtcDataLog_InsertCell_double(const char* table_name,
const char* column_name,
double value);
int WebRtcDataLog_InsertArray_double(const char* table_name,
const char* column_name,
const double* values,
int length);
int WebRtcDataLog_InsertCell_int32(const char* table_name,
const char* column_name,
int32_t value);
int WebRtcDataLog_InsertArray_int32(const char* table_name,
const char* column_name,
const int32_t* values,
int length);
int WebRtcDataLog_InsertCell_uint32(const char* table_name,
const char* column_name,
uint32_t value);
int WebRtcDataLog_InsertArray_uint32(const char* table_name,
const char* column_name,
const uint32_t* values,
int length);
int WebRtcDataLog_InsertCell_int64(const char* table_name,
const char* column_name,
int64_t value);
int WebRtcDataLog_InsertArray_int64(const char* table_name,
const char* column_name,
const int64_t* values,
int length);
int WebRtcDataLog_NextRow(const char* table_name);
#ifdef __cplusplus
} // end of extern "C"
#endif
#endif // SRC_SYSTEM_WRAPPERS_INTERFACE_DATA_LOG_C_H_ // NOLINT
|
<br>
<hr>
<a name="tmva"></a>
<h3>TMVA</h3>
TMVA version 4.1.0 is included in this root release. The most
important new feature is the support for simulataneous classification
of multiple output classes for several multi-variate methods.
A lot of effort went into consolidation of the software,
i.e. method performance and robustness, and framework
stability. The changes with respect to ROOT 5.27 / TMVA 4.0.7 are
in detail:
<h4>Framework</h4>
<ul>
<li><b><em>Multi-class support.</em></b> The support of multiple
output classes (i.e., more than a single background and signal
class) has been enabled for these methods: MLP (NN), BDTG,
FDA.<br>
<div style="margin-left:20; font-size: small">The multiclass
functionality can be enabled with the Factory option
<code>"AnalysisType=multiclass"</code>. Training data is
specified with an additional classname, e.g. via
<code>factory->AddTree(tree,"classname");</code>. After the
training a genetic algorithm is invoked to determine the best
cuts for selecting a specific class, based on the figure of
merit: purity*efficiency. TMVA comes with two examples in
<code>$ROOTSYS/tmva/test</code>: <code>TMVAMulticlass.C</code>
and <code>TMVAMulticlassApplication.C</code></div>
</li>
<li> <b><em>New TMVA event vector building.</em></b> The code
for splitting the input data into training and test samples for
all classes and the mixing of those samples to one training and
one test sample has been rewritten completely. The new code is
more performant and has a clearer structure. This fixes several
bugs which have been reported by some users of TMVA.</li>
<li><b><em>Code and performance test framework</em></b>: A unit
test framework for daily software and method performance
validation has been implemented.
</li>
</ul>
<h4>Methods</h4>
<ul>
<li><b><em>BDT Automatic parameter optimisation for building the
tree architecture</em></b>: The optimisation procedure uses the
performance of the trained classifier on the "test sample" for
finding the set of optimal parameters. Two different methods to
traverse the parameter space are available (scanning, genetic
algorithm). Currently parameter optimization is implemented only
for these three parameters that influence the tree architectur:
the maximum depth of a tree, <code>MaxDepth</code>, the minimum
number of events in each node, <code>NodeMinEvents</code>, and
the number of tress, <code>NTrees</code>.
<div style="margin-left:20; font-size: small">Optimization can
is invoked by calling
<code>factory->OptimizeAllMethods();</code> prior to the call
<code>factory->TrainAllMethods();</code>.</div>
Automated and configurable parameter optimization is soon to
be enabled for all methods (for those parameters where
optimization is applicable).
</li>
<li>
<b><em>BDT node splitting</em></b>: While Decision Trees
typically have only univariate splits, in TMVA one can now
also opt for multivariate splits that use a "Fisher
Discriminant" (option: UseFisherCuts), built from all
observables that show correlations larger than some threshold
(MinLinCorrForFisher). The training will then test at each
split a cut on this fisher discriminant in addition to all
univariate cuts on the variables (or only on those variables
that have not been used in the Fisher discriminant, option
UseExcusiveVars). No obvious improvement betwen very simple
decision trees after boosting has been observed so far, but
only a limited number of studies has been performed concerning
potiential benenfit of these simple multivariate splits.
</li>
</ul>
<h4>Bug fixes</h4>
<ul>
<li>A problem in the BDTG has been fixed, leading to a much
improved regression performance.</li>
<li>A problem in the TMVA::Reader has been fixed.</li>
<li>With the new test framework and the coverity checks of ROOT
a number of bugs were discovered and fixed. They mainly concerned
memory leaks, and did not affect the performance.</li>
</ul>
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\View\Helper;
abstract class AbstractHtmlElement extends AbstractHelper
{
/**
* EOL character
*/
const EOL = PHP_EOL;
/**
* The tag closing bracket
*
* @var string
*/
protected $closingBracket = null;
/**
* Get the tag closing bracket
*
* @return string
*/
public function getClosingBracket()
{
if (!$this->closingBracket) {
if ($this->isXhtml()) {
$this->closingBracket = ' />';
} else {
$this->closingBracket = '>';
}
}
return $this->closingBracket;
}
/**
* Is doctype XHTML?
*
* @return bool
*/
protected function isXhtml()
{
return $this->getView()->plugin('doctype')->isXhtml();
}
/**
* Converts an associative array to a string of tag attributes.
*
* @access public
*
* @param array $attribs From this array, each key-value pair is
* converted to an attribute name and value.
*
* @return string The XHTML for the attributes.
*/
protected function htmlAttribs($attribs)
{
$xhtml = '';
$escaper = $this->getView()->plugin('escapehtml');
foreach ((array) $attribs as $key => $val) {
$key = $escaper($key);
if (('on' == substr($key, 0, 2)) || ('constraints' == $key)) {
// Don't escape event attributes; _do_ substitute double quotes with singles
if (!is_scalar($val)) {
// non-scalar data should be cast to JSON first
$val = \Zend\Json\Json::encode($val);
}
// Escape single quotes inside event attribute values.
// This will create html, where the attribute value has
// single quotes around it, and escaped single quotes or
// non-escaped double quotes inside of it
$val = str_replace('\'', ''', $val);
} else {
if (is_array($val)) {
$val = implode(' ', $val);
}
$val = $escaper($val);
}
if ('id' == $key) {
$val = $this->normalizeId($val);
}
if (strpos($val, '"') !== false) {
$xhtml .= " $key='$val'";
} else {
$xhtml .= " $key=\"$val\"";
}
}
return $xhtml;
}
/**
* Normalize an ID
*
* @param string $value
* @return string
*/
protected function normalizeId($value)
{
if (strstr($value, '[')) {
if ('[]' == substr($value, -2)) {
$value = substr($value, 0, strlen($value) - 2);
}
$value = trim($value, ']');
$value = str_replace('][', '-', $value);
$value = str_replace('[', '-', $value);
}
return $value;
}
}
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Controller;
use Zend\Http\Request as HttpRequest;
use Zend\Json\Json;
use Zend\Mvc\Exception;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
/**
* Abstract RESTful controller
*/
abstract class AbstractRestfulController extends AbstractController
{
const CONTENT_TYPE_JSON = 'json';
/**
* @var string
*/
protected $eventIdentifier = __CLASS__;
/**
* @var array
*/
protected $contentTypes = array(
self::CONTENT_TYPE_JSON => array(
'application/hal+json',
'application/json'
)
);
/**
* Name of request or query parameter containing identifier
*
* @var string
*/
protected $identifierName = 'id';
/**
* @var int From Zend\Json\Json
*/
protected $jsonDecodeType = Json::TYPE_ARRAY;
/**
* Map of custom HTTP methods and their handlers
*
* @var array
*/
protected $customHttpMethodsMap = array();
/**
* Set the route match/query parameter name containing the identifier
*
* @param string $name
* @return self
*/
public function setIdentifierName($name)
{
$this->identifierName = (string) $name;
return $this;
}
/**
* Retrieve the route match/query parameter name containing the identifier
*
* @return string
*/
public function getIdentifierName()
{
return $this->identifierName;
}
/**
* Create a new resource
*
* @param mixed $data
* @return mixed
*/
abstract public function create($data);
/**
* Delete an existing resource
*
* @param mixed $id
* @return mixed
*/
abstract public function delete($id);
/**
* Delete the entire resource collection
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.1.0); instead, raises an exception if not implemented.
*
* @return mixed
* @throws Exception\RuntimeException
*/
public function deleteList()
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Return single resource
*
* @param mixed $id
* @return mixed
*/
abstract public function get($id);
/**
* Return list of resources
*
* @return mixed
*/
abstract public function getList();
/**
* Retrieve HEAD metadata for the resource
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.1.0); instead, raises an exception if not implemented.
*
* @param null|mixed $id
* @return mixed
* @throws Exception\RuntimeException
*/
public function head($id = null)
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Respond to the OPTIONS method
*
* Typically, set the Allow header with allowed HTTP methods, and
* return the response.
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.1.0); instead, raises an exception if not implemented.
*
* @return mixed
* @throws Exception\RuntimeException
*/
public function options()
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Respond to the PATCH method
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.1.0); instead, raises an exception if not implemented.
*
* @param $id
* @param $data
* @throws Exception\RuntimeException
*/
public function patch($id, $data)
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Replace an entire resource collection
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.1.0); instead, raises an exception if not implemented.
*
* @param mixed $data
* @return mixed
* @throws Exception\RuntimeException
*/
public function replaceList($data)
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Modify a resource collection withou completely replacing it
*
* Not marked as abstract, as that would introduce a BC break
* (introduced in 2.2.0); instead, raises an exception if not implemented.
*
* @param mixed $data
* @return mixed
* @throws Exception\RuntimeException
*/
public function patchList($data)
{
throw new Exception\RuntimeException(sprintf(
'%s is unimplemented', __METHOD__
));
}
/**
* Update an existing resource
*
* @param mixed $id
* @param mixed $data
* @return mixed
*/
abstract public function update($id, $data);
/**
* Basic functionality for when a page is not available
*
* @return array
*/
public function notFoundAction()
{
$this->response->setStatusCode(404);
return array(
'content' => 'Page not found'
);
}
/**
* Dispatch a request
*
* If the route match includes an "action" key, then this acts basically like
* a standard action controller. Otherwise, it introspects the HTTP method
* to determine how to handle the request, and which method to delegate to.
*
* @events dispatch.pre, dispatch.post
* @param Request $request
* @param null|Response $response
* @return mixed|Response
* @throws Exception\InvalidArgumentException
*/
public function dispatch(Request $request, Response $response = null)
{
if (! $request instanceof HttpRequest) {
throw new Exception\InvalidArgumentException(
'Expected an HTTP request');
}
return parent::dispatch($request, $response);
}
/**
* Handle the request
*
* @todo try-catch in "patch" for patchList should be removed in the future
* @param MvcEvent $e
* @return mixed
* @throws Exception\DomainException if no route matches in event or invalid HTTP method
*/
public function onDispatch(MvcEvent $e)
{
$routeMatch = $e->getRouteMatch();
if (! $routeMatch) {
/**
* @todo Determine requirements for when route match is missing.
* Potentially allow pulling directly from request metadata?
*/
throw new Exception\DomainException(
'Missing route matches; unsure how to retrieve action');
}
$request = $e->getRequest();
// Was an "action" requested?
$action = $routeMatch->getParam('action', false);
if ($action) {
// Handle arbitrary methods, ending in Action
$method = static::getMethodFromAction($action);
if (! method_exists($this, $method)) {
$method = 'notFoundAction';
}
$return = $this->$method();
$e->setResult($return);
return $return;
}
// RESTful methods
$method = strtolower($request->getMethod());
switch ($method) {
// Custom HTTP methods (or custom overrides for standard methods)
case (isset($this->customHttpMethodsMap[$method])):
$callable = $this->customHttpMethodsMap[$method];
$action = $method;
$return = call_user_func($callable, $e);
break;
// DELETE
case 'delete':
$id = $this->getIdentifier($routeMatch, $request);
if ($id !== false) {
$action = 'delete';
$return = $this->delete($id);
break;
}
$action = 'deleteList';
$return = $this->deleteList();
break;
// GET
case 'get':
$id = $this->getIdentifier($routeMatch, $request);
if ($id !== false) {
$action = 'get';
$return = $this->get($id);
break;
}
$action = 'getList';
$return = $this->getList();
break;
// HEAD
case 'head':
$id = $this->getIdentifier($routeMatch, $request);
if ($id === false) {
$id = null;
}
$action = 'head';
$this->head($id);
$response = $e->getResponse();
$response->setContent('');
$return = $response;
break;
// OPTIONS
case 'options':
$action = 'options';
$this->options();
$return = $e->getResponse();
break;
// PATCH
case 'patch':
$id = $this->getIdentifier($routeMatch, $request);
$data = $this->processBodyContent($request);
if ($id !== false) {
$action = 'patch';
$return = $this->patch($id, $data);
break;
}
// TODO: This try-catch should be removed in the future, but it
// will create a BC break for pre-2.2.0 apps that expect a 405
// instead of going to patchList
try {
$action = 'patchList';
$return = $this->patchList($data);
} catch (Exception\RuntimeException $ex) {
$response = $e->getResponse();
$response->setStatusCode(405);
return $response;
}
break;
// POST
case 'post':
$action = 'create';
$return = $this->processPostData($request);
break;
// PUT
case 'put':
$id = $this->getIdentifier($routeMatch, $request);
$data = $this->processBodyContent($request);
if ($id !== false) {
$action = 'update';
$return = $this->update($id, $data);
break;
}
$action = 'replaceList';
$return = $this->replaceList($data);
break;
// All others...
default:
$response = $e->getResponse();
$response->setStatusCode(405);
return $response;
}
$routeMatch->setParam('action', $action);
$e->setResult($return);
return $return;
}
/**
* Process post data and call create
*
* @param Request $request
* @return mixed
*/
public function processPostData(Request $request)
{
if ($this->requestHasContentType($request, self::CONTENT_TYPE_JSON)) {
$data = Json::decode($request->getContent(), $this->jsonDecodeType);
} else {
$data = $request->getPost()->toArray();
}
return $this->create($data);
}
/**
* Check if request has certain content type
*
* @param Request $request
* @param string|null $contentType
* @return bool
*/
public function requestHasContentType(Request $request, $contentType = '')
{
/** @var $headerContentType \Zend\Http\Header\ContentType */
$headerContentType = $request->getHeaders()->get('content-type');
if (!$headerContentType) {
return false;
}
$requestedContentType = $headerContentType->getFieldValue();
if (strstr($requestedContentType, ';')) {
$headerData = explode(';', $requestedContentType);
$requestedContentType = array_shift($headerData);
}
$requestedContentType = trim($requestedContentType);
if (array_key_exists($contentType, $this->contentTypes)) {
foreach ($this->contentTypes[$contentType] as $contentTypeValue) {
if (stripos($contentTypeValue, $requestedContentType) === 0) {
return true;
}
}
}
return false;
}
/**
* Register a handler for a custom HTTP method
*
* This method allows you to handle arbitrary HTTP method types, mapping
* them to callables. Typically, these will be methods of the controller
* instance: e.g., array($this, 'foobar'). The typical place to register
* these is in your constructor.
*
* Additionally, as this map is checked prior to testing the standard HTTP
* methods, this is a way to override what methods will handle the standard
* HTTP methods. However, if you do this, you will have to retrieve the
* identifier and any request content manually.
*
* Callbacks will be passed the current MvcEvent instance.
*
* To retrieve the identifier, you can use "$id =
* $this->getIdentifier($routeMatch, $request)",
* passing the appropriate objects.
*
* To retrive the body content data, use "$data = $this->processBodyContent($request)";
* that method will return a string, array, or, in the case of JSON, an object.
*
* @param string $method
* @param Callable $handler
* @return AbstractRestfulController
*/
public function addHttpMethodHandler($method, /* Callable */ $handler)
{
if (!is_callable($handler)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid HTTP method handler: must be a callable; received "%s"',
(is_object($handler) ? get_class($handler) : gettype($handler))
));
}
$method = strtolower($method);
$this->customHttpMethodsMap[$method] = $handler;
return $this;
}
/**
* Retrieve the identifier, if any
*
* Attempts to see if an identifier was passed in either the URI or the
* query string, returning it if found. Otherwise, returns a boolean false.
*
* @param \Zend\Mvc\Router\RouteMatch $routeMatch
* @param Request $request
* @return false|mixed
*/
protected function getIdentifier($routeMatch, $request)
{
$identifier = $this->getIdentifierName();
$id = $routeMatch->getParam($identifier, false);
if ($id !== false) {
return $id;
}
$id = $request->getQuery()->get($identifier, false);
if ($id !== false) {
return $id;
}
return false;
}
/**
* Process the raw body content
*
* If the content-type indicates a JSON payload, the payload is immediately
* decoded and the data returned. Otherwise, the data is passed to
* parse_str(). If that function returns a single-member array with a key
* of "0", the method assumes that we have non-urlencoded content and
* returns the raw content; otherwise, the array created is returned.
*
* @param mixed $request
* @return object|string|array
*/
protected function processBodyContent($request)
{
$content = $request->getContent();
// JSON content? decode and return it.
if ($this->requestHasContentType($request, self::CONTENT_TYPE_JSON)) {
return Json::decode($content, $this->jsonDecodeType);
}
parse_str($content, $parsedParams);
// If parse_str fails to decode, or we have a single element with key
// 0, return the raw content.
if (!is_array($parsedParams)
|| (1 == count($parsedParams) && isset($parsedParams[0]))
) {
return $content;
}
return $parsedParams;
}
}
|
/*
* jQuery UI Effects Pulsate 1.7.2
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Effects/Pulsate
*
* Depends:
* effects.core.js
*/
(function($) {
$.effects.pulsate = function(o) {
return this.queue(function() {
// Create element
var el = $(this);
// Set options
var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
var times = o.options.times || 5; // Default # of times
var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;
// Adjust
if (mode == 'hide') times--;
if (el.is(':hidden')) { // Show fadeIn
el.css('opacity', 0);
el.show(); // Show
el.animate({opacity: 1}, duration, o.options.easing);
times = times-2;
}
// Animate
for (var i = 0; i < times; i++) { // Pulsate
el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing);
};
if (mode == 'hide') { // Last Pulse
el.animate({opacity: 0}, duration, o.options.easing, function(){
el.hide(); // Hide
if(o.callback) o.callback.apply(this, arguments); // Callback
});
} else {
el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){
if(o.callback) o.callback.apply(this, arguments); // Callback
});
};
el.queue('fx', function() { el.dequeue(); });
el.dequeue();
});
};
})(jQuery);
|
<?php
/** @file
* This file is part of Google Chart PHP library.
*
* Copyright (c) 2010 Rémi Lanvin <remi@cloudconnected.fr>
*
* Licensed under the MIT license.
*
* For the full copyright and license information, please view the LICENSE file.
*/
/**
* A Marker.
*
* This in an abstract class that is used by all the Markers type.
*
* Marker implementation in Google Chart API is quite complex. There are many types
* of markers (value, line, shape, candlestick and range) and each has a
* different set of parameter and a slightly different logic. So each type has
* its own class, that extends GoogleChartMarker.
*
* To display a marker, you need to set a data serie using setData() function.
* A data serie is a GoogleChartData object. It contains points used by the
* marker. You can provides an existing data serie (i.e. a data serie that has been
* or will be added to the chart with GoogleChart::addData()) or a new data serie.
* In this case, the data serie will be hidden. Please refer to Google Chart API
* documentation about compound chart for further information.
*/
abstract class GoogleChartMarker
{
/**
* @var GoogleChartData Will hold the data serie.
*/
protected $data = null;
/**
* @name Common parameters to every markers
*/
//@{
/**
* @var string Color of the marker
*/
protected $color = '4D89F9';
/**
* @var float Z-order of the marker
*/
protected $z_order = null;
//@}
/**
* Set the color of the marker.
*
* @param $color (string)
*/
public function setColor($color)
{
$this->color = $color;
return $this;
}
/**
* Return the color.
*
* @return string
*/
public function getColor()
{
return $this->color;
}
public function setZOrder($z_order)
{
if ( $z_order < -1 || $z_order > 1 )
throw new InvalidArgumentException('Invalid Z-order (must be between -1.0 and 1.0)');
$this->z_order = $z_order;
return $this;
}
public function getZOrder($z_order)
{
return $this->z_order;
}
public function setData(GoogleChartData $data)
{
$this->data = $data;
return $this;
}
public function getData()
{
return $this->data;
}
abstract public function compute($index, $chart_type = null);
}
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QTCPSERVER_H
#define QTCPSERVER_H
#include <QtCore/qobject.h>
#include <QtNetwork/qabstractsocket.h>
#include <QtNetwork/qhostaddress.h>
QT_BEGIN_NAMESPACE
class QTcpServerPrivate;
#ifndef QT_NO_NETWORKPROXY
class QNetworkProxy;
#endif
class QTcpSocket;
class Q_NETWORK_EXPORT QTcpServer : public QObject
{
Q_OBJECT
public:
explicit QTcpServer(QObject *parent = 0);
virtual ~QTcpServer();
bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
void close();
bool isListening() const;
void setMaxPendingConnections(int numConnections);
int maxPendingConnections() const;
quint16 serverPort() const;
QHostAddress serverAddress() const;
qintptr socketDescriptor() const;
bool setSocketDescriptor(qintptr socketDescriptor);
bool waitForNewConnection(int msec = 0, bool *timedOut = 0);
virtual bool hasPendingConnections() const;
virtual QTcpSocket *nextPendingConnection();
QAbstractSocket::SocketError serverError() const;
QString errorString() const;
void pauseAccepting();
void resumeAccepting();
#ifndef QT_NO_NETWORKPROXY
void setProxy(const QNetworkProxy &networkProxy);
QNetworkProxy proxy() const;
#endif
protected:
virtual void incomingConnection(qintptr handle);
void addPendingConnection(QTcpSocket* socket);
Q_SIGNALS:
void newConnection();
void acceptError(QAbstractSocket::SocketError socketError);
private:
Q_DISABLE_COPY(QTcpServer)
Q_DECLARE_PRIVATE(QTcpServer)
};
QT_END_NAMESPACE
#endif // QTCPSERVER_H
|
<!--
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
Copyright (c) Microsoft Corporation. All rights reserved
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Article</title>
<!-- WinJS references -->
<link href="/Microsoft.WinJS.4.0/css/ui-dark.css" rel="stylesheet">
<script src="/Microsoft.WinJS.4.0/js/WinJS.js"></script>
<link href="/css/default.css" rel="stylesheet">
<link href="/pages/article/article.css" rel="stylesheet">
<script src="/pages/article/article.js"></script>
</head>
<body class="win-type-body">
<!-- The content that will be loaded and displayed. -->
<div id="article" class="fragment">
<header aria-label="Header content" role="banner">
<button class="win-backbutton win-button" aria-label="Back" disabled></button>
<h1 class="titlearea win-type-ellipsis win-type-header">
<span class="pagetitle"></span>
</h1>
</header>
<div id="articleArea" aria-label="Main content" role="main">
<article>
<div id="content"></div>
</article>
</div>
</div>
</body>
</html> |
/*
* A hwmon driver for the Analog Devices ADT7470
* Copyright (C) 2007 IBM
*
* Author: Darrick J. Wong <darrick.wong@oracle.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/log2.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/util_macros.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2C, 0x2E, 0x2F, I2C_CLIENT_END };
/* ADT7470 registers */
#define ADT7470_REG_BASE_ADDR 0x20
#define ADT7470_REG_TEMP_BASE_ADDR 0x20
#define ADT7470_REG_TEMP_MAX_ADDR 0x29
#define ADT7470_REG_FAN_BASE_ADDR 0x2A
#define ADT7470_REG_FAN_MAX_ADDR 0x31
#define ADT7470_REG_PWM_BASE_ADDR 0x32
#define ADT7470_REG_PWM_MAX_ADDR 0x35
#define ADT7470_REG_PWM_MAX_BASE_ADDR 0x38
#define ADT7470_REG_PWM_MAX_MAX_ADDR 0x3B
#define ADT7470_REG_CFG 0x40
#define ADT7470_FSPD_MASK 0x04
#define ADT7470_REG_ALARM1 0x41
#define ADT7470_R1T_ALARM 0x01
#define ADT7470_R2T_ALARM 0x02
#define ADT7470_R3T_ALARM 0x04
#define ADT7470_R4T_ALARM 0x08
#define ADT7470_R5T_ALARM 0x10
#define ADT7470_R6T_ALARM 0x20
#define ADT7470_R7T_ALARM 0x40
#define ADT7470_OOL_ALARM 0x80
#define ADT7470_REG_ALARM2 0x42
#define ADT7470_R8T_ALARM 0x01
#define ADT7470_R9T_ALARM 0x02
#define ADT7470_R10T_ALARM 0x04
#define ADT7470_FAN1_ALARM 0x10
#define ADT7470_FAN2_ALARM 0x20
#define ADT7470_FAN3_ALARM 0x40
#define ADT7470_FAN4_ALARM 0x80
#define ADT7470_REG_TEMP_LIMITS_BASE_ADDR 0x44
#define ADT7470_REG_TEMP_LIMITS_MAX_ADDR 0x57
#define ADT7470_REG_FAN_MIN_BASE_ADDR 0x58
#define ADT7470_REG_FAN_MIN_MAX_ADDR 0x5F
#define ADT7470_REG_FAN_MAX_BASE_ADDR 0x60
#define ADT7470_REG_FAN_MAX_MAX_ADDR 0x67
#define ADT7470_REG_PWM_CFG_BASE_ADDR 0x68
#define ADT7470_REG_PWM12_CFG 0x68
#define ADT7470_PWM2_AUTO_MASK 0x40
#define ADT7470_PWM1_AUTO_MASK 0x80
#define ADT7470_PWM_AUTO_MASK 0xC0
#define ADT7470_REG_PWM34_CFG 0x69
#define ADT7470_PWM3_AUTO_MASK 0x40
#define ADT7470_PWM4_AUTO_MASK 0x80
#define ADT7470_REG_PWM_MIN_BASE_ADDR 0x6A
#define ADT7470_REG_PWM_MIN_MAX_ADDR 0x6D
#define ADT7470_REG_PWM_TEMP_MIN_BASE_ADDR 0x6E
#define ADT7470_REG_PWM_TEMP_MIN_MAX_ADDR 0x71
#define ADT7470_REG_CFG_2 0x74
#define ADT7470_REG_ACOUSTICS12 0x75
#define ADT7470_REG_ACOUSTICS34 0x76
#define ADT7470_REG_DEVICE 0x3D
#define ADT7470_REG_VENDOR 0x3E
#define ADT7470_REG_REVISION 0x3F
#define ADT7470_REG_ALARM1_MASK 0x72
#define ADT7470_REG_ALARM2_MASK 0x73
#define ADT7470_REG_PWM_AUTO_TEMP_BASE_ADDR 0x7C
#define ADT7470_REG_PWM_AUTO_TEMP_MAX_ADDR 0x7D
#define ADT7470_REG_MAX_ADDR 0x81
#define ADT7470_TEMP_COUNT 10
#define ADT7470_TEMP_REG(x) (ADT7470_REG_TEMP_BASE_ADDR + (x))
#define ADT7470_TEMP_MIN_REG(x) (ADT7470_REG_TEMP_LIMITS_BASE_ADDR + ((x) * 2))
#define ADT7470_TEMP_MAX_REG(x) (ADT7470_REG_TEMP_LIMITS_BASE_ADDR + \
((x) * 2) + 1)
#define ADT7470_FAN_COUNT 4
#define ADT7470_REG_FAN(x) (ADT7470_REG_FAN_BASE_ADDR + ((x) * 2))
#define ADT7470_REG_FAN_MIN(x) (ADT7470_REG_FAN_MIN_BASE_ADDR + ((x) * 2))
#define ADT7470_REG_FAN_MAX(x) (ADT7470_REG_FAN_MAX_BASE_ADDR + ((x) * 2))
#define ADT7470_PWM_COUNT 4
#define ADT7470_REG_PWM(x) (ADT7470_REG_PWM_BASE_ADDR + (x))
#define ADT7470_REG_PWM_MAX(x) (ADT7470_REG_PWM_MAX_BASE_ADDR + (x))
#define ADT7470_REG_PWM_MIN(x) (ADT7470_REG_PWM_MIN_BASE_ADDR + (x))
#define ADT7470_REG_PWM_TMIN(x) (ADT7470_REG_PWM_TEMP_MIN_BASE_ADDR + (x))
#define ADT7470_REG_PWM_CFG(x) (ADT7470_REG_PWM_CFG_BASE_ADDR + ((x) / 2))
#define ADT7470_REG_PWM_AUTO_TEMP(x) (ADT7470_REG_PWM_AUTO_TEMP_BASE_ADDR + \
((x) / 2))
#define ALARM2(x) ((x) << 8)
#define ADT7470_VENDOR 0x41
#define ADT7470_DEVICE 0x70
/* datasheet only mentions a revision 2 */
#define ADT7470_REVISION 0x02
/* "all temps" according to hwmon sysfs interface spec */
#define ADT7470_PWM_ALL_TEMPS 0x3FF
/* How often do we reread sensors values? (In jiffies) */
#define SENSOR_REFRESH_INTERVAL (5 * HZ)
/* How often do we reread sensor limit values? (In jiffies) */
#define LIMIT_REFRESH_INTERVAL (60 * HZ)
/* Wait at least 200ms per sensor for 10 sensors */
#define TEMP_COLLECTION_TIME 2000
/* auto update thing won't fire more than every 2s */
#define AUTO_UPDATE_INTERVAL 2000
/* datasheet says to divide this number by the fan reading to get fan rpm */
#define FAN_PERIOD_TO_RPM(x) ((90000 * 60) / (x))
#define FAN_RPM_TO_PERIOD FAN_PERIOD_TO_RPM
#define FAN_PERIOD_INVALID 65535
#define FAN_DATA_VALID(x) ((x) && (x) != FAN_PERIOD_INVALID)
/* Config registers 1 and 2 include fields for selecting the PWM frequency */
#define ADT7470_CFG_LF 0x40
#define ADT7470_FREQ_MASK 0x70
#define ADT7470_FREQ_SHIFT 4
struct adt7470_data {
struct i2c_client *client;
struct mutex lock;
char sensors_valid;
char limits_valid;
unsigned long sensors_last_updated; /* In jiffies */
unsigned long limits_last_updated; /* In jiffies */
int num_temp_sensors; /* -1 = probe */
int temperatures_probed;
s8 temp[ADT7470_TEMP_COUNT];
s8 temp_min[ADT7470_TEMP_COUNT];
s8 temp_max[ADT7470_TEMP_COUNT];
u16 fan[ADT7470_FAN_COUNT];
u16 fan_min[ADT7470_FAN_COUNT];
u16 fan_max[ADT7470_FAN_COUNT];
u16 alarm;
u16 alarms_mask;
u8 force_pwm_max;
u8 pwm[ADT7470_PWM_COUNT];
u8 pwm_max[ADT7470_PWM_COUNT];
u8 pwm_automatic[ADT7470_PWM_COUNT];
u8 pwm_min[ADT7470_PWM_COUNT];
s8 pwm_tmin[ADT7470_PWM_COUNT];
u8 pwm_auto_temp[ADT7470_PWM_COUNT];
struct task_struct *auto_update;
unsigned int auto_update_interval;
};
/*
* 16-bit registers on the ADT7470 are low-byte first. The data sheet says
* that the low byte must be read before the high byte.
*/
static inline int adt7470_read_word_data(struct i2c_client *client, u8 reg)
{
u16 foo;
foo = i2c_smbus_read_byte_data(client, reg);
foo |= ((u16)i2c_smbus_read_byte_data(client, reg + 1) << 8);
return foo;
}
static inline int adt7470_write_word_data(struct i2c_client *client, u8 reg,
u16 value)
{
return i2c_smbus_write_byte_data(client, reg, value & 0xFF)
|| i2c_smbus_write_byte_data(client, reg + 1, value >> 8);
}
/* Probe for temperature sensors. Assumes lock is held */
static int adt7470_read_temperatures(struct i2c_client *client,
struct adt7470_data *data)
{
unsigned long res;
int i;
u8 cfg, pwm[4], pwm_cfg[2];
/* save pwm[1-4] config register */
pwm_cfg[0] = i2c_smbus_read_byte_data(client, ADT7470_REG_PWM_CFG(0));
pwm_cfg[1] = i2c_smbus_read_byte_data(client, ADT7470_REG_PWM_CFG(2));
/* set manual pwm to whatever it is set to now */
for (i = 0; i < ADT7470_FAN_COUNT; i++)
pwm[i] = i2c_smbus_read_byte_data(client, ADT7470_REG_PWM(i));
/* put pwm in manual mode */
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_CFG(0),
pwm_cfg[0] & ~(ADT7470_PWM_AUTO_MASK));
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_CFG(2),
pwm_cfg[1] & ~(ADT7470_PWM_AUTO_MASK));
/* write pwm control to whatever it was */
for (i = 0; i < ADT7470_FAN_COUNT; i++)
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM(i), pwm[i]);
/* start reading temperature sensors */
cfg = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG);
cfg |= 0x80;
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG, cfg);
/* Delay is 200ms * number of temp sensors. */
res = msleep_interruptible((data->num_temp_sensors >= 0 ?
data->num_temp_sensors * 200 :
TEMP_COLLECTION_TIME));
/* done reading temperature sensors */
cfg = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG);
cfg &= ~0x80;
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG, cfg);
/* restore pwm[1-4] config registers */
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_CFG(0), pwm_cfg[0]);
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_CFG(2), pwm_cfg[1]);
if (res) {
pr_err("ha ha, interrupted\n");
return -EAGAIN;
}
/* Only count fans if we have to */
if (data->num_temp_sensors >= 0)
return 0;
for (i = 0; i < ADT7470_TEMP_COUNT; i++) {
data->temp[i] = i2c_smbus_read_byte_data(client,
ADT7470_TEMP_REG(i));
if (data->temp[i])
data->num_temp_sensors = i + 1;
}
data->temperatures_probed = 1;
return 0;
}
static int adt7470_update_thread(void *p)
{
struct i2c_client *client = p;
struct adt7470_data *data = i2c_get_clientdata(client);
while (!kthread_should_stop()) {
mutex_lock(&data->lock);
adt7470_read_temperatures(client, data);
mutex_unlock(&data->lock);
set_current_state(TASK_INTERRUPTIBLE);
if (kthread_should_stop())
break;
schedule_timeout(msecs_to_jiffies(data->auto_update_interval));
}
return 0;
}
static struct adt7470_data *adt7470_update_device(struct device *dev)
{
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
unsigned long local_jiffies = jiffies;
u8 cfg;
int i;
int need_sensors = 1;
int need_limits = 1;
/*
* Figure out if we need to update the shadow registers.
* Lockless means that we may occasionally report out of
* date data.
*/
if (time_before(local_jiffies, data->sensors_last_updated +
SENSOR_REFRESH_INTERVAL) &&
data->sensors_valid)
need_sensors = 0;
if (time_before(local_jiffies, data->limits_last_updated +
LIMIT_REFRESH_INTERVAL) &&
data->limits_valid)
need_limits = 0;
if (!need_sensors && !need_limits)
return data;
mutex_lock(&data->lock);
if (!need_sensors)
goto no_sensor_update;
if (!data->temperatures_probed)
adt7470_read_temperatures(client, data);
else
for (i = 0; i < ADT7470_TEMP_COUNT; i++)
data->temp[i] = i2c_smbus_read_byte_data(client,
ADT7470_TEMP_REG(i));
for (i = 0; i < ADT7470_FAN_COUNT; i++)
data->fan[i] = adt7470_read_word_data(client,
ADT7470_REG_FAN(i));
for (i = 0; i < ADT7470_PWM_COUNT; i++) {
int reg;
int reg_mask;
data->pwm[i] = i2c_smbus_read_byte_data(client,
ADT7470_REG_PWM(i));
if (i % 2)
reg_mask = ADT7470_PWM2_AUTO_MASK;
else
reg_mask = ADT7470_PWM1_AUTO_MASK;
reg = ADT7470_REG_PWM_CFG(i);
if (i2c_smbus_read_byte_data(client, reg) & reg_mask)
data->pwm_automatic[i] = 1;
else
data->pwm_automatic[i] = 0;
reg = ADT7470_REG_PWM_AUTO_TEMP(i);
cfg = i2c_smbus_read_byte_data(client, reg);
if (!(i % 2))
data->pwm_auto_temp[i] = cfg >> 4;
else
data->pwm_auto_temp[i] = cfg & 0xF;
}
if (i2c_smbus_read_byte_data(client, ADT7470_REG_CFG) &
ADT7470_FSPD_MASK)
data->force_pwm_max = 1;
else
data->force_pwm_max = 0;
data->alarm = i2c_smbus_read_byte_data(client, ADT7470_REG_ALARM1);
if (data->alarm & ADT7470_OOL_ALARM)
data->alarm |= ALARM2(i2c_smbus_read_byte_data(client,
ADT7470_REG_ALARM2));
data->alarms_mask = adt7470_read_word_data(client,
ADT7470_REG_ALARM1_MASK);
data->sensors_last_updated = local_jiffies;
data->sensors_valid = 1;
no_sensor_update:
if (!need_limits)
goto out;
for (i = 0; i < ADT7470_TEMP_COUNT; i++) {
data->temp_min[i] = i2c_smbus_read_byte_data(client,
ADT7470_TEMP_MIN_REG(i));
data->temp_max[i] = i2c_smbus_read_byte_data(client,
ADT7470_TEMP_MAX_REG(i));
}
for (i = 0; i < ADT7470_FAN_COUNT; i++) {
data->fan_min[i] = adt7470_read_word_data(client,
ADT7470_REG_FAN_MIN(i));
data->fan_max[i] = adt7470_read_word_data(client,
ADT7470_REG_FAN_MAX(i));
}
for (i = 0; i < ADT7470_PWM_COUNT; i++) {
data->pwm_max[i] = i2c_smbus_read_byte_data(client,
ADT7470_REG_PWM_MAX(i));
data->pwm_min[i] = i2c_smbus_read_byte_data(client,
ADT7470_REG_PWM_MIN(i));
data->pwm_tmin[i] = i2c_smbus_read_byte_data(client,
ADT7470_REG_PWM_TMIN(i));
}
data->limits_last_updated = local_jiffies;
data->limits_valid = 1;
out:
mutex_unlock(&data->lock);
return data;
}
static ssize_t show_auto_update_interval(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->auto_update_interval);
}
static ssize_t set_auto_update_interval(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct adt7470_data *data = dev_get_drvdata(dev);
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = clamp_val(temp, 0, 60000);
mutex_lock(&data->lock);
data->auto_update_interval = temp;
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_num_temp_sensors(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->num_temp_sensors);
}
static ssize_t set_num_temp_sensors(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct adt7470_data *data = dev_get_drvdata(dev);
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = clamp_val(temp, -1, 10);
mutex_lock(&data->lock);
data->num_temp_sensors = temp;
if (temp < 0)
data->temperatures_probed = 0;
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", 1000 * data->temp_min[attr->index]);
}
static ssize_t set_temp_min(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = DIV_ROUND_CLOSEST(temp, 1000);
temp = clamp_val(temp, -128, 127);
mutex_lock(&data->lock);
data->temp_min[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_TEMP_MIN_REG(attr->index),
temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", 1000 * data->temp_max[attr->index]);
}
static ssize_t set_temp_max(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = DIV_ROUND_CLOSEST(temp, 1000);
temp = clamp_val(temp, -128, 127);
mutex_lock(&data->lock);
data->temp_max[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_TEMP_MAX_REG(attr->index),
temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_temp(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", 1000 * data->temp[attr->index]);
}
static ssize_t show_alarm_mask(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%x\n", data->alarms_mask);
}
static ssize_t set_alarm_mask(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct adt7470_data *data = dev_get_drvdata(dev);
long mask;
if (kstrtoul(buf, 0, &mask))
return -EINVAL;
if (mask & ~0xffff)
return -EINVAL;
mutex_lock(&data->lock);
data->alarms_mask = mask;
adt7470_write_word_data(data->client, ADT7470_REG_ALARM1_MASK, mask);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_fan_max(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
if (FAN_DATA_VALID(data->fan_max[attr->index]))
return sprintf(buf, "%d\n",
FAN_PERIOD_TO_RPM(data->fan_max[attr->index]));
else
return sprintf(buf, "0\n");
}
static ssize_t set_fan_max(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp) || !temp)
return -EINVAL;
temp = FAN_RPM_TO_PERIOD(temp);
temp = clamp_val(temp, 1, 65534);
mutex_lock(&data->lock);
data->fan_max[attr->index] = temp;
adt7470_write_word_data(client, ADT7470_REG_FAN_MAX(attr->index), temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_fan_min(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
if (FAN_DATA_VALID(data->fan_min[attr->index]))
return sprintf(buf, "%d\n",
FAN_PERIOD_TO_RPM(data->fan_min[attr->index]));
else
return sprintf(buf, "0\n");
}
static ssize_t set_fan_min(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp) || !temp)
return -EINVAL;
temp = FAN_RPM_TO_PERIOD(temp);
temp = clamp_val(temp, 1, 65534);
mutex_lock(&data->lock);
data->fan_min[attr->index] = temp;
adt7470_write_word_data(client, ADT7470_REG_FAN_MIN(attr->index), temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
if (FAN_DATA_VALID(data->fan[attr->index]))
return sprintf(buf, "%d\n",
FAN_PERIOD_TO_RPM(data->fan[attr->index]));
else
return sprintf(buf, "0\n");
}
static ssize_t show_force_pwm_max(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->force_pwm_max);
}
static ssize_t set_force_pwm_max(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
u8 reg;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
mutex_lock(&data->lock);
data->force_pwm_max = temp;
reg = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG);
if (temp)
reg |= ADT7470_FSPD_MASK;
else
reg &= ~ADT7470_FSPD_MASK;
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG, reg);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->pwm[attr->index]);
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = clamp_val(temp, 0, 255);
mutex_lock(&data->lock);
data->pwm[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM(attr->index), temp);
mutex_unlock(&data->lock);
return count;
}
/* These are the valid PWM frequencies to the nearest Hz */
static const int adt7470_freq_map[] = {
11, 15, 22, 29, 35, 44, 59, 88, 1400, 22500
};
static ssize_t show_pwm_freq(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct adt7470_data *data = adt7470_update_device(dev);
unsigned char cfg_reg_1;
unsigned char cfg_reg_2;
int index;
mutex_lock(&data->lock);
cfg_reg_1 = i2c_smbus_read_byte_data(data->client, ADT7470_REG_CFG);
cfg_reg_2 = i2c_smbus_read_byte_data(data->client, ADT7470_REG_CFG_2);
mutex_unlock(&data->lock);
index = (cfg_reg_2 & ADT7470_FREQ_MASK) >> ADT7470_FREQ_SHIFT;
if (!(cfg_reg_1 & ADT7470_CFG_LF))
index += 8;
if (index >= ARRAY_SIZE(adt7470_freq_map))
index = ARRAY_SIZE(adt7470_freq_map) - 1;
return scnprintf(buf, PAGE_SIZE, "%d\n", adt7470_freq_map[index]);
}
static ssize_t set_pwm_freq(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long freq;
int index;
int low_freq = ADT7470_CFG_LF;
unsigned char val;
if (kstrtol(buf, 10, &freq))
return -EINVAL;
/* Round the user value given to the closest available frequency */
index = find_closest(freq, adt7470_freq_map,
ARRAY_SIZE(adt7470_freq_map));
if (index >= 8) {
index -= 8;
low_freq = 0;
}
mutex_lock(&data->lock);
/* Configuration Register 1 */
val = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG);
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG,
(val & ~ADT7470_CFG_LF) | low_freq);
/* Configuration Register 2 */
val = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG_2);
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG_2,
(val & ~ADT7470_FREQ_MASK) | (index << ADT7470_FREQ_SHIFT));
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm_max(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->pwm_max[attr->index]);
}
static ssize_t set_pwm_max(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = clamp_val(temp, 0, 255);
mutex_lock(&data->lock);
data->pwm_max[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_MAX(attr->index),
temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm_min(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", data->pwm_min[attr->index]);
}
static ssize_t set_pwm_min(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = clamp_val(temp, 0, 255);
mutex_lock(&data->lock);
data->pwm_min[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_MIN(attr->index),
temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm_tmax(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
/* the datasheet says that tmax = tmin + 20C */
return sprintf(buf, "%d\n", 1000 * (20 + data->pwm_tmin[attr->index]));
}
static ssize_t show_pwm_tmin(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", 1000 * data->pwm_tmin[attr->index]);
}
static ssize_t set_pwm_tmin(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
long temp;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = DIV_ROUND_CLOSEST(temp, 1000);
temp = clamp_val(temp, -128, 127);
mutex_lock(&data->lock);
data->pwm_tmin[attr->index] = temp;
i2c_smbus_write_byte_data(client, ADT7470_REG_PWM_TMIN(attr->index),
temp);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm_auto(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
return sprintf(buf, "%d\n", 1 + data->pwm_automatic[attr->index]);
}
static ssize_t set_pwm_auto(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int pwm_auto_reg = ADT7470_REG_PWM_CFG(attr->index);
int pwm_auto_reg_mask;
long temp;
u8 reg;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
if (attr->index % 2)
pwm_auto_reg_mask = ADT7470_PWM2_AUTO_MASK;
else
pwm_auto_reg_mask = ADT7470_PWM1_AUTO_MASK;
if (temp != 2 && temp != 1)
return -EINVAL;
temp--;
mutex_lock(&data->lock);
data->pwm_automatic[attr->index] = temp;
reg = i2c_smbus_read_byte_data(client, pwm_auto_reg);
if (temp)
reg |= pwm_auto_reg_mask;
else
reg &= ~pwm_auto_reg_mask;
i2c_smbus_write_byte_data(client, pwm_auto_reg, reg);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_pwm_auto_temp(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
u8 ctrl = data->pwm_auto_temp[attr->index];
if (ctrl)
return sprintf(buf, "%d\n", 1 << (ctrl - 1));
else
return sprintf(buf, "%d\n", ADT7470_PWM_ALL_TEMPS);
}
static int cvt_auto_temp(int input)
{
if (input == ADT7470_PWM_ALL_TEMPS)
return 0;
if (input < 1 || !is_power_of_2(input))
return -EINVAL;
return ilog2(input) + 1;
}
static ssize_t set_pwm_auto_temp(struct device *dev,
struct device_attribute *devattr,
const char *buf,
size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
int pwm_auto_reg = ADT7470_REG_PWM_AUTO_TEMP(attr->index);
long temp;
u8 reg;
if (kstrtol(buf, 10, &temp))
return -EINVAL;
temp = cvt_auto_temp(temp);
if (temp < 0)
return temp;
mutex_lock(&data->lock);
data->pwm_automatic[attr->index] = temp;
reg = i2c_smbus_read_byte_data(client, pwm_auto_reg);
if (!(attr->index % 2)) {
reg &= 0xF;
reg |= (temp << 4) & 0xF0;
} else {
reg &= 0xF0;
reg |= temp & 0xF;
}
i2c_smbus_write_byte_data(client, pwm_auto_reg, reg);
mutex_unlock(&data->lock);
return count;
}
static ssize_t show_alarm(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adt7470_data *data = adt7470_update_device(dev);
if (data->alarm & attr->index)
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static DEVICE_ATTR(alarm_mask, S_IWUSR | S_IRUGO, show_alarm_mask,
set_alarm_mask);
static DEVICE_ATTR(num_temp_sensors, S_IWUSR | S_IRUGO, show_num_temp_sensors,
set_num_temp_sensors);
static DEVICE_ATTR(auto_update_interval, S_IWUSR | S_IRUGO,
show_auto_update_interval, set_auto_update_interval);
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 0);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 1);
static SENSOR_DEVICE_ATTR(temp3_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 2);
static SENSOR_DEVICE_ATTR(temp4_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 3);
static SENSOR_DEVICE_ATTR(temp5_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 4);
static SENSOR_DEVICE_ATTR(temp6_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 5);
static SENSOR_DEVICE_ATTR(temp7_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 6);
static SENSOR_DEVICE_ATTR(temp8_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 7);
static SENSOR_DEVICE_ATTR(temp9_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 8);
static SENSOR_DEVICE_ATTR(temp10_max, S_IWUSR | S_IRUGO, show_temp_max,
set_temp_max, 9);
static SENSOR_DEVICE_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 0);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 1);
static SENSOR_DEVICE_ATTR(temp3_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 2);
static SENSOR_DEVICE_ATTR(temp4_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 3);
static SENSOR_DEVICE_ATTR(temp5_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 4);
static SENSOR_DEVICE_ATTR(temp6_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 5);
static SENSOR_DEVICE_ATTR(temp7_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 6);
static SENSOR_DEVICE_ATTR(temp8_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 7);
static SENSOR_DEVICE_ATTR(temp9_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 8);
static SENSOR_DEVICE_ATTR(temp10_min, S_IWUSR | S_IRUGO, show_temp_min,
set_temp_min, 9);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp, NULL, 3);
static SENSOR_DEVICE_ATTR(temp5_input, S_IRUGO, show_temp, NULL, 4);
static SENSOR_DEVICE_ATTR(temp6_input, S_IRUGO, show_temp, NULL, 5);
static SENSOR_DEVICE_ATTR(temp7_input, S_IRUGO, show_temp, NULL, 6);
static SENSOR_DEVICE_ATTR(temp8_input, S_IRUGO, show_temp, NULL, 7);
static SENSOR_DEVICE_ATTR(temp9_input, S_IRUGO, show_temp, NULL, 8);
static SENSOR_DEVICE_ATTR(temp10_input, S_IRUGO, show_temp, NULL, 9);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R1T_ALARM);
static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R2T_ALARM);
static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R3T_ALARM);
static SENSOR_DEVICE_ATTR(temp4_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R4T_ALARM);
static SENSOR_DEVICE_ATTR(temp5_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R5T_ALARM);
static SENSOR_DEVICE_ATTR(temp6_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R6T_ALARM);
static SENSOR_DEVICE_ATTR(temp7_alarm, S_IRUGO, show_alarm, NULL,
ADT7470_R7T_ALARM);
static SENSOR_DEVICE_ATTR(temp8_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_R8T_ALARM));
static SENSOR_DEVICE_ATTR(temp9_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_R9T_ALARM));
static SENSOR_DEVICE_ATTR(temp10_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_R10T_ALARM));
static SENSOR_DEVICE_ATTR(fan1_max, S_IWUSR | S_IRUGO, show_fan_max,
set_fan_max, 0);
static SENSOR_DEVICE_ATTR(fan2_max, S_IWUSR | S_IRUGO, show_fan_max,
set_fan_max, 1);
static SENSOR_DEVICE_ATTR(fan3_max, S_IWUSR | S_IRUGO, show_fan_max,
set_fan_max, 2);
static SENSOR_DEVICE_ATTR(fan4_max, S_IWUSR | S_IRUGO, show_fan_max,
set_fan_max, 3);
static SENSOR_DEVICE_ATTR(fan1_min, S_IWUSR | S_IRUGO, show_fan_min,
set_fan_min, 0);
static SENSOR_DEVICE_ATTR(fan2_min, S_IWUSR | S_IRUGO, show_fan_min,
set_fan_min, 1);
static SENSOR_DEVICE_ATTR(fan3_min, S_IWUSR | S_IRUGO, show_fan_min,
set_fan_min, 2);
static SENSOR_DEVICE_ATTR(fan4_min, S_IWUSR | S_IRUGO, show_fan_min,
set_fan_min, 3);
static SENSOR_DEVICE_ATTR(fan1_input, S_IRUGO, show_fan, NULL, 0);
static SENSOR_DEVICE_ATTR(fan2_input, S_IRUGO, show_fan, NULL, 1);
static SENSOR_DEVICE_ATTR(fan3_input, S_IRUGO, show_fan, NULL, 2);
static SENSOR_DEVICE_ATTR(fan4_input, S_IRUGO, show_fan, NULL, 3);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_FAN1_ALARM));
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_FAN2_ALARM));
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_FAN3_ALARM));
static SENSOR_DEVICE_ATTR(fan4_alarm, S_IRUGO, show_alarm, NULL,
ALARM2(ADT7470_FAN4_ALARM));
static SENSOR_DEVICE_ATTR(force_pwm_max, S_IWUSR | S_IRUGO,
show_force_pwm_max, set_force_pwm_max, 0);
static SENSOR_DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 0);
static SENSOR_DEVICE_ATTR(pwm2, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 1);
static SENSOR_DEVICE_ATTR(pwm3, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 2);
static SENSOR_DEVICE_ATTR(pwm4, S_IWUSR | S_IRUGO, show_pwm, set_pwm, 3);
static DEVICE_ATTR(pwm1_freq, S_IWUSR | S_IRUGO, show_pwm_freq, set_pwm_freq);
static SENSOR_DEVICE_ATTR(pwm1_auto_point1_pwm, S_IWUSR | S_IRUGO,
show_pwm_min, set_pwm_min, 0);
static SENSOR_DEVICE_ATTR(pwm2_auto_point1_pwm, S_IWUSR | S_IRUGO,
show_pwm_min, set_pwm_min, 1);
static SENSOR_DEVICE_ATTR(pwm3_auto_point1_pwm, S_IWUSR | S_IRUGO,
show_pwm_min, set_pwm_min, 2);
static SENSOR_DEVICE_ATTR(pwm4_auto_point1_pwm, S_IWUSR | S_IRUGO,
show_pwm_min, set_pwm_min, 3);
static SENSOR_DEVICE_ATTR(pwm1_auto_point2_pwm, S_IWUSR | S_IRUGO,
show_pwm_max, set_pwm_max, 0);
static SENSOR_DEVICE_ATTR(pwm2_auto_point2_pwm, S_IWUSR | S_IRUGO,
show_pwm_max, set_pwm_max, 1);
static SENSOR_DEVICE_ATTR(pwm3_auto_point2_pwm, S_IWUSR | S_IRUGO,
show_pwm_max, set_pwm_max, 2);
static SENSOR_DEVICE_ATTR(pwm4_auto_point2_pwm, S_IWUSR | S_IRUGO,
show_pwm_max, set_pwm_max, 3);
static SENSOR_DEVICE_ATTR(pwm1_auto_point1_temp, S_IWUSR | S_IRUGO,
show_pwm_tmin, set_pwm_tmin, 0);
static SENSOR_DEVICE_ATTR(pwm2_auto_point1_temp, S_IWUSR | S_IRUGO,
show_pwm_tmin, set_pwm_tmin, 1);
static SENSOR_DEVICE_ATTR(pwm3_auto_point1_temp, S_IWUSR | S_IRUGO,
show_pwm_tmin, set_pwm_tmin, 2);
static SENSOR_DEVICE_ATTR(pwm4_auto_point1_temp, S_IWUSR | S_IRUGO,
show_pwm_tmin, set_pwm_tmin, 3);
static SENSOR_DEVICE_ATTR(pwm1_auto_point2_temp, S_IRUGO, show_pwm_tmax,
NULL, 0);
static SENSOR_DEVICE_ATTR(pwm2_auto_point2_temp, S_IRUGO, show_pwm_tmax,
NULL, 1);
static SENSOR_DEVICE_ATTR(pwm3_auto_point2_temp, S_IRUGO, show_pwm_tmax,
NULL, 2);
static SENSOR_DEVICE_ATTR(pwm4_auto_point2_temp, S_IRUGO, show_pwm_tmax,
NULL, 3);
static SENSOR_DEVICE_ATTR(pwm1_enable, S_IWUSR | S_IRUGO, show_pwm_auto,
set_pwm_auto, 0);
static SENSOR_DEVICE_ATTR(pwm2_enable, S_IWUSR | S_IRUGO, show_pwm_auto,
set_pwm_auto, 1);
static SENSOR_DEVICE_ATTR(pwm3_enable, S_IWUSR | S_IRUGO, show_pwm_auto,
set_pwm_auto, 2);
static SENSOR_DEVICE_ATTR(pwm4_enable, S_IWUSR | S_IRUGO, show_pwm_auto,
set_pwm_auto, 3);
static SENSOR_DEVICE_ATTR(pwm1_auto_channels_temp, S_IWUSR | S_IRUGO,
show_pwm_auto_temp, set_pwm_auto_temp, 0);
static SENSOR_DEVICE_ATTR(pwm2_auto_channels_temp, S_IWUSR | S_IRUGO,
show_pwm_auto_temp, set_pwm_auto_temp, 1);
static SENSOR_DEVICE_ATTR(pwm3_auto_channels_temp, S_IWUSR | S_IRUGO,
show_pwm_auto_temp, set_pwm_auto_temp, 2);
static SENSOR_DEVICE_ATTR(pwm4_auto_channels_temp, S_IWUSR | S_IRUGO,
show_pwm_auto_temp, set_pwm_auto_temp, 3);
static struct attribute *adt7470_attrs[] = {
&dev_attr_alarm_mask.attr,
&dev_attr_num_temp_sensors.attr,
&dev_attr_auto_update_interval.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp4_max.dev_attr.attr,
&sensor_dev_attr_temp5_max.dev_attr.attr,
&sensor_dev_attr_temp6_max.dev_attr.attr,
&sensor_dev_attr_temp7_max.dev_attr.attr,
&sensor_dev_attr_temp8_max.dev_attr.attr,
&sensor_dev_attr_temp9_max.dev_attr.attr,
&sensor_dev_attr_temp10_max.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp4_min.dev_attr.attr,
&sensor_dev_attr_temp5_min.dev_attr.attr,
&sensor_dev_attr_temp6_min.dev_attr.attr,
&sensor_dev_attr_temp7_min.dev_attr.attr,
&sensor_dev_attr_temp8_min.dev_attr.attr,
&sensor_dev_attr_temp9_min.dev_attr.attr,
&sensor_dev_attr_temp10_min.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp4_input.dev_attr.attr,
&sensor_dev_attr_temp5_input.dev_attr.attr,
&sensor_dev_attr_temp6_input.dev_attr.attr,
&sensor_dev_attr_temp7_input.dev_attr.attr,
&sensor_dev_attr_temp8_input.dev_attr.attr,
&sensor_dev_attr_temp9_input.dev_attr.attr,
&sensor_dev_attr_temp10_input.dev_attr.attr,
&sensor_dev_attr_temp1_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_alarm.dev_attr.attr,
&sensor_dev_attr_temp4_alarm.dev_attr.attr,
&sensor_dev_attr_temp5_alarm.dev_attr.attr,
&sensor_dev_attr_temp6_alarm.dev_attr.attr,
&sensor_dev_attr_temp7_alarm.dev_attr.attr,
&sensor_dev_attr_temp8_alarm.dev_attr.attr,
&sensor_dev_attr_temp9_alarm.dev_attr.attr,
&sensor_dev_attr_temp10_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_max.dev_attr.attr,
&sensor_dev_attr_fan2_max.dev_attr.attr,
&sensor_dev_attr_fan3_max.dev_attr.attr,
&sensor_dev_attr_fan4_max.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan3_min.dev_attr.attr,
&sensor_dev_attr_fan4_min.dev_attr.attr,
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan3_input.dev_attr.attr,
&sensor_dev_attr_fan4_input.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan3_alarm.dev_attr.attr,
&sensor_dev_attr_fan4_alarm.dev_attr.attr,
&sensor_dev_attr_force_pwm_max.dev_attr.attr,
&sensor_dev_attr_pwm1.dev_attr.attr,
&dev_attr_pwm1_freq.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
&sensor_dev_attr_pwm3.dev_attr.attr,
&sensor_dev_attr_pwm4.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm4_auto_point1_pwm.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point2_pwm.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point2_pwm.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point2_pwm.dev_attr.attr,
&sensor_dev_attr_pwm4_auto_point2_pwm.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_pwm4_auto_point1_temp.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_pwm4_auto_point2_temp.dev_attr.attr,
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
&sensor_dev_attr_pwm4_enable.dev_attr.attr,
&sensor_dev_attr_pwm1_auto_channels_temp.dev_attr.attr,
&sensor_dev_attr_pwm2_auto_channels_temp.dev_attr.attr,
&sensor_dev_attr_pwm3_auto_channels_temp.dev_attr.attr,
&sensor_dev_attr_pwm4_auto_channels_temp.dev_attr.attr,
NULL
};
ATTRIBUTE_GROUPS(adt7470);
/* Return 0 if detection is successful, -ENODEV otherwise */
static int adt7470_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int vendor, device, revision;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
vendor = i2c_smbus_read_byte_data(client, ADT7470_REG_VENDOR);
if (vendor != ADT7470_VENDOR)
return -ENODEV;
device = i2c_smbus_read_byte_data(client, ADT7470_REG_DEVICE);
if (device != ADT7470_DEVICE)
return -ENODEV;
revision = i2c_smbus_read_byte_data(client, ADT7470_REG_REVISION);
if (revision != ADT7470_REVISION)
return -ENODEV;
strlcpy(info->type, "adt7470", I2C_NAME_SIZE);
return 0;
}
static void adt7470_init_client(struct i2c_client *client)
{
int reg = i2c_smbus_read_byte_data(client, ADT7470_REG_CFG);
if (reg < 0) {
dev_err(&client->dev, "cannot read configuration register\n");
} else {
/* start monitoring (and do a self-test) */
i2c_smbus_write_byte_data(client, ADT7470_REG_CFG, reg | 3);
}
}
static int adt7470_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct device *dev = &client->dev;
struct adt7470_data *data;
struct device *hwmon_dev;
data = devm_kzalloc(dev, sizeof(struct adt7470_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->num_temp_sensors = -1;
data->auto_update_interval = AUTO_UPDATE_INTERVAL;
i2c_set_clientdata(client, data);
data->client = client;
mutex_init(&data->lock);
dev_info(&client->dev, "%s chip found\n", client->name);
/* Initialize the ADT7470 chip */
adt7470_init_client(client);
/* Register sysfs hooks */
hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name,
data,
adt7470_groups);
if (IS_ERR(hwmon_dev))
return PTR_ERR(hwmon_dev);
data->auto_update = kthread_run(adt7470_update_thread, client, "%s",
dev_name(hwmon_dev));
if (IS_ERR(data->auto_update)) {
return PTR_ERR(data->auto_update);
}
return 0;
}
static int adt7470_remove(struct i2c_client *client)
{
struct adt7470_data *data = i2c_get_clientdata(client);
kthread_stop(data->auto_update);
return 0;
}
static const struct i2c_device_id adt7470_id[] = {
{ "adt7470", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adt7470_id);
static struct i2c_driver adt7470_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "adt7470",
},
.probe = adt7470_probe,
.remove = adt7470_remove,
.id_table = adt7470_id,
.detect = adt7470_detect,
.address_list = normal_i2c,
};
module_i2c_driver(adt7470_driver);
MODULE_AUTHOR("Darrick J. Wong <darrick.wong@oracle.com>");
MODULE_DESCRIPTION("ADT7470 driver");
MODULE_LICENSE("GPL");
|
/*
Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <ndb_global.h>
#include "InitConfigFileParser.hpp"
#include "ConfigInfo.hpp"
#include "Config.hpp"
#include <portlib/NdbDir.hpp>
#define CHECK(x) \
if (!(x)) {\
fprintf(stderr, "testConfig: '"#x"' failed on line %d\n", __LINE__); \
exit(1); \
}
static const ConfigInfo g_info;
/*
Create a small config.ini with the given parameter and run
it through InitConfigFileParser
*/
bool
check_param(const ConfigInfo::ParamInfo & param)
{
FILE* config_file= tmpfile();
CHECK(config_file);
const char* section= g_info.nameToAlias(param._section);
if (section == NULL)
section= param._section;
if (param._type == ConfigInfo::CI_SECTION)
{
fclose(config_file);
return true;
}
if(param._default == MANDATORY)
{
// Mandatory parameter
fclose(config_file);
return true;
}
else
{
fprintf(config_file, "[%s]\n", section);
fprintf(config_file, "%s=%s\n", param._fname,
param._default ? param._default : "some value");
}
// Fill in lines needed for a minimal config
if (strcmp(section, "NDBD") != 0)
fprintf(config_file, "[ndbd]\n");
if (strcmp(param._fname, "NoOfReplicas") != 0)
fprintf(config_file, "NoOfReplicas=1\n");
if (strcmp(section, "NDB_MGMD") != 0)
fprintf(config_file, "[ndb_mgmd]\n");
if (strcmp(param._fname, "Hostname") != 0)
fprintf(config_file, "HostName=localhost\n");
if (strcmp(section, "MYSQLD") != 0)
fprintf(config_file, "[mysqld]\n");
rewind(config_file);
// Run the config file through InitConfigFileParser
InitConfigFileParser parser;
Config* conf = parser.parseConfig(config_file);
fclose(config_file);
if (conf == NULL)
return false;
delete conf;
return true;
}
bool
check_params(void)
{
bool ok= true;
for (int j=0; j<g_info.m_NoOfParams; j++) {
const ConfigInfo::ParamInfo & param= g_info.m_ParamInfo[j];
printf("Checking %s...\n", param._fname);
if (!check_param(param))
{
ok= false;
}
}
return true; // Ignore "ok" for now, just checking it doesn't crash
}
Config*
create_config(const char* first, ...)
{
va_list args;
FILE* config_file= tmpfile();
CHECK(config_file);
va_start(args, first);
const char* str= first;
do
fprintf(config_file, "%s\n", str);
while((str= va_arg(args, const char*)) != NULL);
va_end(args);
#if 0
rewind(config_file);
char buf[100];
while(fgets(buf, sizeof(buf), config_file))
ndbout_c(buf);
#endif
rewind(config_file);
InitConfigFileParser parser;
Config* conf = parser.parseConfig(config_file);
fclose(config_file);
return conf;
}
// Global variable for my_getopt
extern "C" const char* my_defaults_file;
static
unsigned
ndb_procid()
{
#ifdef _WIN32
return (unsigned)GetCurrentProcessId();
#else
return (unsigned)getpid();
#endif
}
Config*
create_mycnf(const char* first, ...)
{
va_list args;
NdbDir::Temp tempdir;
BaseString mycnf_file;
mycnf_file.assfmt("%s%stest_my.%u.cnf",
tempdir.path(), DIR_SEPARATOR, ndb_procid());
FILE* config_file= fopen(mycnf_file.c_str(), "w+");
CHECK(config_file);
va_start(args, first);
const char* str= first;
do
fprintf(config_file, "%s\n", str);
while((str= va_arg(args, const char*)) != NULL);
va_end(args);
#if 0
rewind(config_file);
char buf[100];
while(fgets(buf, sizeof(buf), config_file))
printf("%s", buf);
#endif
fflush(config_file);
rewind(config_file);
// Trick handle_options to read from the temp file
const char* save_defaults_file = my_defaults_file;
my_defaults_file = mycnf_file.c_str();
InitConfigFileParser parser;
Config* conf = parser.parse_mycnf();
// Restore the global variable
my_defaults_file = save_defaults_file;
fclose(config_file);
// Remove file
unlink(mycnf_file.c_str());
return conf;
}
void
diff_config(void)
{
Config* c1=
create_config("[ndbd]", "NoOfReplicas=1",
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", NULL);
CHECK(c1);
Config* c2=
create_config("[ndbd]", "NoOfReplicas=1",
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", "[mysqld]", NULL);
CHECK(c2);
CHECK(c1->equal(c1));
CHECK(!c1->equal(c2));
CHECK(!c2->equal(c1));
CHECK(!c2->illegal_change(c1));
CHECK(!c1->illegal_change(c2));
ndbout_c("==================");
ndbout_c("c1->print_diff(c2)");
c1->print_diff(c2);
ndbout_c("==================");
ndbout_c("c2->print_diff(c1)");
c2->print_diff(c1);
ndbout_c("==================");
{
// BUG#47036 Reload of config shows only diff of last changed parameter
// - check that diff of c1 and c3 shows 2 diffs
Config* c1_bug47306=
create_config("[ndbd]", "NoOfReplicas=1",
"DataMemory=100M", "IndexMemory=100M",
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", NULL);
CHECK(c1_bug47306);
ndbout_c("c1->print_diff(c1_bug47306)");
c1->print_diff(c1_bug47306);
Properties diff_list;
unsigned exclude[]= {CFG_SECTION_SYSTEM, 0};
c1->diff(c1_bug47306, diff_list, exclude);
// open section for ndbd with NodeId=1
const Properties* section;
CHECK(diff_list.get("NodeId=1", §ion));
// Count the number of diffs for ndbd 1
const char* name;
int count= 0, found = 0;
Properties::Iterator prop_it(section);
while ((name = prop_it.next())){
if (strcmp(name, "IndexMemory") == 0)
found++;
if (strcmp(name, "DataMemory") == 0)
found++;
count++;
}
CHECK(found == 2 &&
count == found + 2); // Overhead == 2
ndbout_c("==================");
delete c1_bug47306;
}
delete c1;
delete c2;
}
void
print_restart_info(void)
{
Vector<const char*> initial_node;
Vector<const char*> system;
Vector<const char*> initial_system;
for (int i = 0; i < g_info.m_NoOfParams; i++) {
const ConfigInfo::ParamInfo & param = g_info.m_ParamInfo[i];
if ((param._flags & ConfigInfo::CI_RESTART_INITIAL) &&
(param._flags & ConfigInfo::CI_RESTART_SYSTEM))
initial_system.push_back(param._fname);
else if (param._flags & (ConfigInfo::CI_RESTART_SYSTEM))
system.push_back(param._fname);
else if (param._flags & (ConfigInfo::CI_RESTART_INITIAL))
initial_node.push_back(param._fname);
}
fprintf(stderr, "*** initial node restart ***\n");
for (size_t i = 0; i < initial_node.size(); i++) {
fprintf(stderr, "%s\n", initial_node[i]);
}
fprintf(stderr, "\n");
fprintf(stderr, "*** system restart ***\n");
for (size_t i = 0; i < system.size(); i++) {
fprintf(stderr, "%s\n", system[i]);
}
fprintf(stderr, "\n");
fprintf(stderr, "*** initial system restart ***\n");
for (size_t i = 0; i < initial_system.size(); i++) {
fprintf(stderr, "%s\n", initial_system[i]);
}
fprintf(stderr, "\n");
}
static void
checksum_config(void)
{
Config* c1=
create_config("[ndbd]", "NoOfReplicas=1",
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", NULL);
CHECK(c1);
Config* c2=
create_config("[ndbd]", "NoOfReplicas=1",
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", "[mysqld]", NULL);
CHECK(c2);
ndbout_c("== checksum tests ==");
Uint32 c1_check = c1->checksum();
Uint32 c2_check = c2->checksum();
ndbout_c("c1->checksum(): 0x%x", c1_check);
ndbout_c("c2->checksum(): 0x%x", c2_check);
// Different config should not have same checksum
CHECK(c1_check != c2_check);
// Same config should have same checksum
CHECK(c1_check == c1->checksum());
// Copied config should have same checksum
Config c1_copy(c1);
CHECK(c1_check == c1_copy.checksum());
ndbout_c("==================");
delete c1;
delete c2;
}
static void
test_param_values(void)
{
struct test {
const char* param;
bool result;
} tests [] = {
// CI_ENUM
{ "Arbitration=Disabled", true },
{ "Arbitration=Invalid", false },
{ "Arbitration=", false },
// CI_BITMASK
{ "LockExecuteThreadToCPU=0", true },
{ "LockExecuteThreadToCPU=1", true },
{ "LockExecuteThreadToCPU=65535", true },
{ "LockExecuteThreadToCPU=0-65535", true },
{ "LockExecuteThreadToCPU=0-1,65534-65535", true },
{ "LockExecuteThreadToCPU=17-256", true },
{ "LockExecuteThreadToCPU=1-2,36-37,17-256,11-12,1-2", true },
{ "LockExecuteThreadToCPU=", false }, // Zero size value not allowed
{ "LockExecuteThreadToCPU=1-", false },
{ "LockExecuteThreadToCPU=1--", false },
{ "LockExecuteThreadToCPU=1-2,34-", false },
{ "LockExecuteThreadToCPU=x", false },
{ "LockExecuteThreadToCPU=x-1", false },
{ "LockExecuteThreadToCPU=x-x", false },
{ 0, false }
};
for (struct test* t = tests; t->param; t++)
{
ndbout_c("testing %s", t->param);
{
const Config* c =
create_config("[ndbd]", "NoOfReplicas=1",
t->param,
"[ndb_mgmd]", "HostName=localhost",
"[mysqld]", NULL);
if (t->result)
{
CHECK(c);
delete c;
}
else
{
CHECK(c == NULL);
}
}
{
const Config* c =
create_mycnf("[cluster_config]",
"ndb_mgmd=localhost",
"ndbd=localhost,localhost",
"ndbapi=localhost",
"NoOfReplicas=1",
t->param,
NULL);
if (t->result)
{
CHECK(c);
delete c;
}
else
{
CHECK(c == NULL);
}
}
}
}
static void
test_hostname_mycnf(void)
{
// Check the special rule for my.cnf that says
// the two hostname specs must match
{
// Valid config, ndbd=localhost, matches HostName=localhost
const Config* c =
create_mycnf("[cluster_config]",
"ndb_mgmd=localhost",
"ndbd=localhost,localhost",
"ndbapi=localhost",
"NoOfReplicas=1",
"[cluster_config.ndbd.1]",
"HostName=localhost",
NULL);
CHECK(c);
delete c;
}
{
// Invalid config, ndbd=localhost, does not match HostName=host1
const Config* c =
create_mycnf("[cluster_config]",
"ndb_mgmd=localhost",
"ndbd=localhost,localhost",
"ndbapi=localhost",
"NoOfReplicas=1",
"[cluster_config.ndbd.1]",
"HostName=host1",
NULL);
CHECK(c == NULL);
}
}
#include <NdbTap.hpp>
#include <EventLogger.hpp>
extern EventLogger* g_eventLogger;
TAPTEST(MgmConfig)
{
ndb_init();
g_eventLogger->createConsoleHandler();
diff_config();
CHECK(check_params());
checksum_config();
test_param_values();
test_hostname_mycnf();
#if 0
print_restart_info();
#endif
ndb_end(0);
return 1; // OK
}
|
/**
* Akeeba Strapper
* A handy distribution of namespaced jQuery, jQuery UI and Twitter
* Bootstrapper for use with Akeeba components.
*
* This file includes only Joomla! 3.2-specific style overrides
*/
/*
* Bootstrap (namespaced)
*/
div.akeeba-bootstrap {
/**
* If your template already includes Bootstrap CSS styling please comment
* out this line and uncomment the include below.
*/
/**
* If your template already includes Bootstrap CSS styling please uncomment
* out this line and comment out the include above.
*/
/**
* Akeeba Strapper
* A handy distribution of namespaced jQuery, jQuery UI and Twitter
* Bootstrapper for use with Akeeba components.
*
* This file includes the minimal Bootstrap markup only for Joomla! 3.2 templates which include Bootstrap CSS styling
*/
/* White icons with optional class, or on hover/active states of certain elements */
}
div.akeeba-bootstrap [class^="icon-"],
div.akeeba-bootstrap [class*=" icon-"] {
display: inline-block;
width: 14px;
height: 14px;
*margin-right: .3em;
line-height: 14px;
vertical-align: text-top;
background-image: url("../img/glyphicons-halflings.png");
background-position: 14px 14px;
background-repeat: no-repeat;
margin-top: 1px;
}
div.akeeba-bootstrap .icon-white,
div.akeeba-bootstrap .nav-pills > .active > a > [class^="icon-"],
div.akeeba-bootstrap .nav-pills > .active > a > [class*=" icon-"],
div.akeeba-bootstrap .nav-list > .active > a > [class^="icon-"],
div.akeeba-bootstrap .nav-list > .active > a > [class*=" icon-"],
div.akeeba-bootstrap .navbar-inverse .nav > .active > a > [class^="icon-"],
div.akeeba-bootstrap .navbar-inverse .nav > .active > a > [class*=" icon-"],
div.akeeba-bootstrap .dropdown-menu > li > a:hover > [class^="icon-"],
div.akeeba-bootstrap .dropdown-menu > li > a:focus > [class^="icon-"],
div.akeeba-bootstrap .dropdown-menu > li > a:hover > [class*=" icon-"],
div.akeeba-bootstrap .dropdown-menu > li > a:focus > [class*=" icon-"],
div.akeeba-bootstrap .dropdown-menu > .active > a > [class^="icon-"],
div.akeeba-bootstrap .dropdown-menu > .active > a > [class*=" icon-"],
div.akeeba-bootstrap .dropdown-submenu:hover > a > [class^="icon-"],
div.akeeba-bootstrap .dropdown-submenu:focus > a > [class^="icon-"],
div.akeeba-bootstrap .dropdown-submenu:hover > a > [class*=" icon-"],
div.akeeba-bootstrap .dropdown-submenu:focus > a > [class*=" icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
div.akeeba-bootstrap .icon-glass {
background-position: 0 0;
}
div.akeeba-bootstrap .icon-film {
background-position: -192px 0;
}
div.akeeba-bootstrap .icon-th-large {
background-position: -216px 0;
}
div.akeeba-bootstrap .icon-th {
background-position: -240px 0;
}
div.akeeba-bootstrap .icon-th-list {
background-position: -264px 0;
}
div.akeeba-bootstrap .icon-off {
background-position: -384px 0;
}
div.akeeba-bootstrap .icon-signal {
background-position: -408px 0;
}
div.akeeba-bootstrap .icon-time {
background-position: -48px -24px;
}
div.akeeba-bootstrap .icon-road {
background-position: -72px -24px;
}
div.akeeba-bootstrap .icon-download-alt {
background-position: -96px -24px;
}
div.akeeba-bootstrap .icon-inbox {
background-position: -168px -24px;
}
div.akeeba-bootstrap .icon-repeat {
background-position: -216px -24px;
}
div.akeeba-bootstrap .icon-list-alt {
background-position: -264px -24px;
}
div.akeeba-bootstrap .icon-headphones {
background-position: -336px -24px;
}
div.akeeba-bootstrap .icon-volume-off {
background-position: -360px -24px;
}
div.akeeba-bootstrap .icon-volume-down {
background-position: -384px -24px;
}
div.akeeba-bootstrap .icon-volume-up {
background-position: -408px -24px;
}
div.akeeba-bootstrap .icon-qrcode {
background-position: -432px -24px;
}
div.akeeba-bootstrap .icon-barcode {
background-position: -456px -24px;
}
div.akeeba-bootstrap .icon-font {
background-position: -144px -48px;
}
div.akeeba-bootstrap .icon-bold {
background-position: -167px -48px;
}
div.akeeba-bootstrap .icon-italic {
background-position: -192px -48px;
}
div.akeeba-bootstrap .icon-text-height {
background-position: -216px -48px;
}
div.akeeba-bootstrap .icon-text-width {
background-position: -240px -48px;
}
div.akeeba-bootstrap .icon-align-left {
background-position: -264px -48px;
}
div.akeeba-bootstrap .icon-align-center {
background-position: -288px -48px;
}
div.akeeba-bootstrap .icon-align-right {
background-position: -312px -48px;
}
div.akeeba-bootstrap .icon-align-justify {
background-position: -336px -48px;
}
div.akeeba-bootstrap .icon-indent-left {
background-position: -384px -48px;
}
div.akeeba-bootstrap .icon-indent-right {
background-position: -408px -48px;
}
div.akeeba-bootstrap .icon-facetime-video {
background-position: -432px -48px;
}
div.akeeba-bootstrap .icon-map-marker {
background-position: -24px -72px;
}
div.akeeba-bootstrap .icon-adjust {
background-position: -48px -72px;
}
div.akeeba-bootstrap .icon-tint {
background-position: -72px -72px;
}
div.akeeba-bootstrap .icon-check {
background-position: -144px -72px;
}
div.akeeba-bootstrap .icon-step-backward {
background-position: -192px -72px;
}
div.akeeba-bootstrap .icon-fast-backward {
background-position: -216px -72px;
}
div.akeeba-bootstrap .icon-fast-forward {
background-position: -360px -72px;
}
div.akeeba-bootstrap .icon-step-forward {
background-position: -384px -72px;
}
div.akeeba-bootstrap .icon-eject {
background-position: -408px -72px;
}
div.akeeba-bootstrap .icon-plus-sign {
background-position: 0 -96px;
}
div.akeeba-bootstrap .icon-remove-sign {
background-position: -48px -96px;
}
div.akeeba-bootstrap .icon-ok-sign {
background-position: -72px -96px;
}
div.akeeba-bootstrap .icon-info-sign {
background-position: -120px -96px;
}
div.akeeba-bootstrap .icon-screenshot {
background-position: -144px -96px;
}
div.akeeba-bootstrap .icon-remove-circle {
background-position: -168px -96px;
}
div.akeeba-bootstrap .icon-ok-circle {
background-position: -192px -96px;
}
div.akeeba-bootstrap .icon-arrow-up {
background-position: -289px -96px;
}
div.akeeba-bootstrap .icon-arrow-down {
background-position: -312px -96px;
}
div.akeeba-bootstrap .icon-resize-full {
background-position: -360px -96px;
}
div.akeeba-bootstrap .icon-resize-small {
background-position: -384px -96px;
}
div.akeeba-bootstrap .icon-exclamation-sign {
background-position: 0 -120px;
}
div.akeeba-bootstrap .icon-gift {
background-position: -24px -120px;
}
div.akeeba-bootstrap .icon-leaf {
background-position: -48px -120px;
}
div.akeeba-bootstrap .icon-fire {
background-position: -72px -120px;
}
div.akeeba-bootstrap .icon-warning-sign {
background-position: -144px -120px;
}
div.akeeba-bootstrap .icon-plane {
background-position: -168px -120px;
}
div.akeeba-bootstrap .icon-random {
background-position: -216px -120px;
width: 16px;
}
div.akeeba-bootstrap .icon-magnet {
background-position: -264px -120px;
}
div.akeeba-bootstrap .icon-retweet {
background-position: -336px -120px;
}
div.akeeba-bootstrap .icon-shopping-cart {
background-position: -360px -120px;
}
div.akeeba-bootstrap .icon-resize-vertical {
background-position: -432px -119px;
}
div.akeeba-bootstrap .icon-resize-horizontal {
background-position: -456px -118px;
}
div.akeeba-bootstrap .icon-hdd {
background-position: 0 -144px;
}
div.akeeba-bootstrap .icon-bullhorn {
background-position: -24px -144px;
}
div.akeeba-bootstrap .icon-bell {
background-position: -48px -144px;
}
div.akeeba-bootstrap .icon-certificate {
background-position: -72px -144px;
}
div.akeeba-bootstrap .icon-hand-right {
background-position: -144px -144px;
}
div.akeeba-bootstrap .icon-hand-left {
background-position: -168px -144px;
}
div.akeeba-bootstrap .icon-hand-up {
background-position: -192px -144px;
}
div.akeeba-bootstrap .icon-hand-down {
background-position: -216px -144px;
}
div.akeeba-bootstrap .icon-circle-arrow-right {
background-position: -240px -144px;
}
div.akeeba-bootstrap .icon-circle-arrow-left {
background-position: -264px -144px;
}
div.akeeba-bootstrap .icon-circle-arrow-up {
background-position: -288px -144px;
}
div.akeeba-bootstrap .icon-circle-arrow-down {
background-position: -312px -144px;
}
div.akeeba-bootstrap .icon-globe {
background-position: -336px -144px;
}
div.akeeba-bootstrap .icon-tasks {
background-position: -384px -144px;
}
div.akeeba-bootstrap .icon-fullscreen {
background-position: -456px -144px;
}
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
line-height: 0;
}
.clearfix:after {
clear: both;
}
.hide-text {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.input-block-level {
display: block;
width: 100%;
min-height: 30px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1010;
display: none;
max-width: 276px;
padding: 1px;
text-align: left;
background-color: #ffffff;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
white-space: normal;
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
margin: 0;
padding: 8px 14px;
font-size: 14px;
font-weight: normal;
line-height: 18px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
-webkit-border-radius: 5px 5px 0 0;
-moz-border-radius: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
}
.popover-title:empty {
display: none;
}
.popover-content {
padding: 9px 14px;
}
.popover .arrow,
.popover .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover .arrow {
border-width: 11px;
}
.popover .arrow:after {
border-width: 10px;
content: "";
}
.popover.top .arrow {
left: 50%;
margin-left: -11px;
border-bottom-width: 0;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, 0.25);
bottom: -11px;
}
.popover.top .arrow:after {
bottom: 1px;
margin-left: -10px;
border-bottom-width: 0;
border-top-color: #ffffff;
}
.popover.right .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-left-width: 0;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, 0.25);
}
.popover.right .arrow:after {
left: 1px;
bottom: -10px;
border-left-width: 0;
border-right-color: #ffffff;
}
.popover.bottom .arrow {
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, 0.25);
top: -11px;
}
.popover.bottom .arrow:after {
top: 1px;
margin-left: -10px;
border-top-width: 0;
border-bottom-color: #ffffff;
}
.popover.left .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, 0.25);
}
.popover.left .arrow:after {
right: 1px;
border-right-width: 0;
border-left-color: #ffffff;
bottom: -10px;
}
/*
* Akeeba Strapper overrides
*/
/*!
* Akeeba Strapper
* A handy distribution of namespaced jQuery, jQuery UI and Twitter
* Bootstrapper for use with Akeeba components.
*
* This file defines Akeeba Strapper specific styling overrides
*/
div.akeeba-bootstrap {
font-size: 10pt;
background: transparent;
}
div.akeeba-bootstrap .alert {
background-image: none;
}
div.akeeba-bootstrap form.form-horizontal-wide label.control-label {
width: 300px;
}
div.akeeba-bootstrap form.form-horizontal-wide div.controls {
margin-left: 320px;
}
div.akeeba-bootstrap form.form-horizontal-wide textarea {
width: 450px;
}
div.akeeba-bootstrap td.order {
width: 12px;
}
div.akeeba-bootstrap td.order span {
line-height: 16px;
height: 16px;
margin: 0;
padding: 0;
}
div.akeeba-bootstrap td.order a.jgrid span.state {
background-repeat: no-repeat;
height: 12px;
margin-bottom: 2px;
}
div.akeeba-bootstrap td.order a.jgrid span.state span.text {
line-height: 16px;
}
div.akeeba-bootstrap td.order input.text-area-order {
margin-bottom: 0;
width: 20px;
}
div.akeeba-bootstrap td.order .sortable-handler {
display: block;
float: left;
margin: 1px 0 0 0;
padding: 5px 5px;
}
div.akeeba-bootstrap td.order .order-enabled {
width: 60px;
}
div.akeeba-bootstrap td.order .order-disabled .sortable-handler {
margin: 0;
padding: 0;
}
div.akeeba-bootstrap th a.save-order {
height: 19px;
}
div.akeeba-bootstrap div.ak_clr_left {
clear: left;
}
div.akeeba-bootstrap div.ak_clr {
clear: both;
}
div.akeeba-bootstrap div.icon a.modal {
position: relative;
top: inherit;
left: inherit;
z-index: inherit;
margin: 0 !important;
box-shadow: none;
}
div.akeeba-bootstrap div [class^="icon-wrapper"] {
display: inline;
}
#akeeba-bootstrap:not(.joomla-version-25) input[name="cid[]"] {
margin: -3px 0 0 0;
}
div.icon-wrapper {
display: inline;
}
/**
* Akeeba Live Update button styling
*/
span.liveupdate-icon-notsupported {
color: #555555;
}
span.liveupdate-icon-crashed {
color: #555555;
}
span.liveupdate-icon-updates {
font-weight: bold;
color: #9d261d;
font-size: 0.87em;
}
span.liveupdate-icon-noupdates {
color: #46a546;
}
/**
* Akeeba Strapper
* A handy distribution of namespaced jQuery, jQuery UI and Twitter
* Bootstrapper for use with Akeeba components.
*
* This file defines Akeeba Strapper specific styling overrides
*/
.akeeba-bootstrap .cpanel div.icon,
.akeeba-bootstrap #cpanel div.icon {
text-align: center;
margin-right: 15px;
float: left;
margin-bottom: 15px;
font-size: 0.9em;
}
.akeeba-bootstrap .cpanel div.icon a,
.akeeba-bootstrap #cpanel div.icon a {
padding: 7px 5px 5px;
background-color: white;
background-position: -30px;
display: block;
float: left;
height: 97px;
width: 108px;
color: #565656;
vertical-align: middle;
text-decoration: none;
border: 1px solid #CCC;
border-radius: 5px;
transition-property: none;
box-shadow: inset -5px -5px 10px rgba(0, 0, 0, 0.1), inset 5px 5px 10px rgba(0, 0, 0, 0.05);
}
.akeeba-bootstrap .cpanel div.icon a:hover,
.akeeba-bootstrap #cpanel div.icon a:hover,
.akeeba-bootstrap .cpanel div.icon a:focus,
.akeeba-bootstrap #cpanel div.icon a:focus,
.akeeba-bootstrap .cpanel div.icon a:active,
.akeeba-bootstrap #cpanel div.icon a:active {
background-position: 0;
-webkit-border-bottom-left-radius: inherit;
-moz-border-radius-bottomleft: inherit;
border-bottom-left-radius: inherit;
box-shadow: inset 5px 5px 10px rgba(0, 0, 0, 0.1), inset -5px -5px 10px rgba(0, 0, 0, 0.05);
position: relative;
z-index: 10;
}
.akeeba-bootstrap .cpanel div.icon span,
.akeeba-bootstrap #cpanel div.icon span {
display: block;
text-align: center;
}
.akeeba-bootstrap div#toolbar div#toolbar-back button.btn span.icon-back::before {
content: "";
}
.akeeba-bootstrap .icon-downarrow::before,
.akeeba-bootstrap .akeeba-bootstrap .icon-arrow-down::before {
content: "";
}
.akeeba-bootstrap .icon-uparrow::before,
.akeeba-bootstrap .akeeba-bootstrap .icon-arrow-up::before {
content: "";
}
.akeeba-bootstrap label.radio {
display: inline-block;
}
.akeeba-bootstrap div.controls > div.controls {
margin: 0;
}
|
# Makefile for the Linux device tree
obj-y := component.o core.o bus.o dd.o syscore.o \
driver.o class.o platform.o \
cpu.o firmware.o init.o map.o devres.o \
attribute_container.o transport_class.o \
topology.o container.o
obj-$(CONFIG_DEVTMPFS) += devtmpfs.o
obj-$(CONFIG_DMA_CMA) += dma-contiguous.o
obj-y += power/
obj-$(CONFIG_HAS_DMA) += dma-mapping.o
obj-$(CONFIG_HAVE_GENERIC_DMA_COHERENT) += dma-coherent.o
obj-$(CONFIG_ISA) += isa.o
obj-$(CONFIG_FW_LOADER) += firmware_class.o
obj-$(CONFIG_NUMA) += node.o
obj-$(CONFIG_MEMORY_HOTPLUG_SPARSE) += memory.o
ifeq ($(CONFIG_SYSFS),y)
obj-$(CONFIG_MODULES) += module.o
endif
obj-$(CONFIG_SYS_HYPERVISOR) += hypervisor.o
obj-$(CONFIG_REGMAP) += regmap/
obj-$(CONFIG_SOC_BUS) += soc.o
obj-$(CONFIG_PINCTRL) += pinctrl.o
ccflags-$(CONFIG_DEBUG_DRIVER) := -DDEBUG
|
/*
* Kernel-based Virtual Machine -- Performance Monitoring Unit support
*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@redhat.com>
* Gleb Natapov <gleb@redhat.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <linux/types.h>
#include <linux/kvm_host.h>
#include <linux/perf_event.h>
#include "x86.h"
#include "cpuid.h"
#include "lapic.h"
static struct kvm_arch_event_perf_mapping {
u8 eventsel;
u8 unit_mask;
unsigned event_type;
bool inexact;
} arch_events[] = {
/* Index must match CPUID 0x0A.EBX bit vector */
[0] = { 0x3c, 0x00, PERF_COUNT_HW_CPU_CYCLES },
[1] = { 0xc0, 0x00, PERF_COUNT_HW_INSTRUCTIONS },
[2] = { 0x3c, 0x01, PERF_COUNT_HW_BUS_CYCLES },
[3] = { 0x2e, 0x4f, PERF_COUNT_HW_CACHE_REFERENCES },
[4] = { 0x2e, 0x41, PERF_COUNT_HW_CACHE_MISSES },
[5] = { 0xc4, 0x00, PERF_COUNT_HW_BRANCH_INSTRUCTIONS },
[6] = { 0xc5, 0x00, PERF_COUNT_HW_BRANCH_MISSES },
[7] = { 0x00, 0x30, PERF_COUNT_HW_REF_CPU_CYCLES },
};
/* mapping between fixed pmc index and arch_events array */
int fixed_pmc_events[] = {1, 0, 7};
static bool pmc_is_gp(struct kvm_pmc *pmc)
{
return pmc->type == KVM_PMC_GP;
}
static inline u64 pmc_bitmask(struct kvm_pmc *pmc)
{
struct kvm_pmu *pmu = &pmc->vcpu->arch.pmu;
return pmu->counter_bitmask[pmc->type];
}
static inline bool pmc_enabled(struct kvm_pmc *pmc)
{
struct kvm_pmu *pmu = &pmc->vcpu->arch.pmu;
return test_bit(pmc->idx, (unsigned long *)&pmu->global_ctrl);
}
static inline struct kvm_pmc *get_gp_pmc(struct kvm_pmu *pmu, u32 msr,
u32 base)
{
if (msr >= base && msr < base + pmu->nr_arch_gp_counters)
return &pmu->gp_counters[msr - base];
return NULL;
}
static inline struct kvm_pmc *get_fixed_pmc(struct kvm_pmu *pmu, u32 msr)
{
int base = MSR_CORE_PERF_FIXED_CTR0;
if (msr >= base && msr < base + pmu->nr_arch_fixed_counters)
return &pmu->fixed_counters[msr - base];
return NULL;
}
static inline struct kvm_pmc *get_fixed_pmc_idx(struct kvm_pmu *pmu, int idx)
{
return get_fixed_pmc(pmu, MSR_CORE_PERF_FIXED_CTR0 + idx);
}
static struct kvm_pmc *global_idx_to_pmc(struct kvm_pmu *pmu, int idx)
{
if (idx < INTEL_PMC_IDX_FIXED)
return get_gp_pmc(pmu, MSR_P6_EVNTSEL0 + idx, MSR_P6_EVNTSEL0);
else
return get_fixed_pmc_idx(pmu, idx - INTEL_PMC_IDX_FIXED);
}
void kvm_deliver_pmi(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.apic)
kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
}
static void trigger_pmi(struct irq_work *irq_work)
{
struct kvm_pmu *pmu = container_of(irq_work, struct kvm_pmu,
irq_work);
struct kvm_vcpu *vcpu = container_of(pmu, struct kvm_vcpu,
arch.pmu);
kvm_deliver_pmi(vcpu);
}
static void kvm_perf_overflow(struct perf_event *perf_event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct kvm_pmc *pmc = perf_event->overflow_handler_context;
struct kvm_pmu *pmu = &pmc->vcpu->arch.pmu;
if (!test_and_set_bit(pmc->idx, (unsigned long *)&pmu->reprogram_pmi)) {
__set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
}
}
static void kvm_perf_overflow_intr(struct perf_event *perf_event,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct kvm_pmc *pmc = perf_event->overflow_handler_context;
struct kvm_pmu *pmu = &pmc->vcpu->arch.pmu;
if (!test_and_set_bit(pmc->idx, (unsigned long *)&pmu->reprogram_pmi)) {
__set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
/*
* Inject PMI. If vcpu was in a guest mode during NMI PMI
* can be ejected on a guest mode re-entry. Otherwise we can't
* be sure that vcpu wasn't executing hlt instruction at the
* time of vmexit and is not going to re-enter guest mode until,
* woken up. So we should wake it, but this is impossible from
* NMI context. Do it from irq work instead.
*/
if (!kvm_is_in_guest())
irq_work_queue(&pmc->vcpu->arch.pmu.irq_work);
else
kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
}
}
static u64 read_pmc(struct kvm_pmc *pmc)
{
u64 counter, enabled, running;
counter = pmc->counter;
if (pmc->perf_event)
counter += perf_event_read_value(pmc->perf_event,
&enabled, &running);
/* FIXME: Scaling needed? */
return counter & pmc_bitmask(pmc);
}
static void stop_counter(struct kvm_pmc *pmc)
{
if (pmc->perf_event) {
pmc->counter = read_pmc(pmc);
perf_event_release_kernel(pmc->perf_event);
pmc->perf_event = NULL;
}
}
static void reprogram_counter(struct kvm_pmc *pmc, u32 type,
unsigned config, bool exclude_user, bool exclude_kernel,
bool intr, bool in_tx, bool in_tx_cp)
{
struct perf_event *event;
struct perf_event_attr attr = {
.type = type,
.size = sizeof(attr),
.pinned = true,
.exclude_idle = true,
.exclude_host = 1,
.exclude_user = exclude_user,
.exclude_kernel = exclude_kernel,
.config = config,
};
if (in_tx)
attr.config |= HSW_IN_TX;
if (in_tx_cp)
attr.config |= HSW_IN_TX_CHECKPOINTED;
attr.sample_period = (-pmc->counter) & pmc_bitmask(pmc);
event = perf_event_create_kernel_counter(&attr, -1, current,
intr ? kvm_perf_overflow_intr :
kvm_perf_overflow, pmc);
if (IS_ERR(event)) {
printk_once("kvm: pmu event creation failed %ld\n",
PTR_ERR(event));
return;
}
pmc->perf_event = event;
clear_bit(pmc->idx, (unsigned long*)&pmc->vcpu->arch.pmu.reprogram_pmi);
}
static unsigned find_arch_event(struct kvm_pmu *pmu, u8 event_select,
u8 unit_mask)
{
int i;
for (i = 0; i < ARRAY_SIZE(arch_events); i++)
if (arch_events[i].eventsel == event_select
&& arch_events[i].unit_mask == unit_mask
&& (pmu->available_event_types & (1 << i)))
break;
if (i == ARRAY_SIZE(arch_events))
return PERF_COUNT_HW_MAX;
return arch_events[i].event_type;
}
static void reprogram_gp_counter(struct kvm_pmc *pmc, u64 eventsel)
{
unsigned config, type = PERF_TYPE_RAW;
u8 event_select, unit_mask;
if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
printk_once("kvm pmu: pin control bit is ignored\n");
pmc->eventsel = eventsel;
stop_counter(pmc);
if (!(eventsel & ARCH_PERFMON_EVENTSEL_ENABLE) || !pmc_enabled(pmc))
return;
event_select = eventsel & ARCH_PERFMON_EVENTSEL_EVENT;
unit_mask = (eventsel & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
if (!(eventsel & (ARCH_PERFMON_EVENTSEL_EDGE |
ARCH_PERFMON_EVENTSEL_INV |
ARCH_PERFMON_EVENTSEL_CMASK |
HSW_IN_TX |
HSW_IN_TX_CHECKPOINTED))) {
config = find_arch_event(&pmc->vcpu->arch.pmu, event_select,
unit_mask);
if (config != PERF_COUNT_HW_MAX)
type = PERF_TYPE_HARDWARE;
}
if (type == PERF_TYPE_RAW)
config = eventsel & X86_RAW_EVENT_MASK;
reprogram_counter(pmc, type, config,
!(eventsel & ARCH_PERFMON_EVENTSEL_USR),
!(eventsel & ARCH_PERFMON_EVENTSEL_OS),
eventsel & ARCH_PERFMON_EVENTSEL_INT,
(eventsel & HSW_IN_TX),
(eventsel & HSW_IN_TX_CHECKPOINTED));
}
static void reprogram_fixed_counter(struct kvm_pmc *pmc, u8 en_pmi, int idx)
{
unsigned en = en_pmi & 0x3;
bool pmi = en_pmi & 0x8;
stop_counter(pmc);
if (!en || !pmc_enabled(pmc))
return;
reprogram_counter(pmc, PERF_TYPE_HARDWARE,
arch_events[fixed_pmc_events[idx]].event_type,
!(en & 0x2), /* exclude user */
!(en & 0x1), /* exclude kernel */
pmi, false, false);
}
static inline u8 fixed_en_pmi(u64 ctrl, int idx)
{
return (ctrl >> (idx * 4)) & 0xf;
}
static void reprogram_fixed_counters(struct kvm_pmu *pmu, u64 data)
{
int i;
for (i = 0; i < pmu->nr_arch_fixed_counters; i++) {
u8 en_pmi = fixed_en_pmi(data, i);
struct kvm_pmc *pmc = get_fixed_pmc_idx(pmu, i);
if (fixed_en_pmi(pmu->fixed_ctr_ctrl, i) == en_pmi)
continue;
reprogram_fixed_counter(pmc, en_pmi, i);
}
pmu->fixed_ctr_ctrl = data;
}
static void reprogram_idx(struct kvm_pmu *pmu, int idx)
{
struct kvm_pmc *pmc = global_idx_to_pmc(pmu, idx);
if (!pmc)
return;
if (pmc_is_gp(pmc))
reprogram_gp_counter(pmc, pmc->eventsel);
else {
int fidx = idx - INTEL_PMC_IDX_FIXED;
reprogram_fixed_counter(pmc,
fixed_en_pmi(pmu->fixed_ctr_ctrl, fidx), fidx);
}
}
static void global_ctrl_changed(struct kvm_pmu *pmu, u64 data)
{
int bit;
u64 diff = pmu->global_ctrl ^ data;
pmu->global_ctrl = data;
for_each_set_bit(bit, (unsigned long *)&diff, X86_PMC_IDX_MAX)
reprogram_idx(pmu, bit);
}
bool kvm_pmu_msr(struct kvm_vcpu *vcpu, u32 msr)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
int ret;
switch (msr) {
case MSR_CORE_PERF_FIXED_CTR_CTRL:
case MSR_CORE_PERF_GLOBAL_STATUS:
case MSR_CORE_PERF_GLOBAL_CTRL:
case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
ret = pmu->version > 1;
break;
default:
ret = get_gp_pmc(pmu, msr, MSR_IA32_PERFCTR0)
|| get_gp_pmc(pmu, msr, MSR_P6_EVNTSEL0)
|| get_fixed_pmc(pmu, msr);
break;
}
return ret;
}
int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
struct kvm_pmc *pmc;
switch (index) {
case MSR_CORE_PERF_FIXED_CTR_CTRL:
*data = pmu->fixed_ctr_ctrl;
return 0;
case MSR_CORE_PERF_GLOBAL_STATUS:
*data = pmu->global_status;
return 0;
case MSR_CORE_PERF_GLOBAL_CTRL:
*data = pmu->global_ctrl;
return 0;
case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
*data = pmu->global_ovf_ctrl;
return 0;
default:
if ((pmc = get_gp_pmc(pmu, index, MSR_IA32_PERFCTR0)) ||
(pmc = get_fixed_pmc(pmu, index))) {
*data = read_pmc(pmc);
return 0;
} else if ((pmc = get_gp_pmc(pmu, index, MSR_P6_EVNTSEL0))) {
*data = pmc->eventsel;
return 0;
}
}
return 1;
}
int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
struct kvm_pmc *pmc;
u32 index = msr_info->index;
u64 data = msr_info->data;
switch (index) {
case MSR_CORE_PERF_FIXED_CTR_CTRL:
if (pmu->fixed_ctr_ctrl == data)
return 0;
if (!(data & 0xfffffffffffff444ull)) {
reprogram_fixed_counters(pmu, data);
return 0;
}
break;
case MSR_CORE_PERF_GLOBAL_STATUS:
if (msr_info->host_initiated) {
pmu->global_status = data;
return 0;
}
break; /* RO MSR */
case MSR_CORE_PERF_GLOBAL_CTRL:
if (pmu->global_ctrl == data)
return 0;
if (!(data & pmu->global_ctrl_mask)) {
global_ctrl_changed(pmu, data);
return 0;
}
break;
case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
if (!(data & (pmu->global_ctrl_mask & ~(3ull<<62)))) {
if (!msr_info->host_initiated)
pmu->global_status &= ~data;
pmu->global_ovf_ctrl = data;
return 0;
}
break;
default:
if ((pmc = get_gp_pmc(pmu, index, MSR_IA32_PERFCTR0)) ||
(pmc = get_fixed_pmc(pmu, index))) {
if (!msr_info->host_initiated)
data = (s64)(s32)data;
pmc->counter += data - read_pmc(pmc);
return 0;
} else if ((pmc = get_gp_pmc(pmu, index, MSR_P6_EVNTSEL0))) {
if (data == pmc->eventsel)
return 0;
if (!(data & pmu->reserved_bits)) {
reprogram_gp_counter(pmc, data);
return 0;
}
}
}
return 1;
}
int kvm_pmu_check_pmc(struct kvm_vcpu *vcpu, unsigned pmc)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
bool fixed = pmc & (1u << 30);
pmc &= ~(3u << 30);
return (!fixed && pmc >= pmu->nr_arch_gp_counters) ||
(fixed && pmc >= pmu->nr_arch_fixed_counters);
}
int kvm_pmu_read_pmc(struct kvm_vcpu *vcpu, unsigned pmc, u64 *data)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
bool fast_mode = pmc & (1u << 31);
bool fixed = pmc & (1u << 30);
struct kvm_pmc *counters;
u64 ctr;
pmc &= ~(3u << 30);
if (!fixed && pmc >= pmu->nr_arch_gp_counters)
return 1;
if (fixed && pmc >= pmu->nr_arch_fixed_counters)
return 1;
counters = fixed ? pmu->fixed_counters : pmu->gp_counters;
ctr = read_pmc(&counters[pmc]);
if (fast_mode)
ctr = (u32)ctr;
*data = ctr;
return 0;
}
void kvm_pmu_cpuid_update(struct kvm_vcpu *vcpu)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
struct kvm_cpuid_entry2 *entry;
unsigned bitmap_len;
pmu->nr_arch_gp_counters = 0;
pmu->nr_arch_fixed_counters = 0;
pmu->counter_bitmask[KVM_PMC_GP] = 0;
pmu->counter_bitmask[KVM_PMC_FIXED] = 0;
pmu->version = 0;
pmu->reserved_bits = 0xffffffff00200000ull;
entry = kvm_find_cpuid_entry(vcpu, 0xa, 0);
if (!entry)
return;
pmu->version = entry->eax & 0xff;
if (!pmu->version)
return;
pmu->nr_arch_gp_counters = min((int)(entry->eax >> 8) & 0xff,
INTEL_PMC_MAX_GENERIC);
pmu->counter_bitmask[KVM_PMC_GP] =
((u64)1 << ((entry->eax >> 16) & 0xff)) - 1;
bitmap_len = (entry->eax >> 24) & 0xff;
pmu->available_event_types = ~entry->ebx & ((1ull << bitmap_len) - 1);
if (pmu->version == 1) {
pmu->nr_arch_fixed_counters = 0;
} else {
pmu->nr_arch_fixed_counters = min((int)(entry->edx & 0x1f),
INTEL_PMC_MAX_FIXED);
pmu->counter_bitmask[KVM_PMC_FIXED] =
((u64)1 << ((entry->edx >> 5) & 0xff)) - 1;
}
pmu->global_ctrl = ((1 << pmu->nr_arch_gp_counters) - 1) |
(((1ull << pmu->nr_arch_fixed_counters) - 1) << INTEL_PMC_IDX_FIXED);
pmu->global_ctrl_mask = ~pmu->global_ctrl;
entry = kvm_find_cpuid_entry(vcpu, 7, 0);
if (entry &&
(boot_cpu_has(X86_FEATURE_HLE) || boot_cpu_has(X86_FEATURE_RTM)) &&
(entry->ebx & (X86_FEATURE_HLE|X86_FEATURE_RTM)))
pmu->reserved_bits ^= HSW_IN_TX|HSW_IN_TX_CHECKPOINTED;
}
void kvm_pmu_init(struct kvm_vcpu *vcpu)
{
int i;
struct kvm_pmu *pmu = &vcpu->arch.pmu;
memset(pmu, 0, sizeof(*pmu));
for (i = 0; i < INTEL_PMC_MAX_GENERIC; i++) {
pmu->gp_counters[i].type = KVM_PMC_GP;
pmu->gp_counters[i].vcpu = vcpu;
pmu->gp_counters[i].idx = i;
}
for (i = 0; i < INTEL_PMC_MAX_FIXED; i++) {
pmu->fixed_counters[i].type = KVM_PMC_FIXED;
pmu->fixed_counters[i].vcpu = vcpu;
pmu->fixed_counters[i].idx = i + INTEL_PMC_IDX_FIXED;
}
init_irq_work(&pmu->irq_work, trigger_pmi);
kvm_pmu_cpuid_update(vcpu);
}
void kvm_pmu_reset(struct kvm_vcpu *vcpu)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
int i;
irq_work_sync(&pmu->irq_work);
for (i = 0; i < INTEL_PMC_MAX_GENERIC; i++) {
struct kvm_pmc *pmc = &pmu->gp_counters[i];
stop_counter(pmc);
pmc->counter = pmc->eventsel = 0;
}
for (i = 0; i < INTEL_PMC_MAX_FIXED; i++)
stop_counter(&pmu->fixed_counters[i]);
pmu->fixed_ctr_ctrl = pmu->global_ctrl = pmu->global_status =
pmu->global_ovf_ctrl = 0;
}
void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
{
kvm_pmu_reset(vcpu);
}
void kvm_handle_pmu_event(struct kvm_vcpu *vcpu)
{
struct kvm_pmu *pmu = &vcpu->arch.pmu;
u64 bitmask;
int bit;
bitmask = pmu->reprogram_pmi;
for_each_set_bit(bit, (unsigned long *)&bitmask, X86_PMC_IDX_MAX) {
struct kvm_pmc *pmc = global_idx_to_pmc(pmu, bit);
if (unlikely(!pmc || !pmc->perf_event)) {
clear_bit(bit, (unsigned long *)&pmu->reprogram_pmi);
continue;
}
reprogram_idx(pmu, bit);
}
}
|
<?php
/**
* WooCommerce API Orders Class
*
* Handles requests to the /orders endpoint
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class WC_API_Orders extends WC_API_Resource {
/** @var string $base the route base */
protected $base = '/orders';
/** @var string $post_type the custom post type */
protected $post_type = 'shop_order';
/**
* Register the routes for this class
*
* GET|POST /orders
* GET /orders/count
* GET|PUT|DELETE /orders/<id>
* GET /orders/<id>/notes
*
* @since 2.1
* @param array $routes
* @return array
*/
public function register_routes( $routes ) {
# GET|POST /orders
$routes[ $this->base ] = array(
array( array( $this, 'get_orders' ), WC_API_Server::READABLE ),
array( array( $this, 'create_order' ), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA ),
);
# GET /orders/count
$routes[ $this->base . '/count' ] = array(
array( array( $this, 'get_orders_count' ), WC_API_Server::READABLE ),
);
# GET /orders/statuses
$routes[ $this->base . '/statuses' ] = array(
array( array( $this, 'get_order_statuses' ), WC_API_Server::READABLE ),
);
# GET|PUT|DELETE /orders/<id>
$routes[ $this->base . '/(?P<id>\d+)' ] = array(
array( array( $this, 'get_order' ), WC_API_Server::READABLE ),
array( array( $this, 'edit_order' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
array( array( $this, 'delete_order' ), WC_API_Server::DELETABLE ),
);
# GET|POST /orders/<id>/notes
$routes[ $this->base . '/(?P<order_id>\d+)/notes' ] = array(
array( array( $this, 'get_order_notes' ), WC_API_Server::READABLE ),
array( array( $this, 'create_order_note' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
);
# GET|PUT|DELETE /orders/<order_id>/notes/<id>
$routes[ $this->base . '/(?P<order_id>\d+)/notes/(?P<id>\d+)' ] = array(
array( array( $this, 'get_order_note' ), WC_API_Server::READABLE ),
array( array( $this, 'edit_order_note' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
array( array( $this, 'delete_order_note' ), WC_API_SERVER::DELETABLE ),
);
# GET|POST /orders/<order_id>/refunds
$routes[ $this->base . '/(?P<order_id>\d+)/refunds' ] = array(
array( array( $this, 'get_order_refunds' ), WC_API_Server::READABLE ),
array( array( $this, 'create_order_refund' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
);
# GET|PUT|DELETE /orders/<order_id>/refunds/<id>
$routes[ $this->base . '/(?P<order_id>\d+)/refunds/(?P<id>\d+)' ] = array(
array( array( $this, 'get_order_refund' ), WC_API_Server::READABLE ),
array( array( $this, 'edit_order_refund' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
array( array( $this, 'delete_order_refund' ), WC_API_SERVER::DELETABLE ),
);
# POST|PUT /orders/bulk
$routes[ $this->base . '/bulk' ] = array(
array( array( $this, 'bulk' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
);
return $routes;
}
/**
* Get all orders
*
* @since 2.1
* @param string $fields
* @param array $filter
* @param string $status
* @param int $page
* @return array
*/
public function get_orders( $fields = null, $filter = array(), $status = null, $page = 1 ) {
if ( ! empty( $status ) ) {
$filter['status'] = $status;
}
$filter['page'] = $page;
$query = $this->query_orders( $filter );
$orders = array();
foreach ( $query->posts as $order_id ) {
if ( ! $this->is_readable( $order_id ) ) {
continue;
}
$orders[] = current( $this->get_order( $order_id, $fields, $filter ) );
}
$this->server->add_pagination_headers( $query );
return array( 'orders' => $orders );
}
/**
* Get the order for the given ID
*
* @since 2.1
* @param int $id the order ID
* @param array $fields
* @param array $filter
* @return array
*/
public function get_order( $id, $fields = null, $filter = array() ) {
// ensure order ID is valid & user has permission to read
$id = $this->validate_request( $id, $this->post_type, 'read' );
if ( is_wp_error( $id ) ) {
return $id;
}
// Get the decimal precession
$dp = ( isset( $filter['dp'] ) ? intval( $filter['dp'] ) : 2 );
$order = wc_get_order( $id );
$order_post = get_post( $id );
$order_data = array(
'id' => $order->id,
'order_number' => $order->get_order_number(),
'created_at' => $this->server->format_datetime( $order_post->post_date_gmt ),
'updated_at' => $this->server->format_datetime( $order_post->post_modified_gmt ),
'completed_at' => $this->server->format_datetime( $order->completed_date, true ),
'status' => $order->get_status(),
'currency' => $order->get_order_currency(),
'total' => wc_format_decimal( $order->get_total(), $dp ),
'subtotal' => wc_format_decimal( $order->get_subtotal(), $dp ),
'total_line_items_quantity' => $order->get_item_count(),
'total_tax' => wc_format_decimal( $order->get_total_tax(), $dp ),
'total_shipping' => wc_format_decimal( $order->get_total_shipping(), $dp ),
'cart_tax' => wc_format_decimal( $order->get_cart_tax(), $dp ),
'shipping_tax' => wc_format_decimal( $order->get_shipping_tax(), $dp ),
'total_discount' => wc_format_decimal( $order->get_total_discount(), $dp ),
'shipping_methods' => $order->get_shipping_method(),
'payment_details' => array(
'method_id' => $order->payment_method,
'method_title' => $order->payment_method_title,
'paid' => isset( $order->paid_date ),
),
'billing_address' => array(
'first_name' => $order->billing_first_name,
'last_name' => $order->billing_last_name,
'company' => $order->billing_company,
'address_1' => $order->billing_address_1,
'address_2' => $order->billing_address_2,
'city' => $order->billing_city,
'state' => $order->billing_state,
'postcode' => $order->billing_postcode,
'country' => $order->billing_country,
'email' => $order->billing_email,
'phone' => $order->billing_phone,
),
'shipping_address' => array(
'first_name' => $order->shipping_first_name,
'last_name' => $order->shipping_last_name,
'company' => $order->shipping_company,
'address_1' => $order->shipping_address_1,
'address_2' => $order->shipping_address_2,
'city' => $order->shipping_city,
'state' => $order->shipping_state,
'postcode' => $order->shipping_postcode,
'country' => $order->shipping_country,
),
'note' => $order->customer_note,
'customer_ip' => $order->customer_ip_address,
'customer_user_agent' => $order->customer_user_agent,
'customer_id' => $order->get_user_id(),
'view_order_url' => $order->get_view_order_url(),
'line_items' => array(),
'shipping_lines' => array(),
'tax_lines' => array(),
'fee_lines' => array(),
'coupon_lines' => array(),
);
// add line items
foreach ( $order->get_items() as $item_id => $item ) {
$product = $order->get_product_from_item( $item );
$product_id = null;
$product_sku = null;
// Check if the product exists.
if ( is_object( $product ) ) {
$product_id = ( isset( $product->variation_id ) ) ? $product->variation_id : $product->id;
$product_sku = $product->get_sku();
}
$meta = new WC_Order_Item_Meta( $item, $product );
$item_meta = array();
$hideprefix = ( isset( $filter['all_item_meta'] ) && $filter['all_item_meta'] === 'true' ) ? null : '_';
foreach ( $meta->get_formatted( $hideprefix ) as $meta_key => $formatted_meta ) {
$item_meta[] = array(
'key' => $meta_key,
'label' => $formatted_meta['label'],
'value' => $formatted_meta['value'],
);
}
$order_data['line_items'][] = array(
'id' => $item_id,
'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item, false, false ), $dp ),
'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], $dp ),
'total' => wc_format_decimal( $order->get_line_total( $item, false, false ), $dp ),
'total_tax' => wc_format_decimal( $item['line_tax'], $dp ),
'price' => wc_format_decimal( $order->get_item_total( $item, false, false ), $dp ),
'quantity' => wc_stock_amount( $item['qty'] ),
'tax_class' => ( ! empty( $item['tax_class'] ) ) ? $item['tax_class'] : null,
'name' => $item['name'],
'product_id' => $product_id,
'sku' => $product_sku,
'meta' => $item_meta,
);
}
// add shipping
foreach ( $order->get_shipping_methods() as $shipping_item_id => $shipping_item ) {
$order_data['shipping_lines'][] = array(
'id' => $shipping_item_id,
'method_id' => $shipping_item['method_id'],
'method_title' => $shipping_item['name'],
'total' => wc_format_decimal( $shipping_item['cost'], $dp ),
);
}
// add taxes
foreach ( $order->get_tax_totals() as $tax_code => $tax ) {
$order_data['tax_lines'][] = array(
'id' => $tax->id,
'rate_id' => $tax->rate_id,
'code' => $tax_code,
'title' => $tax->label,
'total' => wc_format_decimal( $tax->amount, $dp ),
'compound' => (bool) $tax->is_compound,
);
}
// add fees
foreach ( $order->get_fees() as $fee_item_id => $fee_item ) {
$order_data['fee_lines'][] = array(
'id' => $fee_item_id,
'title' => $fee_item['name'],
'tax_class' => ( ! empty( $fee_item['tax_class'] ) ) ? $fee_item['tax_class'] : null,
'total' => wc_format_decimal( $order->get_line_total( $fee_item ), $dp ),
'total_tax' => wc_format_decimal( $order->get_line_tax( $fee_item ), $dp ),
);
}
// add coupons
foreach ( $order->get_items( 'coupon' ) as $coupon_item_id => $coupon_item ) {
$order_data['coupon_lines'][] = array(
'id' => $coupon_item_id,
'code' => $coupon_item['name'],
'amount' => wc_format_decimal( $coupon_item['discount_amount'], $dp ),
);
}
return array( 'order' => apply_filters( 'woocommerce_api_order_response', $order_data, $order, $fields, $this->server ) );
}
/**
* Get the total number of orders
*
* @since 2.4
* @param string $status
* @param array $filter
* @return array
*/
public function get_orders_count( $status = null, $filter = array() ) {
try {
if ( ! current_user_can( 'read_private_shop_orders' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_orders_count', __( 'You do not have permission to read the orders count', 'woocommerce' ), 401 );
}
if ( ! empty( $status ) ) {
if ( $status == 'any' ) {
$order_statuses = array();
foreach ( wc_get_order_statuses() as $slug => $name ) {
$filter['status'] = str_replace( 'wc-', '', $slug );
$query = $this->query_orders( $filter );
$order_statuses[ str_replace( 'wc-', '', $slug ) ] = (int) $query->found_posts;
}
return array( 'count' => $order_statuses );
} else {
$filter['status'] = $status;
}
}
$query = $this->query_orders( $filter );
return array( 'count' => (int) $query->found_posts );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get a list of valid order statuses
*
* Note this requires no specific permissions other than being an authenticated
* API user. Order statuses (particularly custom statuses) could be considered
* private information which is why it's not in the API index.
*
* @since 2.1
* @return array
*/
public function get_order_statuses() {
$order_statuses = array();
foreach ( wc_get_order_statuses() as $slug => $name ) {
$order_statuses[ str_replace( 'wc-', '', $slug ) ] = $name;
}
return array( 'order_statuses' => apply_filters( 'woocommerce_api_order_statuses_response', $order_statuses, $this ) );
}
/**
* Create an order
*
* @since 2.2
* @param array $data raw order data
* @return array
*/
public function create_order( $data ) {
global $wpdb;
$wpdb->query( 'START TRANSACTION' );
try {
if ( ! isset( $data['order'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order' ), 400 );
}
$data = $data['order'];
// permission check
if ( ! current_user_can( 'publish_shop_orders' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order', __( 'You do not have permission to create orders', 'woocommerce' ), 401 );
}
$data = apply_filters( 'woocommerce_api_create_order_data', $data, $this );
// default order args, note that status is checked for validity in wc_create_order()
$default_order_args = array(
'status' => isset( $data['status'] ) ? $data['status'] : '',
'customer_note' => isset( $data['note'] ) ? $data['note'] : null,
);
// if creating order for existing customer
if ( ! empty( $data['customer_id'] ) ) {
// make sure customer exists
if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
}
$default_order_args['customer_id'] = $data['customer_id'];
}
// create the pending order
$order = $this->create_base_order( $default_order_args, $data );
if ( is_wp_error( $order ) ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_order', sprintf( __( 'Cannot create order: %s', 'woocommerce' ), implode( ', ', $order->get_error_messages() ) ), 400 );
}
// billing/shipping addresses
$this->set_order_addresses( $order, $data );
$lines = array(
'line_item' => 'line_items',
'shipping' => 'shipping_lines',
'fee' => 'fee_lines',
'coupon' => 'coupon_lines',
);
foreach ( $lines as $line_type => $line ) {
if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
$set_item = "set_{$line_type}";
foreach ( $data[ $line ] as $item ) {
$this->$set_item( $order, $item, 'create' );
}
}
}
// calculate totals and set them
$order->calculate_totals();
// payment method (and payment_complete() if `paid` == true)
if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
// method ID & title are required
if ( empty( $data['payment_details']['method_id'] ) || empty( $data['payment_details']['method_title'] ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_payment_details', __( 'Payment method ID and title are required', 'woocommerce' ), 400 );
}
update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
// mark as paid if set
if ( isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
$order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
}
}
// set order currency
if ( isset( $data['currency'] ) ) {
if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce'), 400 );
}
update_post_meta( $order->id, '_order_currency', $data['currency'] );
}
// set order number
if ( isset( $data['order_number'] ) ) {
update_post_meta( $order->id, '_order_number', $data['order_number'] );
}
// set order meta
if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
$this->set_order_meta( $order->id, $data['order_meta'] );
}
// HTTP 201 Created
$this->server->send_status( 201 );
wc_delete_shop_order_transients( $order->id );
do_action( 'woocommerce_api_create_order', $order->id, $data, $this );
$wpdb->query( 'COMMIT' );
return $this->get_order( $order->id );
} catch ( WC_API_Exception $e ) {
$wpdb->query( 'ROLLBACK' );
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Creates new WC_Order.
*
* Requires a separate function for classes that extend WC_API_Orders.
*
* @since 2.3
* @param $args array
* @return WC_Order
*/
protected function create_base_order( $args, $data ) {
return wc_create_order( $args );
}
/**
* Edit an order
*
* @since 2.2
* @param int $id the order ID
* @param array $data
* @return array
*/
public function edit_order( $id, $data ) {
try {
if ( ! isset( $data['order'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order' ), 400 );
}
$data = $data['order'];
$update_totals = false;
$id = $this->validate_request( $id, $this->post_type, 'edit' );
if ( is_wp_error( $id ) ) {
return $id;
}
$data = apply_filters( 'woocommerce_api_edit_order_data', $data, $id, $this );
$order = wc_get_order( $id );
if ( empty( $order ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
}
$order_args = array( 'order_id' => $order->id );
// customer note
if ( isset( $data['note'] ) ) {
$order_args['customer_note'] = $data['note'];
}
// order status
if ( ! empty( $data['status'] ) ) {
$order->update_status( $data['status'], isset( $data['status_note'] ) ? $data['status_note'] : '' );
}
// customer ID
if ( isset( $data['customer_id'] ) && $data['customer_id'] != $order->get_user_id() ) {
// make sure customer exists
if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
}
update_post_meta( $order->id, '_customer_user', $data['customer_id'] );
}
// billing/shipping address
$this->set_order_addresses( $order, $data );
$lines = array(
'line_item' => 'line_items',
'shipping' => 'shipping_lines',
'fee' => 'fee_lines',
'coupon' => 'coupon_lines',
);
foreach ( $lines as $line_type => $line ) {
if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
$update_totals = true;
foreach ( $data[ $line ] as $item ) {
// item ID is always required
if ( ! array_key_exists( 'id', $item ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID is required', 'woocommerce' ), 400 );
}
// create item
if ( is_null( $item['id'] ) ) {
$this->set_item( $order, $line_type, $item, 'create' );
} elseif ( $this->item_is_null( $item ) ) {
// delete item
wc_delete_order_item( $item['id'] );
} else {
// update item
$this->set_item( $order, $line_type, $item, 'update' );
}
}
}
}
// payment method (and payment_complete() if `paid` == true and order needs payment)
if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
// method ID
if ( isset( $data['payment_details']['method_id'] ) ) {
update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
}
// method title
if ( isset( $data['payment_details']['method_title'] ) ) {
update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
}
// mark as paid if set
if ( $order->needs_payment() && isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
$order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
}
}
// set order currency
if ( isset( $data['currency'] ) ) {
if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce' ), 400 );
}
update_post_meta( $order->id, '_order_currency', $data['currency'] );
}
// set order number
if ( isset( $data['order_number'] ) ) {
update_post_meta( $order->id, '_order_number', $data['order_number'] );
}
// if items have changed, recalculate order totals
if ( $update_totals ) {
$order->calculate_totals();
}
// update order meta
if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
$this->set_order_meta( $order->id, $data['order_meta'] );
}
// update the order post to set customer note/modified date
wc_update_order( $order_args );
wc_delete_shop_order_transients( $order->id );
do_action( 'woocommerce_api_edit_order', $order->id, $data, $this );
return $this->get_order( $id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Delete an order
*
* @param int $id the order ID
* @param bool $force true to permanently delete order, false to move to trash
* @return array
*/
public function delete_order( $id, $force = false ) {
$id = $this->validate_request( $id, $this->post_type, 'delete' );
if ( is_wp_error( $id ) ) {
return $id;
}
wc_delete_shop_order_transients( $id );
do_action( 'woocommerce_api_delete_order', $id, $this );
return $this->delete( $id, 'order', ( 'true' === $force ) );
}
/**
* Helper method to get order post objects
*
* @since 2.1
* @param array $args request arguments for filtering query
* @return WP_Query
*/
protected function query_orders( $args ) {
// set base query arguments
$query_args = array(
'fields' => 'ids',
'post_type' => $this->post_type,
'post_status' => array_keys( wc_get_order_statuses() )
);
// add status argument
if ( ! empty( $args['status'] ) ) {
$statuses = 'wc-' . str_replace( ',', ',wc-', $args['status'] );
$statuses = explode( ',', $statuses );
$query_args['post_status'] = $statuses;
unset( $args['status'] );
}
$query_args = $this->merge_query_args( $query_args, $args );
return new WP_Query( $query_args );
}
/**
* Helper method to set/update the billing & shipping addresses for
* an order
*
* @since 2.1
* @param \WC_Order $order
* @param array $data
*/
protected function set_order_addresses( $order, $data ) {
$address_fields = array(
'first_name',
'last_name',
'company',
'email',
'phone',
'address_1',
'address_2',
'city',
'state',
'postcode',
'country',
);
$billing_address = $shipping_address = array();
// billing address
if ( isset( $data['billing_address'] ) && is_array( $data['billing_address'] ) ) {
foreach ( $address_fields as $field ) {
if ( isset( $data['billing_address'][ $field ] ) ) {
$billing_address[ $field ] = wc_clean( $data['billing_address'][ $field ] );
}
}
unset( $address_fields['email'] );
unset( $address_fields['phone'] );
}
// shipping address
if ( isset( $data['shipping_address'] ) && is_array( $data['shipping_address'] ) ) {
foreach ( $address_fields as $field ) {
if ( isset( $data['shipping_address'][ $field ] ) ) {
$shipping_address[ $field ] = wc_clean( $data['shipping_address'][ $field ] );
}
}
}
$order->set_address( $billing_address, 'billing' );
$order->set_address( $shipping_address, 'shipping' );
// update user meta
if ( $order->get_user_id() ) {
foreach ( $billing_address as $key => $value ) {
update_user_meta( $order->get_user_id(), 'billing_' . $key, $value );
}
foreach ( $shipping_address as $key => $value ) {
update_user_meta( $order->get_user_id(), 'shipping_' . $key, $value );
}
}
}
/**
* Helper method to add/update order meta, with two restrictions:
*
* 1) Only non-protected meta (no leading underscore) can be set
* 2) Meta values must be scalar (int, string, bool)
*
* @since 2.2
* @param int $order_id valid order ID
* @param array $order_meta order meta in array( 'meta_key' => 'meta_value' ) format
*/
protected function set_order_meta( $order_id, $order_meta ) {
foreach ( $order_meta as $meta_key => $meta_value ) {
if ( is_string( $meta_key) && ! is_protected_meta( $meta_key ) && is_scalar( $meta_value ) ) {
update_post_meta( $order_id, $meta_key, $meta_value );
}
}
}
/**
* Helper method to check if the resource ID associated with the provided item is null
*
* Items can be deleted by setting the resource ID to null
*
* @since 2.2
* @param array $item item provided in the request body
* @return bool true if the item resource ID is null, false otherwise
*/
protected function item_is_null( $item ) {
$keys = array( 'product_id', 'method_id', 'title', 'code' );
foreach ( $keys as $key ) {
if ( array_key_exists( $key, $item ) && is_null( $item[ $key ] ) ) {
return true;
}
}
return false;
}
/**
* Wrapper method to create/update order items
*
* When updating, the item ID provided is checked to ensure it is associated
* with the order.
*
* @since 2.2
* @param \WC_Order $order order
* @param string $item_type
* @param array $item item provided in the request body
* @param string $action either 'create' or 'update'
* @throws WC_API_Exception if item ID is not associated with order
*/
protected function set_item( $order, $item_type, $item, $action ) {
global $wpdb;
$set_method = "set_{$item_type}";
// verify provided line item ID is associated with order
if ( 'update' === $action ) {
$result = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id = %d AND order_id = %d",
absint( $item['id'] ),
absint( $order->id )
) );
if ( is_null( $result ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID provided is not associated with order', 'woocommerce' ), 400 );
}
}
$this->$set_method( $order, $item, $action );
}
/**
* Create or update a line item
*
* @since 2.2
* @param \WC_Order $order
* @param array $item line item data
* @param string $action 'create' to add line item or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_line_item( $order, $item, $action ) {
$creating = ( 'create' === $action );
// product is always required
if ( ! isset( $item['product_id'] ) && ! isset( $item['sku'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID or SKU is required', 'woocommerce' ), 400 );
}
// when updating, ensure product ID provided matches
if ( 'update' === $action ) {
$item_product_id = wc_get_order_item_meta( $item['id'], '_product_id' );
$item_variation_id = wc_get_order_item_meta( $item['id'], '_variation_id' );
if ( $item['product_id'] != $item_product_id && $item['product_id'] != $item_variation_id ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID provided does not match this line item', 'woocommerce' ), 400 );
}
}
if ( isset( $item['product_id'] ) ) {
$product_id = $item['product_id'];
} elseif ( isset( $item['sku'] ) ) {
$product_id = wc_get_product_id_by_sku( $item['sku'] );
}
// variations must each have a key & value
$variation_id = 0;
if ( isset( $item['variations'] ) && is_array( $item['variations'] ) ) {
foreach ( $item['variations'] as $key => $value ) {
if ( ! $key || ! $value ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_variation', __( 'The product variation is invalid', 'woocommerce' ), 400 );
}
}
$item_args['variation'] = $item['variations'];
$variation_id = $this->get_variation_id( wc_get_product( $product_id ), $item_args['variation'] );
}
$product = wc_get_product( $variation_id ? $variation_id : $product_id );
// must be a valid WC_Product
if ( ! is_object( $product ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product', __( 'Product is invalid', 'woocommerce' ), 400 );
}
// quantity must be positive float
if ( isset( $item['quantity'] ) && floatval( $item['quantity'] ) <= 0 ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity must be a positive float', 'woocommerce' ), 400 );
}
// quantity is required when creating
if ( $creating && ! isset( $item['quantity'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity is required', 'woocommerce' ), 400 );
}
$item_args = array();
// quantity
if ( isset( $item['quantity'] ) ) {
$item_args['qty'] = $item['quantity'];
}
// total
if ( isset( $item['total'] ) ) {
$item_args['totals']['total'] = floatval( $item['total'] );
}
// total tax
if ( isset( $item['total_tax'] ) ) {
$item_args['totals']['tax'] = floatval( $item['total_tax'] );
}
// subtotal
if ( isset( $item['subtotal'] ) ) {
$item_args['totals']['subtotal'] = floatval( $item['subtotal'] );
}
// subtotal tax
if ( isset( $item['subtotal_tax'] ) ) {
$item_args['totals']['subtotal_tax'] = floatval( $item['subtotal_tax'] );
}
if ( $creating ) {
$item_id = $order->add_product( $product, $item_args['qty'], $item_args );
if ( ! $item_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_create_line_item', __( 'Cannot create line item, try again', 'woocommerce' ), 500 );
}
} else {
$item_id = $order->update_product( $item['id'], $product, $item_args );
if ( ! $item_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_update_line_item', __( 'Cannot update line item, try again', 'woocommerce' ), 500 );
}
}
}
/**
* Given a product ID & API provided variations, find the correct variation ID to use for calculation
* We can't just trust input from the API to pass a variation_id manually, otherwise you could pass
* the cheapest variation ID but provide other information so we have to look up the variation ID.
* @param int $product_id main product ID
* @return int returns an ID if a valid variation was found for this product
*/
function get_variation_id( $product, $variations = array() ) {
$variation_id = null;
$variations_normalized = array();
if ( $product->is_type( 'variable' ) && $product->has_child() ) {
if ( isset( $variations ) && is_array( $variations ) ) {
// start by normalizing the passed variations
foreach ( $variations as $key => $value ) {
$key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) ); // from get_attributes in class-wc-api-products.php
$variations_normalized[ $key ] = strtolower( $value );
}
// now search through each product child and see if our passed variations match anything
foreach ( $product->get_children() as $variation ) {
$meta = array();
foreach ( get_post_meta( $variation ) as $key => $value ) {
$value = $value[0];
$key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) );
$meta[ $key ] = strtolower( $value );
}
// if the variation array is a part of the $meta array, we found our match
if ( $this->array_contains( $variations_normalized, $meta ) ) {
$variation_id = $variation;
break;
}
}
}
}
return $variation_id;
}
/**
* Utility function to see if the meta array contains data from variations
*/
protected function array_contains( $needles, $haystack ) {
foreach ( $needles as $key => $value ) {
if ( $haystack[ $key ] !== $value ) {
return false;
}
}
return true;
}
/**
* Create or update an order shipping method
*
* @since 2.2
* @param \WC_Order $order
* @param array $shipping item data
* @param string $action 'create' to add shipping or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_shipping( $order, $shipping, $action ) {
// total must be a positive float
if ( isset( $shipping['total'] ) && floatval( $shipping['total'] ) < 0 ) {
throw new WC_API_Exception( 'woocommerce_invalid_shipping_total', __( 'Shipping total must be a positive amount', 'woocommerce' ), 400 );
}
if ( 'create' === $action ) {
// method ID is required
if ( ! isset( $shipping['method_id'] ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_shipping_item', __( 'Shipping method ID is required', 'woocommerce' ), 400 );
}
$rate = new WC_Shipping_Rate( $shipping['method_id'], isset( $shipping['method_title'] ) ? $shipping['method_title'] : '', isset( $shipping['total'] ) ? floatval( $shipping['total'] ) : 0, array(), $shipping['method_id'] );
$shipping_id = $order->add_shipping( $rate );
if ( ! $shipping_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_create_shipping', __( 'Cannot create shipping method, try again', 'woocommerce' ), 500 );
}
} else {
$shipping_args = array();
if ( isset( $shipping['method_id'] ) ) {
$shipping_args['method_id'] = $shipping['method_id'];
}
if ( isset( $shipping['method_title'] ) ) {
$shipping_args['method_title'] = $shipping['method_title'];
}
if ( isset( $shipping['total'] ) ) {
$shipping_args['cost'] = floatval( $shipping['total'] );
}
$shipping_id = $order->update_shipping( $shipping['id'], $shipping_args );
if ( ! $shipping_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_update_shipping', __( 'Cannot update shipping method, try again', 'woocommerce' ), 500 );
}
}
}
/**
* Create or update an order fee
*
* @since 2.2
* @param \WC_Order $order
* @param array $fee item data
* @param string $action 'create' to add fee or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_fee( $order, $fee, $action ) {
if ( 'create' === $action ) {
// fee title is required
if ( ! isset( $fee['title'] ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee title is required', 'woocommerce' ), 400 );
}
$order_fee = new stdClass();
$order_fee->id = sanitize_title( $fee['title'] );
$order_fee->name = $fee['title'];
$order_fee->amount = isset( $fee['total'] ) ? floatval( $fee['total'] ) : 0;
$order_fee->taxable = false;
$order_fee->tax = 0;
$order_fee->tax_data = array();
$order_fee->tax_class = '';
// if taxable, tax class and total are required
if ( isset( $fee['taxable'] ) && $fee['taxable'] ) {
if ( ! isset( $fee['tax_class'] ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee tax class is required when fee is taxable', 'woocommerce' ), 400 );
}
$order_fee->taxable = true;
$order_fee->tax_class = $fee['tax_class'];
if ( isset( $fee['total_tax'] ) ) {
$order_fee->tax = isset( $fee['total_tax'] ) ? wc_format_refund_total( $fee['total_tax'] ) : 0;
}
if ( isset( $fee['tax_data'] ) ) {
$order_fee->tax = wc_format_refund_total( array_sum( $fee['tax_data'] ) );
$order_fee->tax_data = array_map( 'wc_format_refund_total', $fee['tax_data'] );
}
}
$fee_id = $order->add_fee( $order_fee );
if ( ! $fee_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_create_fee', __( 'Cannot create fee, try again', 'woocommerce' ), 500 );
}
} else {
$fee_args = array();
if ( isset( $fee['title'] ) ) {
$fee_args['name'] = $fee['title'];
}
if ( isset( $fee['tax_class'] ) ) {
$fee_args['tax_class'] = $fee['tax_class'];
}
if ( isset( $fee['total'] ) ) {
$fee_args['line_total'] = floatval( $fee['total'] );
}
if ( isset( $fee['total_tax'] ) ) {
$fee_args['line_tax'] = floatval( $fee['total_tax'] );
}
$fee_id = $order->update_fee( $fee['id'], $fee_args );
if ( ! $fee_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_update_fee', __( 'Cannot update fee, try again', 'woocommerce' ), 500 );
}
}
}
/**
* Create or update an order coupon
*
* @since 2.2
* @param \WC_Order $order
* @param array $coupon item data
* @param string $action 'create' to add coupon or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_coupon( $order, $coupon, $action ) {
// coupon amount must be positive float
if ( isset( $coupon['amount'] ) && floatval( $coupon['amount'] ) < 0 ) {
throw new WC_API_Exception( 'woocommerce_invalid_coupon_total', __( 'Coupon discount total must be a positive amount', 'woocommerce' ), 400 );
}
if ( 'create' === $action ) {
// coupon code is required
if ( empty( $coupon['code'] ) ) {
throw new WC_API_Exception( 'woocommerce_invalid_coupon_coupon', __( 'Coupon code is required', 'woocommerce' ), 400 );
}
$coupon_id = $order->add_coupon( $coupon['code'], isset( $coupon['amount'] ) ? floatval( $coupon['amount'] ) : 0 );
if ( ! $coupon_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_create_order_coupon', __( 'Cannot create coupon, try again', 'woocommerce' ), 500 );
}
} else {
$coupon_args = array();
if ( isset( $coupon['code'] ) ) {
$coupon_args['code'] = $coupon['code'];
}
if ( isset( $coupon['amount'] ) ) {
$coupon_args['discount_amount'] = floatval( $coupon['amount'] );
}
$coupon_id = $order->update_coupon( $coupon['id'], $coupon_args );
if ( ! $coupon_id ) {
throw new WC_API_Exception( 'woocommerce_cannot_update_order_coupon', __( 'Cannot update coupon, try again', 'woocommerce' ), 500 );
}
}
}
/**
* Get the admin order notes for an order
*
* @since 2.1
* @param string $order_id order ID
* @param string|null $fields fields to include in response
* @return array
*/
public function get_order_notes( $order_id, $fields = null ) {
// ensure ID is valid order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$args = array(
'post_id' => $order_id,
'approve' => 'approve',
'type' => 'order_note'
);
remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
$notes = get_comments( $args );
add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
$order_notes = array();
foreach ( $notes as $note ) {
$order_notes[] = current( $this->get_order_note( $order_id, $note->comment_ID, $fields ) );
}
return array( 'order_notes' => apply_filters( 'woocommerce_api_order_notes_response', $order_notes, $order_id, $fields, $notes, $this->server ) );
}
/**
* Get an order note for the given order ID and ID
*
* @since 2.2
* @param string $order_id order ID
* @param string $id order note ID
* @param string|null $fields fields to limit response to
* @return array
*/
public function get_order_note( $order_id, $id, $fields = null ) {
try {
// Validate order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
}
$note = get_comment( $id );
if ( is_null( $note ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
}
$order_note = array(
'id' => $note->comment_ID,
'created_at' => $this->server->format_datetime( $note->comment_date_gmt ),
'note' => $note->comment_content,
'customer_note' => get_comment_meta( $note->comment_ID, 'is_customer_note', true ) ? true : false,
);
return array( 'order_note' => apply_filters( 'woocommerce_api_order_note_response', $order_note, $id, $fields, $note, $order_id, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Create a new order note for the given order
*
* @since 2.2
* @param string $order_id order ID
* @param array $data raw request data
* @return WP_Error|array error or created note response data
*/
public function create_order_note( $order_id, $data ) {
try {
if ( ! isset( $data['order_note'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order_note' ), 400 );
}
$data = $data['order_note'];
// permission check
if ( ! current_user_can( 'publish_shop_orders' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_note', __( 'You do not have permission to create order notes', 'woocommerce' ), 401 );
}
$order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$order = wc_get_order( $order_id );
$data = apply_filters( 'woocommerce_api_create_order_note_data', $data, $order_id, $this );
// note content is required
if ( ! isset( $data['note'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note', __( 'Order note is required', 'woocommerce' ), 400 );
}
$is_customer_note = ( isset( $data['customer_note'] ) && true === $data['customer_note'] );
// create the note
$note_id = $order->add_order_note( $data['note'], $is_customer_note );
if ( ! $note_id ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_note', __( 'Cannot create order note, please try again', 'woocommerce' ), 500 );
}
// HTTP 201 Created
$this->server->send_status( 201 );
do_action( 'woocommerce_api_create_order_note', $note_id, $order_id, $this );
return $this->get_order_note( $order->id, $note_id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Edit the order note
*
* @since 2.2
* @param string $order_id order ID
* @param string $id note ID
* @param array $data parsed request data
* @return WP_Error|array error or edited note response data
*/
public function edit_order_note( $order_id, $id, $data ) {
try {
if ( ! isset( $data['order_note'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order_note' ), 400 );
}
$data = $data['order_note'];
// Validate order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$order = wc_get_order( $order_id );
// Validate note ID
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
}
// Ensure note ID is valid
$note = get_comment( $id );
if ( is_null( $note ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
}
// Ensure note ID is associated with given order
if ( $note->comment_post_ID != $order->id ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
}
$data = apply_filters( 'woocommerce_api_edit_order_note_data', $data, $note->comment_ID, $order->id, $this );
// Note content
if ( isset( $data['note'] ) ) {
wp_update_comment(
array(
'comment_ID' => $note->comment_ID,
'comment_content' => $data['note'],
)
);
}
// Customer note
if ( isset( $data['customer_note'] ) ) {
update_comment_meta( $note->comment_ID, 'is_customer_note', true === $data['customer_note'] ? 1 : 0 );
}
do_action( 'woocommerce_api_edit_order_note', $note->comment_ID, $order->id, $this );
return $this->get_order_note( $order->id, $note->comment_ID );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Delete order note
*
* @since 2.2
* @param string $order_id order ID
* @param string $id note ID
* @return WP_Error|array error or deleted message
*/
public function delete_order_note( $order_id, $id ) {
try {
$order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
// Validate note ID
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
}
// Ensure note ID is valid
$note = get_comment( $id );
if ( is_null( $note ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
}
// Ensure note ID is associated with given order
if ( $note->comment_post_ID != $order_id ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
}
// Force delete since trashed order notes could not be managed through comments list table
$result = wp_delete_comment( $note->comment_ID, true );
if ( ! $result ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_delete_order_note', __( 'This order note cannot be deleted', 'woocommerce' ), 500 );
}
do_action( 'woocommerce_api_delete_order_note', $note->comment_ID, $order_id, $this );
return array( 'message' => __( 'Permanently deleted order note', 'woocommerce' ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get the order refunds for an order
*
* @since 2.2
* @param string $order_id order ID
* @param string|null $fields fields to include in response
* @return array
*/
public function get_order_refunds( $order_id, $fields = null ) {
// Ensure ID is valid order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$refund_items = get_posts(
array(
'post_type' => 'shop_order_refund',
'post_parent' => $order_id,
'posts_per_page' => -1,
'post_status' => 'any',
'fields' => 'ids'
)
);
$order_refunds = array();
foreach ( $refund_items as $refund_id ) {
$order_refunds[] = current( $this->get_order_refund( $order_id, $refund_id, $fields ) );
}
return array( 'order_refunds' => apply_filters( 'woocommerce_api_order_refunds_response', $order_refunds, $order_id, $fields, $refund_items, $this ) );
}
/**
* Get an order refund for the given order ID and ID
*
* @since 2.2
* @param string $order_id order ID
* @param string|null $fields fields to limit response to
* @return array
*/
public function get_order_refund( $order_id, $id, $fields = null ) {
try {
// Validate order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID', 'woocommerce' ), 400 );
}
$order = wc_get_order( $id );
$refund = wc_get_order( $id );
if ( ! $refund ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found', 'woocommerce' ), 404 );
}
$line_items = array();
// Add line items
foreach ( $refund->get_items( 'line_item' ) as $item_id => $item ) {
$product = $order->get_product_from_item( $item );
$meta = new WC_Order_Item_Meta( $item, $product );
$item_meta = array();
foreach ( $meta->get_formatted() as $meta_key => $formatted_meta ) {
$item_meta[] = array(
'key' => $meta_key,
'label' => $formatted_meta['label'],
'value' => $formatted_meta['value'],
);
}
$line_items[] = array(
'id' => $item_id,
'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item ), 2 ),
'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], 2 ),
'total' => wc_format_decimal( $order->get_line_total( $item ), 2 ),
'total_tax' => wc_format_decimal( $order->get_line_tax( $item ), 2 ),
'price' => wc_format_decimal( $order->get_item_total( $item ), 2 ),
'quantity' => (int) $item['qty'],
'tax_class' => ( ! empty( $item['tax_class'] ) ) ? $item['tax_class'] : null,
'name' => $item['name'],
'product_id' => ( isset( $product->variation_id ) ) ? $product->variation_id : $product->id,
'sku' => is_object( $product ) ? $product->get_sku() : null,
'meta' => $item_meta,
);
}
$order_refund = array(
'id' => $refund->id,
'created_at' => $this->server->format_datetime( $refund->date ),
'amount' => wc_format_decimal( $refund->get_refund_amount(), 2 ),
'reason' => $refund->get_refund_reason(),
'line_items' => $line_items
);
return array( 'order_refund' => apply_filters( 'woocommerce_api_order_refund_response', $order_refund, $id, $fields, $refund, $order_id, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Create a new order refund for the given order
*
* @since 2.2
* @param string $order_id order ID
* @param array $data raw request data
* @param bool $api_refund do refund using a payment gateway API
* @return WP_Error|array error or created refund response data
*/
public function create_order_refund( $order_id, $data, $api_refund = true ) {
try {
if ( ! isset( $data['order_refund'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_refund_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order_refund' ), 400 );
}
$data = $data['order_refund'];
// Permission check
if ( ! current_user_can( 'publish_shop_orders' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_refund', __( 'You do not have permission to create order refunds', 'woocommerce' ), 401 );
}
$order_id = absint( $order_id );
if ( empty( $order_id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
}
$data = apply_filters( 'woocommerce_api_create_order_refund_data', $data, $order_id, $this );
// Refund amount is required
if ( ! isset( $data['amount'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund', __( 'Refund amount is required', 'woocommerce' ), 400 );
} elseif ( 0 > $data['amount'] ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund', __( 'Refund amount must be positive', 'woocommerce' ), 400 );
}
$data['order_id'] = $order_id;
$data['refund_id'] = 0;
// Create the refund
$refund = wc_create_refund( $data );
if ( ! $refund ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_refund', __( 'Cannot create order refund, please try again', 'woocommerce' ), 500 );
}
// Refund via API
if ( $api_refund ) {
if ( WC()->payment_gateways() ) {
$payment_gateways = WC()->payment_gateways->payment_gateways();
}
$order = wc_get_order( $order_id );
if ( isset( $payment_gateways[ $order->payment_method ] ) && $payment_gateways[ $order->payment_method ]->supports( 'refunds' ) ) {
$result = $payment_gateways[ $order->payment_method ]->process_refund( $order_id, $refund->get_refund_amount(), $refund->get_refund_reason() );
if ( is_wp_error( $result ) ) {
return $result;
} elseif ( ! $result ) {
throw new WC_API_Exception( 'woocommerce_api_create_order_refund_api_failed', __( 'An error occurred while attempting to create the refund using the payment gateway API', 'woocommerce' ), 500 );
}
}
}
// HTTP 201 Created
$this->server->send_status( 201 );
do_action( 'woocommerce_api_create_order_refund', $refund->id, $order_id, $this );
return $this->get_order_refund( $order_id, $refund->id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Edit an order refund
*
* @since 2.2
* @param string $order_id order ID
* @param string $id refund ID
* @param array $data parsed request data
* @return WP_Error|array error or edited refund response data
*/
public function edit_order_refund( $order_id, $id, $data ) {
try {
if ( ! isset( $data['order_refund'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_order_refund_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order_refund' ), 400 );
}
$data = $data['order_refund'];
// Validate order ID
$order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
// Validate refund ID
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID', 'woocommerce' ), 400 );
}
// Ensure order ID is valid
$refund = get_post( $id );
if ( ! $refund ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found', 'woocommerce' ), 404 );
}
// Ensure refund ID is associated with given order
if ( $refund->post_parent != $order_id ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'The order refund ID provided is not associated with the order', 'woocommerce' ), 400 );
}
$data = apply_filters( 'woocommerce_api_edit_order_refund_data', $data, $refund->ID, $order_id, $this );
// Update reason
if ( isset( $data['reason'] ) ) {
$updated_refund = wp_update_post( array( 'ID' => $refund->ID, 'post_excerpt' => $data['reason'] ) );
if ( is_wp_error( $updated_refund ) ) {
return $updated_refund;
}
}
// Update refund amount
if ( isset( $data['amount'] ) && 0 < $data['amount'] ) {
update_post_meta( $refund->ID, '_refund_amount', wc_format_decimal( $data['amount'] ) );
}
do_action( 'woocommerce_api_edit_order_refund', $refund->ID, $order_id, $this );
return $this->get_order_refund( $order_id, $refund->ID );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Delete order refund
*
* @since 2.2
* @param string $order_id order ID
* @param string $id refund ID
* @return WP_Error|array error or deleted message
*/
public function delete_order_refund( $order_id, $id ) {
try {
$order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
if ( is_wp_error( $order_id ) ) {
return $order_id;
}
// Validate refund ID
$id = absint( $id );
if ( empty( $id ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID', 'woocommerce' ), 400 );
}
// Ensure refund ID is valid
$refund = get_post( $id );
if ( ! $refund ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found', 'woocommerce' ), 404 );
}
// Ensure refund ID is associated with given order
if ( $refund->post_parent != $order_id ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'The order refund ID provided is not associated with the order', 'woocommerce' ), 400 );
}
wc_delete_shop_order_transients( $order_id );
do_action( 'woocommerce_api_delete_order_refund', $refund->ID, $order_id, $this );
return $this->delete( $refund->ID, 'refund', true );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Bulk update or insert orders
* Accepts an array with orders in the formats supported by
* WC_API_Orders->create_order() and WC_API_Orders->edit_order()
*
* @since 2.4.0
* @param array $data
* @return array
*/
public function bulk( $data ) {
try {
if ( ! isset( $data['orders'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_orders_data', sprintf( __( 'No %1$s data specified to create/edit %1$s', 'woocommerce' ), 'orders' ), 400 );
}
$data = $data['orders'];
$limit = apply_filters( 'woocommerce_api_bulk_limit', 100, 'orders' );
// Limit bulk operation
if ( count( $data ) > $limit ) {
throw new WC_API_Exception( 'woocommerce_api_orders_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request', 'woocommerce' ), $limit ), 413 );
}
$orders = array();
foreach ( $data as $_order ) {
$order_id = 0;
// Try to get the order ID
if ( isset( $_order['id'] ) ) {
$order_id = intval( $_order['id'] );
}
// Order exists / edit order
if ( $order_id ) {
$edit = $this->edit_order( $order_id, array( 'order' => $_order ) );
if ( is_wp_error( $edit ) ) {
$orders[] = array(
'id' => $order_id,
'error' => array( 'code' => $edit->get_error_code(), 'message' => $edit->get_error_message() )
);
} else {
$orders[] = $edit['order'];
}
}
// Order don't exists / create order
else {
$new = $this->create_order( array( 'order' => $_order ) );
if ( is_wp_error( $new ) ) {
$orders[] = array(
'id' => $order_id,
'error' => array( 'code' => $new->get_error_code(), 'message' => $new->get_error_message() )
);
} else {
$orders[] = $new['order'];
}
}
}
return array( 'orders' => apply_filters( 'woocommerce_api_orders_bulk_response', $orders, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
}
|
/*
* twl-common.c
*
* Copyright (C) 2011 Texas Instruments, Inc..
* Author: Peter Ujfalusi <peter.ujfalusi@ti.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/i2c.h>
#include <linux/i2c/twl.h>
#include <linux/gpio.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include "soc.h"
#include "twl-common.h"
#include "pm.h"
#include "voltage.h"
#include "mux.h"
static struct i2c_board_info __initdata pmic_i2c_board_info = {
.addr = 0x48,
.flags = I2C_CLIENT_WAKE,
};
#if defined(CONFIG_ARCH_OMAP3) || defined(CONFIG_ARCH_OMAP4)
static int twl_set_voltage(void *data, int target_uV)
{
struct voltagedomain *voltdm = (struct voltagedomain *)data;
return voltdm_scale(voltdm, target_uV);
}
static int twl_get_voltage(void *data)
{
struct voltagedomain *voltdm = (struct voltagedomain *)data;
return voltdm_get_voltage(voltdm);
}
#endif
void __init omap_pmic_init(int bus, u32 clkrate,
const char *pmic_type, int pmic_irq,
struct twl4030_platform_data *pmic_data)
{
omap_mux_init_signal("sys_nirq", OMAP_PIN_INPUT_PULLUP | OMAP_PIN_OFF_WAKEUPENABLE);
strncpy(pmic_i2c_board_info.type, pmic_type,
sizeof(pmic_i2c_board_info.type));
pmic_i2c_board_info.irq = pmic_irq;
pmic_i2c_board_info.platform_data = pmic_data;
omap_register_i2c_bus(bus, clkrate, &pmic_i2c_board_info, 1);
}
void __init omap4_pmic_init(const char *pmic_type,
struct twl4030_platform_data *pmic_data,
struct i2c_board_info *devices, int nr_devices)
{
/* PMIC part*/
omap_mux_init_signal("sys_nirq1", OMAP_PIN_INPUT_PULLUP | OMAP_PIN_OFF_WAKEUPENABLE);
omap_mux_init_signal("fref_clk0_out.sys_drm_msecure", OMAP_PIN_OUTPUT);
omap_pmic_init(1, 400, pmic_type, 7 + OMAP44XX_IRQ_GIC_START, pmic_data);
/* Register additional devices on i2c1 bus if needed */
if (devices)
i2c_register_board_info(1, devices, nr_devices);
}
void __init omap_pmic_late_init(void)
{
/* Init the OMAP TWL parameters (if PMIC has been registerd) */
if (!pmic_i2c_board_info.irq)
return;
omap3_twl_init();
omap4_twl_init();
}
#if defined(CONFIG_ARCH_OMAP3)
static struct twl4030_usb_data omap3_usb_pdata = {
.usb_mode = T2_USB_MODE_ULPI,
};
static int omap3_batt_table[] = {
/* 0 C */
30800, 29500, 28300, 27100,
26000, 24900, 23900, 22900, 22000, 21100, 20300, 19400, 18700, 17900,
17200, 16500, 15900, 15300, 14700, 14100, 13600, 13100, 12600, 12100,
11600, 11200, 10800, 10400, 10000, 9630, 9280, 8950, 8620, 8310,
8020, 7730, 7460, 7200, 6950, 6710, 6470, 6250, 6040, 5830,
5640, 5450, 5260, 5090, 4920, 4760, 4600, 4450, 4310, 4170,
4040, 3910, 3790, 3670, 3550
};
static struct twl4030_bci_platform_data omap3_bci_pdata = {
.battery_tmp_tbl = omap3_batt_table,
.tblsize = ARRAY_SIZE(omap3_batt_table),
};
static struct twl4030_madc_platform_data omap3_madc_pdata = {
.irq_line = 1,
};
static struct twl4030_codec_data omap3_codec;
static struct twl4030_audio_data omap3_audio_pdata = {
.audio_mclk = 26000000,
.codec = &omap3_codec,
};
static struct regulator_consumer_supply omap3_vdda_dac_supplies[] = {
REGULATOR_SUPPLY("vdda_dac", "omapdss_venc"),
};
static struct regulator_init_data omap3_vdac_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap3_vdda_dac_supplies),
.consumer_supplies = omap3_vdda_dac_supplies,
};
static struct regulator_consumer_supply omap3_vpll2_supplies[] = {
REGULATOR_SUPPLY("vdds_dsi", "omapdss"),
REGULATOR_SUPPLY("vdds_dsi", "omapdss_dsi.0"),
};
static struct regulator_init_data omap3_vpll2_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap3_vpll2_supplies),
.consumer_supplies = omap3_vpll2_supplies,
};
static struct regulator_consumer_supply omap3_vdd1_supply[] = {
REGULATOR_SUPPLY("vcc", "cpu0"),
};
static struct regulator_consumer_supply omap3_vdd2_supply[] = {
REGULATOR_SUPPLY("vcc", "l3_main.0"),
};
static struct regulator_init_data omap3_vdd1 = {
.constraints = {
.name = "vdd_mpu_iva",
.min_uV = 600000,
.max_uV = 1450000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(omap3_vdd1_supply),
.consumer_supplies = omap3_vdd1_supply,
};
static struct regulator_init_data omap3_vdd2 = {
.constraints = {
.name = "vdd_core",
.min_uV = 600000,
.max_uV = 1450000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(omap3_vdd2_supply),
.consumer_supplies = omap3_vdd2_supply,
};
static struct twl_regulator_driver_data omap3_vdd1_drvdata = {
.get_voltage = twl_get_voltage,
.set_voltage = twl_set_voltage,
};
static struct twl_regulator_driver_data omap3_vdd2_drvdata = {
.get_voltage = twl_get_voltage,
.set_voltage = twl_set_voltage,
};
void __init omap3_pmic_get_config(struct twl4030_platform_data *pmic_data,
u32 pdata_flags, u32 regulators_flags)
{
if (!pmic_data->vdd1) {
omap3_vdd1.driver_data = &omap3_vdd1_drvdata;
omap3_vdd1_drvdata.data = voltdm_lookup("mpu_iva");
pmic_data->vdd1 = &omap3_vdd1;
}
if (!pmic_data->vdd2) {
omap3_vdd2.driver_data = &omap3_vdd2_drvdata;
omap3_vdd2_drvdata.data = voltdm_lookup("core");
pmic_data->vdd2 = &omap3_vdd2;
}
/* Common platform data configurations */
if (pdata_flags & TWL_COMMON_PDATA_USB && !pmic_data->usb)
pmic_data->usb = &omap3_usb_pdata;
if (pdata_flags & TWL_COMMON_PDATA_BCI && !pmic_data->bci)
pmic_data->bci = &omap3_bci_pdata;
if (pdata_flags & TWL_COMMON_PDATA_MADC && !pmic_data->madc)
pmic_data->madc = &omap3_madc_pdata;
if (pdata_flags & TWL_COMMON_PDATA_AUDIO && !pmic_data->audio)
pmic_data->audio = &omap3_audio_pdata;
/* Common regulator configurations */
if (regulators_flags & TWL_COMMON_REGULATOR_VDAC && !pmic_data->vdac)
pmic_data->vdac = &omap3_vdac_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VPLL2 && !pmic_data->vpll2)
pmic_data->vpll2 = &omap3_vpll2_idata;
}
#endif /* CONFIG_ARCH_OMAP3 */
#if defined(CONFIG_ARCH_OMAP4)
static struct twl4030_usb_data omap4_usb_pdata = {
};
static struct regulator_consumer_supply omap4_vdda_hdmi_dac_supplies[] = {
REGULATOR_SUPPLY("vdda_hdmi_dac", "omapdss_hdmi"),
};
static struct regulator_init_data omap4_vdac_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vdda_hdmi_dac_supplies),
.consumer_supplies = omap4_vdda_hdmi_dac_supplies,
.supply_regulator = "V2V1",
};
static struct regulator_init_data omap4_vaux2_idata = {
.constraints = {
.min_uV = 1200000,
.max_uV = 2800000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_init_data omap4_vaux3_idata = {
.constraints = {
.min_uV = 1000000,
.max_uV = 3000000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_consumer_supply omap4_vmmc_supply[] = {
REGULATOR_SUPPLY("vmmc", "omap_hsmmc.0"),
};
/* VMMC1 for MMC1 card */
static struct regulator_init_data omap4_vmmc_idata = {
.constraints = {
.min_uV = 1200000,
.max_uV = 3000000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vmmc_supply),
.consumer_supplies = omap4_vmmc_supply,
};
static struct regulator_init_data omap4_vpp_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 2500000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_init_data omap4_vana_idata = {
.constraints = {
.min_uV = 2100000,
.max_uV = 2100000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_consumer_supply omap4_vcxio_supply[] = {
REGULATOR_SUPPLY("vdds_dsi", "omapdss_dss"),
REGULATOR_SUPPLY("vdds_dsi", "omapdss_dsi.0"),
REGULATOR_SUPPLY("vdds_dsi", "omapdss_dsi.1"),
};
static struct regulator_init_data omap4_vcxio_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
.always_on = true,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vcxio_supply),
.consumer_supplies = omap4_vcxio_supply,
.supply_regulator = "V2V1",
};
static struct regulator_init_data omap4_vusb_idata = {
.constraints = {
.min_uV = 3300000,
.max_uV = 3300000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_init_data omap4_clk32kg_idata = {
.constraints = {
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
};
static struct regulator_consumer_supply omap4_vdd1_supply[] = {
REGULATOR_SUPPLY("vcc", "cpu0"),
};
static struct regulator_consumer_supply omap4_vdd2_supply[] = {
REGULATOR_SUPPLY("vcc", "iva.0"),
};
static struct regulator_consumer_supply omap4_vdd3_supply[] = {
REGULATOR_SUPPLY("vcc", "l3_main.0"),
};
static struct regulator_init_data omap4_vdd1 = {
.constraints = {
.name = "vdd_mpu",
.min_uV = 500000,
.max_uV = 1500000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vdd1_supply),
.consumer_supplies = omap4_vdd1_supply,
};
static struct regulator_init_data omap4_vdd2 = {
.constraints = {
.name = "vdd_iva",
.min_uV = 500000,
.max_uV = 1500000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vdd2_supply),
.consumer_supplies = omap4_vdd2_supply,
};
static struct regulator_init_data omap4_vdd3 = {
.constraints = {
.name = "vdd_core",
.min_uV = 500000,
.max_uV = 1500000,
.valid_modes_mask = REGULATOR_MODE_NORMAL,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_vdd3_supply),
.consumer_supplies = omap4_vdd3_supply,
};
static struct twl_regulator_driver_data omap4_vdd1_drvdata = {
.get_voltage = twl_get_voltage,
.set_voltage = twl_set_voltage,
};
static struct twl_regulator_driver_data omap4_vdd2_drvdata = {
.get_voltage = twl_get_voltage,
.set_voltage = twl_set_voltage,
};
static struct twl_regulator_driver_data omap4_vdd3_drvdata = {
.get_voltage = twl_get_voltage,
.set_voltage = twl_set_voltage,
};
static struct regulator_consumer_supply omap4_v1v8_supply[] = {
REGULATOR_SUPPLY("vio", "1-004b"),
};
static struct regulator_init_data omap4_v1v8_idata = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
.always_on = true,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_v1v8_supply),
.consumer_supplies = omap4_v1v8_supply,
};
static struct regulator_consumer_supply omap4_v2v1_supply[] = {
REGULATOR_SUPPLY("v2v1", "1-004b"),
};
static struct regulator_init_data omap4_v2v1_idata = {
.constraints = {
.min_uV = 2100000,
.max_uV = 2100000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(omap4_v2v1_supply),
.consumer_supplies = omap4_v2v1_supply,
};
void __init omap4_pmic_get_config(struct twl4030_platform_data *pmic_data,
u32 pdata_flags, u32 regulators_flags)
{
if (!pmic_data->vdd1) {
omap4_vdd1.driver_data = &omap4_vdd1_drvdata;
omap4_vdd1_drvdata.data = voltdm_lookup("mpu");
pmic_data->vdd1 = &omap4_vdd1;
}
if (!pmic_data->vdd2) {
omap4_vdd2.driver_data = &omap4_vdd2_drvdata;
omap4_vdd2_drvdata.data = voltdm_lookup("iva");
pmic_data->vdd2 = &omap4_vdd2;
}
if (!pmic_data->vdd3) {
omap4_vdd3.driver_data = &omap4_vdd3_drvdata;
omap4_vdd3_drvdata.data = voltdm_lookup("core");
pmic_data->vdd3 = &omap4_vdd3;
}
/* Common platform data configurations */
if (pdata_flags & TWL_COMMON_PDATA_USB && !pmic_data->usb)
pmic_data->usb = &omap4_usb_pdata;
/* Common regulator configurations */
if (regulators_flags & TWL_COMMON_REGULATOR_VDAC && !pmic_data->vdac)
pmic_data->vdac = &omap4_vdac_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VAUX2 && !pmic_data->vaux2)
pmic_data->vaux2 = &omap4_vaux2_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VAUX3 && !pmic_data->vaux3)
pmic_data->vaux3 = &omap4_vaux3_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VMMC && !pmic_data->vmmc)
pmic_data->vmmc = &omap4_vmmc_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VPP && !pmic_data->vpp)
pmic_data->vpp = &omap4_vpp_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VANA && !pmic_data->vana)
pmic_data->vana = &omap4_vana_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VCXIO && !pmic_data->vcxio)
pmic_data->vcxio = &omap4_vcxio_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_VUSB && !pmic_data->vusb)
pmic_data->vusb = &omap4_vusb_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_CLK32KG &&
!pmic_data->clk32kg)
pmic_data->clk32kg = &omap4_clk32kg_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_V1V8 && !pmic_data->v1v8)
pmic_data->v1v8 = &omap4_v1v8_idata;
if (regulators_flags & TWL_COMMON_REGULATOR_V2V1 && !pmic_data->v2v1)
pmic_data->v2v1 = &omap4_v2v1_idata;
}
#endif /* CONFIG_ARCH_OMAP4 */
#if defined(CONFIG_SND_OMAP_SOC_OMAP_TWL4030) || \
defined(CONFIG_SND_OMAP_SOC_OMAP_TWL4030_MODULE)
#include <linux/platform_data/omap-twl4030.h>
static struct omap_tw4030_pdata omap_twl4030_audio_data;
static struct platform_device audio_device = {
.name = "omap-twl4030",
.id = -1,
.dev = {
.platform_data = &omap_twl4030_audio_data,
},
};
void __init omap_twl4030_audio_init(char *card_name)
{
omap_twl4030_audio_data.card_name = card_name;
platform_device_register(&audio_device);
}
#else /* SOC_OMAP_TWL4030 */
void __init omap_twl4030_audio_init(char *card_name)
{
return;
}
#endif /* SOC_OMAP_TWL4030 */
|
/* Key type used to cache DNS lookups made by the kernel
*
* See Documentation/networking/dns_resolver.txt
*
* Copyright (c) 2007 Igor Mammedov
* Author(s): Igor Mammedov (niallain@gmail.com)
* Steve French (sfrench@us.ibm.com)
* Wang Lei (wang840925@gmail.com)
* David Howells (dhowells@redhat.com)
*
* 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.1 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/keyctl.h>
#include <linux/err.h>
#include <linux/seq_file.h>
#include <keys/dns_resolver-type.h>
#include <keys/user-type.h>
#include "internal.h"
MODULE_DESCRIPTION("DNS Resolver");
MODULE_AUTHOR("Wang Lei");
MODULE_LICENSE("GPL");
unsigned int dns_resolver_debug;
module_param_named(debug, dns_resolver_debug, uint, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
const struct cred *dns_resolver_cache;
#define DNS_ERRORNO_OPTION "dnserror"
/*
* Preparse instantiation data for a dns_resolver key.
*
* The data must be a NUL-terminated string, with the NUL char accounted in
* datalen.
*
* If the data contains a '#' characters, then we take the clause after each
* one to be an option of the form 'key=value'. The actual data of interest is
* the string leading up to the first '#'. For instance:
*
* "ip1,ip2,...#foo=bar"
*/
static int
dns_resolver_preparse(struct key_preparsed_payload *prep)
{
struct user_key_payload *upayload;
unsigned long derrno;
int ret;
int datalen = prep->datalen, result_len = 0;
const char *data = prep->data, *end, *opt;
kenter("'%*.*s',%u", datalen, datalen, data, datalen);
if (datalen <= 1 || !data || data[datalen - 1] != '\0')
return -EINVAL;
datalen--;
/* deal with any options embedded in the data */
end = data + datalen;
opt = memchr(data, '#', datalen);
if (!opt) {
/* no options: the entire data is the result */
kdebug("no options");
result_len = datalen;
} else {
const char *next_opt;
result_len = opt - data;
opt++;
kdebug("options: '%s'", opt);
do {
const char *eq;
int opt_len, opt_nlen, opt_vlen, tmp;
next_opt = memchr(opt, '#', end - opt) ?: end;
opt_len = next_opt - opt;
if (!opt_len) {
printk(KERN_WARNING
"Empty option to dns_resolver key\n");
return -EINVAL;
}
eq = memchr(opt, '=', opt_len) ?: end;
opt_nlen = eq - opt;
eq++;
opt_vlen = next_opt - eq; /* will be -1 if no value */
tmp = opt_vlen >= 0 ? opt_vlen : 0;
kdebug("option '%*.*s' val '%*.*s'",
opt_nlen, opt_nlen, opt, tmp, tmp, eq);
/* see if it's an error number representing a DNS error
* that's to be recorded as the result in this key */
if (opt_nlen == sizeof(DNS_ERRORNO_OPTION) - 1 &&
memcmp(opt, DNS_ERRORNO_OPTION, opt_nlen) == 0) {
kdebug("dns error number option");
if (opt_vlen <= 0)
goto bad_option_value;
ret = kstrtoul(eq, 10, &derrno);
if (ret < 0)
goto bad_option_value;
if (derrno < 1 || derrno > 511)
goto bad_option_value;
kdebug("dns error no. = %lu", derrno);
prep->type_data[0] = ERR_PTR(-derrno);
continue;
}
bad_option_value:
printk(KERN_WARNING
"Option '%*.*s' to dns_resolver key:"
" bad/missing value\n",
opt_nlen, opt_nlen, opt);
return -EINVAL;
} while (opt = next_opt + 1, opt < end);
}
/* don't cache the result if we're caching an error saying there's no
* result */
if (prep->type_data[0]) {
kleave(" = 0 [h_error %ld]", PTR_ERR(prep->type_data[0]));
return 0;
}
kdebug("store result");
prep->quotalen = result_len;
upayload = kmalloc(sizeof(*upayload) + result_len + 1, GFP_KERNEL);
if (!upayload) {
kleave(" = -ENOMEM");
return -ENOMEM;
}
upayload->datalen = result_len;
memcpy(upayload->data, data, result_len);
upayload->data[result_len] = '\0';
prep->payload[0] = upayload;
kleave(" = 0");
return 0;
}
/*
* Clean up the preparse data
*/
static void dns_resolver_free_preparse(struct key_preparsed_payload *prep)
{
pr_devel("==>%s()\n", __func__);
kfree(prep->payload[0]);
}
/*
* The description is of the form "[<type>:]<domain_name>"
*
* The domain name may be a simple name or an absolute domain name (which
* should end with a period). The domain name is case-independent.
*/
static int
dns_resolver_match(const struct key *key, const void *description)
{
int slen, dlen, ret = 0;
const char *src = key->description, *dsp = description;
kenter("%s,%s", src, dsp);
if (!src || !dsp)
goto no_match;
if (strcasecmp(src, dsp) == 0)
goto matched;
slen = strlen(src);
dlen = strlen(dsp);
if (slen <= 0 || dlen <= 0)
goto no_match;
if (src[slen - 1] == '.')
slen--;
if (dsp[dlen - 1] == '.')
dlen--;
if (slen != dlen || strncasecmp(src, dsp, slen) != 0)
goto no_match;
matched:
ret = 1;
no_match:
kleave(" = %d", ret);
return ret;
}
/*
* Describe a DNS key
*/
static void dns_resolver_describe(const struct key *key, struct seq_file *m)
{
int err = key->type_data.x[0];
seq_puts(m, key->description);
if (key_is_instantiated(key)) {
if (err)
seq_printf(m, ": %d", err);
else
seq_printf(m, ": %u", key->datalen);
}
}
/*
* read the DNS data
* - the key's semaphore is read-locked
*/
static long dns_resolver_read(const struct key *key,
char __user *buffer, size_t buflen)
{
if (key->type_data.x[0])
return key->type_data.x[0];
return user_read(key, buffer, buflen);
}
struct key_type key_type_dns_resolver = {
.name = "dns_resolver",
.preparse = dns_resolver_preparse,
.free_preparse = dns_resolver_free_preparse,
.instantiate = generic_key_instantiate,
.match = dns_resolver_match,
.revoke = user_revoke,
.destroy = user_destroy,
.describe = dns_resolver_describe,
.read = dns_resolver_read,
};
static int __init init_dns_resolver(void)
{
struct cred *cred;
struct key *keyring;
int ret;
/* create an override credential set with a special thread keyring in
* which DNS requests are cached
*
* this is used to prevent malicious redirections from being installed
* with add_key().
*/
cred = prepare_kernel_cred(NULL);
if (!cred)
return -ENOMEM;
keyring = keyring_alloc(".dns_resolver",
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
(KEY_POS_ALL & ~KEY_POS_SETATTR) |
KEY_USR_VIEW | KEY_USR_READ,
KEY_ALLOC_NOT_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto failed_put_cred;
}
ret = register_key_type(&key_type_dns_resolver);
if (ret < 0)
goto failed_put_key;
/* instruct request_key() to use this special keyring as a cache for
* the results it looks up */
set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
cred->thread_keyring = keyring;
cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
dns_resolver_cache = cred;
kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
return 0;
failed_put_key:
key_put(keyring);
failed_put_cred:
put_cred(cred);
return ret;
}
static void __exit exit_dns_resolver(void)
{
key_revoke(dns_resolver_cache->thread_keyring);
unregister_key_type(&key_type_dns_resolver);
put_cred(dns_resolver_cache);
}
module_init(init_dns_resolver)
module_exit(exit_dns_resolver)
MODULE_LICENSE("GPL");
|
public class Foo {
{
int x = 0;
if (x == 0) {
<caret>
}
}
} |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Controller\Plugin;
use Zend\Stdlib\DispatchableInterface as Dispatchable;
interface PluginInterface
{
/**
* Set the current controller instance
*
* @param Dispatchable $controller
* @return void
*/
public function setController(Dispatchable $controller);
/**
* Get the current controller instance
*
* @return null|Dispatchable
*/
public function getController();
}
|
/* { dg-do compile } */
/* { dg-options "-O3 -ffast-math -fdump-tree-optimized" } */
float baz (float x, float y)
{
return x * x * x * x * y * y * y * y;
}
/* { dg-final { scan-tree-dump-times " \\* " 3 "optimized" } } */
/* { dg-final { cleanup-tree-dump "optimized" } } */
|
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by tools/gentest.py. -->
<title>OffscreenCanvas test: size.attributes.parse.percent</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/canvas-tests.js"></script>
<h1>size.attributes.parse.percent</h1>
<p class="desc">Parsing of non-negative integers</p>
<script>
var t = async_test("Parsing of non-negative integers");
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
offscreenCanvas.width = '100%';
offscreenCanvas.height = '100%';
_assertSame(offscreenCanvas.width, 100, "offscreenCanvas.width", "100");
_assertSame(offscreenCanvas.height, 100, "offscreenCanvas.height", "100");
t.done();
});
</script>
|
var config = require('../config'),
_ = require('underscore'),
path = require('path'),
when = require('when'),
api = require('../api'),
mailer = require('../mail'),
errors = require('../errorHandling'),
storage = require('../storage'),
updateCheck = require('../update-check'),
adminNavbar,
adminControllers,
loginSecurity = [];
// TODO: combine path/navClass to single "slug(?)" variable with no prefix
adminNavbar = {
content: {
name: 'Content',
navClass: 'content',
key: 'admin.navbar.content',
path: '/'
},
add: {
name: 'New Post',
navClass: 'editor',
key: 'admin.navbar.editor',
path: '/editor/'
},
settings: {
name: 'Settings',
navClass: 'settings',
key: 'admin.navbar.settings',
path: '/settings/'
}
};
// TODO: make this a util or helper
function setSelected(list, name) {
_.each(list, function (item, key) {
item.selected = key === name;
});
return list;
}
adminControllers = {
'uploader': function (req, res) {
var type = req.files.uploadimage.type,
ext = path.extname(req.files.uploadimage.name).toLowerCase(),
store = storage.get_storage();
if ((type !== 'image/jpeg' && type !== 'image/png' && type !== 'image/gif' && type !== 'image/svg+xml')
|| (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png' && ext !== '.gif' && ext !== '.svg' && ext !== '.svgz')) {
return res.send(415, 'Unsupported Media Type');
}
store
.save(req.files.uploadimage)
.then(function (url) {
return res.send(url);
})
.otherwise(function (e) {
errors.logError(e);
return res.send(500, e.message);
});
},
'login': function (req, res) {
/*jslint unparam:true*/
res.render('login', {
bodyClass: 'ghost-login',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'auth': function (req, res) {
var currentTime = process.hrtime()[0],
remoteAddress = req.connection.remoteAddress,
denied = '';
loginSecurity = _.filter(loginSecurity, function (ipTime) {
return (ipTime.time + 2 > currentTime);
});
denied = _.find(loginSecurity, function (ipTime) {
return (ipTime.ip === remoteAddress);
});
if (!denied) {
loginSecurity.push({ip: remoteAddress, time: currentTime});
api.users.check({email: req.body.email, pw: req.body.password}).then(function (user) {
req.session.regenerate(function (err) {
if (!err) {
req.session.user = user.id;
var redirect = config.paths().subdir + '/ghost/';
if (req.body.redirect) {
redirect += decodeURIComponent(req.body.redirect);
}
// If this IP address successfully logins we
// can remove it from the array of failed login attempts.
loginSecurity = _.reject(loginSecurity, function (ipTime) {
return ipTime.ip === remoteAddress;
});
res.json(200, {redirect: redirect});
}
});
}, function (error) {
res.json(401, {error: error.message});
});
} else {
res.json(401, {error: 'Slow down, there are way too many login attempts!'});
}
},
'changepw': function (req, res) {
return api.users.changePassword({
currentUser: req.session.user,
oldpw: req.body.password,
newpw: req.body.newpassword,
ne2pw: req.body.ne2password
}).then(function () {
res.json(200, {msg: 'Password changed successfully'});
}, function (error) {
res.send(401, {error: error.message});
});
},
'signup': function (req, res) {
/*jslint unparam:true*/
res.render('signup', {
bodyClass: 'ghost-signup',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'doRegister': function (req, res) {
var name = req.body.name,
email = req.body.email,
password = req.body.password;
api.users.add({
name: name,
email: email,
password: password
}).then(function (user) {
api.settings.edit('email', email).then(function () {
var message = {
to: email,
subject: 'Your New Ghost Blog',
html: '<p><strong>Hello!</strong></p>' +
'<p>Good news! You\'ve successfully created a brand new Ghost blog over on ' + config().url + '</p>' +
'<p>You can log in to your admin account with the following details:</p>' +
'<p> Email Address: ' + email + '<br>' +
'Password: The password you chose when you signed up</p>' +
'<p>Keep this email somewhere safe for future reference, and have fun!</p>' +
'<p>xoxo</p>' +
'<p>Team Ghost<br>' +
'<a href="https://ghost.org">https://ghost.org</a></p>'
};
mailer.send(message).otherwise(function (error) {
errors.logError(
error.message,
"Unable to send welcome email, your blog will continue to function.",
"Please see http://docs.ghost.org/mail/ for instructions on configuring email."
);
});
req.session.regenerate(function (err) {
if (!err) {
if (req.session.user === undefined) {
req.session.user = user.id;
}
res.json(200, {redirect: config.paths().subdir + '/ghost/'});
}
});
});
}).otherwise(function (error) {
res.json(401, {error: error.message});
});
},
'forgotten': function (req, res) {
/*jslint unparam:true*/
res.render('forgotten', {
bodyClass: 'ghost-forgotten',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'login')
});
},
'generateResetToken': function (req, res) {
var email = req.body.email;
api.users.generateResetToken(email).then(function (token) {
var siteLink = '<a href="' + config().url + '">' + config().url + '</a>',
resetUrl = config().url.replace(/\/$/, '') + '/ghost/reset/' + token + '/',
resetLink = '<a href="' + resetUrl + '">' + resetUrl + '</a>',
message = {
to: email,
subject: 'Reset Password',
html: '<p><strong>Hello!</strong></p>' +
'<p>A request has been made to reset the password on the site ' + siteLink + '.</p>' +
'<p>Please follow the link below to reset your password:<br><br>' + resetLink + '</p>' +
'<p>Ghost</p>'
};
return mailer.send(message);
}).then(function success() {
var notification = {
type: 'success',
message: 'Check your email for further instructions',
status: 'passive',
id: 'successresetpw'
};
return api.notifications.add(notification).then(function () {
res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'});
});
}, function failure(error) {
// TODO: This is kind of sketchy, depends on magic string error.message from Bookshelf.
// TODO: It's debatable whether we want to just tell the user we sent the email in this case or not, we are giving away sensitive info here.
if (error && error.message === 'EmptyResponse') {
error.message = "Invalid email address";
}
res.json(401, {error: error.message});
});
},
'reset': function (req, res) {
// Validate the request token
var token = req.params.token;
api.users.validateToken(token).then(function () {
// Render the reset form
res.render('reset', {
bodyClass: 'ghost-reset',
hideNavbar: true,
adminNav: setSelected(adminNavbar, 'reset')
});
}).otherwise(function (err) {
// Redirect to forgotten if invalid token
var notification = {
type: 'error',
message: 'Invalid or expired token',
status: 'persistent',
id: 'errorinvalidtoken'
};
errors.logError(err, 'admin.js', "Please check the provided token for validity and expiration.");
return api.notifications.add(notification).then(function () {
res.redirect(config.paths().subdir + '/ghost/forgotten');
});
});
},
'resetPassword': function (req, res) {
var token = req.params.token,
newPassword = req.param('newpassword'),
ne2Password = req.param('ne2password');
api.users.resetPassword(token, newPassword, ne2Password).then(function () {
var notification = {
type: 'success',
message: 'Password changed successfully.',
status: 'passive',
id: 'successresetpw'
};
return api.notifications.add(notification).then(function () {
res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'});
});
}).otherwise(function (err) {
// TODO: Better error message if we can tell whether the passwords didn't match or something
res.json(401, {error: err.message});
});
},
'logout': function (req, res) {
req.session.destroy();
var notification = {
type: 'success',
message: 'You were successfully signed out',
status: 'passive',
id: 'successlogout'
};
return api.notifications.add(notification).then(function () {
res.redirect(config.paths().subdir + '/ghost/signin/');
});
},
'index': function (req, res) {
/*jslint unparam:true*/
function renderIndex() {
res.render('content', {
bodyClass: 'manage',
adminNav: setSelected(adminNavbar, 'content')
});
}
when.join(
updateCheck(res),
when(renderIndex())
// an error here should just get logged
).otherwise(errors.logError);
},
'editor': function (req, res) {
if (req.params.id !== undefined) {
res.render('editor', {
bodyClass: 'editor',
adminNav: setSelected(adminNavbar, 'content')
});
} else {
res.render('editor', {
bodyClass: 'editor',
adminNav: setSelected(adminNavbar, 'add')
});
}
},
'content': function (req, res) {
/*jslint unparam:true*/
res.render('content', {
bodyClass: 'manage',
adminNav: setSelected(adminNavbar, 'content')
});
},
'settings': function (req, res, next) {
// TODO: Centralise list/enumeration of settings panes, so we don't
// run into trouble in future.
var allowedSections = ['', 'general', 'user'],
section = req.url.replace(/(^\/ghost\/settings[\/]*|\/$)/ig, '');
if (allowedSections.indexOf(section) < 0) {
return next();
}
res.render('settings', {
bodyClass: 'settings',
adminNav: setSelected(adminNavbar, 'settings')
});
},
'debug': { /* ugly temporary stuff for managing the app before it's properly finished */
index: function (req, res) {
/*jslint unparam:true*/
res.render('debug', {
bodyClass: 'settings',
adminNav: setSelected(adminNavbar, 'settings')
});
}
}
};
module.exports = adminControllers;
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __CUTILS_UEVENT_H
#define __CUTILS_UEVENT_H
#include <stdbool.h>
#include <sys/socket.h>
#ifdef __cplusplus
extern "C" {
#endif
int uevent_open_socket(int buf_sz, bool passcred);
ssize_t uevent_kernel_multicast_recv(int socket, void *buffer, size_t length);
ssize_t uevent_kernel_multicast_uid_recv(int socket, void *buffer, size_t length, uid_t *uid);
#ifdef __cplusplus
}
#endif
#endif /* __CUTILS_UEVENT_H */
|
#ifndef BOOST_INTRUSIVE_PTR_HPP_INCLUDED
#define BOOST_INTRUSIVE_PTR_HPP_INCLUDED
//
// intrusive_ptr.hpp
//
// Copyright (c) 2001, 2002 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://www.boost.org/libs/smart_ptr/ for documentation.
//
#include <boost/smart_ptr/intrusive_ptr.hpp>
#endif // #ifndef BOOST_INTRUSIVE_PTR_HPP_INCLUDED
|
describe("Ext.dom.Element_scroll", function() {
var el;
afterEach(function(){
Ext.destroy(el);
el = null;
});
function expectLeft(left) {
expect(el.dom.scrollLeft).toBe(left);
}
function expectTop(top) {
expect(el.dom.scrollTop).toBe(top);
}
function expectLeftTop(left, top) {
expectLeft(left);
expectTop(top);
}
describe("scroll", function() {
var scrollSize = Ext.getScrollbarSize(),
maxHorz = 600 + scrollSize.width,
maxVert = 600 + scrollSize.height;
beforeEach(function(){
el = Ext.getBody().createChild({
style: {
width: '400px',
height: '400px',
overflow: 'auto'
},
cn: [{
style: {
width: '1000px',
height: '1000px'
}
}]
});
});
describe("right", function(){
it("should accept 'right' as a param", function(){
el.scroll('right', 200);
expectLeft(200);
});
it("should accept 'r' as a param", function(){
el.scroll('r', 175);
expectLeft(175);
});
it("should append to the current position", function(){
el.scroll('r', 200);
el.scroll('r', 300);
expectLeft(500);
});
it("should constrain the max scroll", function(){
el.scroll('r', 2000);
expectLeft(maxHorz);
});
});
describe("left", function(){
it("should accept 'left' as a param", function(){
el.scroll('r', 200);
el.scroll('left', 125);
expectLeft(75);
});
it("should accept 'l' as a param", function(){
el.scroll('r', 300);
el.scroll('l', 150);
expectLeft(150);
});
it("should append to the current position", function(){
el.scroll('r', 500);
el.scroll('l', 300);
el.scroll('l', 100);
expectLeft(100);
});
it("should constrain to 0", function(){
el.scroll('r', 100);
el.scroll('l', 350);
expectLeft(0);
});
});
describe("bottom", function(){
it("should accept 'bottom' as a param", function() {
el.scroll('bottom', 30);
expectTop(30);
});
it("should accept 'b' as a param", function() {
el.scroll('b', 120);
expectTop(120);
});
it("should accept 'down' as a param", function() {
el.scroll('down', 30);
expectTop(30);
});
it("should accept 'd' as a param", function() {
el.scroll('d', 375);
expectTop(375);
});
it("should append to the current position", function() {
el.scroll('b', 120);
el.scroll('b', 130);
expectTop(250);
});
it("should constrain the max scroll", function(){
el.scroll('b', 1500);
expectTop(maxVert);
});
});
describe("up", function(){
it("should accept 'up' as a param", function() {
el.scroll('b', 30);
el.scroll('u', 10);
expectTop(20);
});
it("should accept 'u' as a param", function() {
el.scroll('b', 120);
el.scroll('u', 50);
expectTop(70);
});
it("should accept 'top' as a param", function() {
el.scroll('b', 200);
el.scroll('top', 130);
expectTop(70);
});
it("should accept 't' as a param", function() {
el.scroll('b', 500);
el.scroll('t', 375);
expectTop(125);
});
it("should append to the current position", function() {
el.scroll('b', 300);
el.scroll('t', 120);
el.scroll('t', 130);
expectTop(50);
});
it("should constrain the max scroll", function() {
el.scroll('b', 300);
el.scroll('t', 3000);
expectTop(0);
});
});
});
});
|
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package replicationcontroller
import (
"strings"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/kubernetes/pkg/api/legacyscheme"
apitesting "k8s.io/kubernetes/pkg/api/testing"
api "k8s.io/kubernetes/pkg/apis/core"
// install all api groups for testing
_ "k8s.io/kubernetes/pkg/api/testapi"
)
func TestControllerStrategy(t *testing.T) {
ctx := genericapirequest.NewDefaultContext()
if !Strategy.NamespaceScoped() {
t.Errorf("ReplicationController must be namespace scoped")
}
if Strategy.AllowCreateOnUpdate() {
t.Errorf("ReplicationController should not allow create on update")
}
validSelector := map[string]string{"a": "b"}
validPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: validSelector,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}},
},
},
}
rc := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
Spec: api.ReplicationControllerSpec{
Selector: validSelector,
Template: &validPodTemplate.Template,
},
Status: api.ReplicationControllerStatus{
Replicas: 1,
ObservedGeneration: int64(10),
},
}
Strategy.PrepareForCreate(ctx, rc)
if rc.Status.Replicas != 0 {
t.Error("ReplicationController should not allow setting status.replicas on create")
}
if rc.Status.ObservedGeneration != int64(0) {
t.Error("ReplicationController should not allow setting status.observedGeneration on create")
}
errs := Strategy.Validate(ctx, rc)
if len(errs) != 0 {
t.Errorf("Unexpected error validating %v", errs)
}
invalidRc := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{Name: "bar", ResourceVersion: "4"},
}
Strategy.PrepareForUpdate(ctx, invalidRc, rc)
errs = Strategy.ValidateUpdate(ctx, invalidRc, rc)
if len(errs) == 0 {
t.Errorf("Expected a validation error")
}
if invalidRc.ResourceVersion != "4" {
t.Errorf("Incoming resource version on update should not be mutated")
}
}
func TestControllerStatusStrategy(t *testing.T) {
ctx := genericapirequest.NewDefaultContext()
if !StatusStrategy.NamespaceScoped() {
t.Errorf("ReplicationController must be namespace scoped")
}
if StatusStrategy.AllowCreateOnUpdate() {
t.Errorf("ReplicationController should not allow create on update")
}
validSelector := map[string]string{"a": "b"}
validPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: validSelector,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
},
},
}
oldController := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault, ResourceVersion: "10"},
Spec: api.ReplicationControllerSpec{
Replicas: 3,
Selector: validSelector,
Template: &validPodTemplate.Template,
},
Status: api.ReplicationControllerStatus{
Replicas: 1,
ObservedGeneration: int64(10),
},
}
newController := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault, ResourceVersion: "9"},
Spec: api.ReplicationControllerSpec{
Replicas: 1,
Selector: validSelector,
Template: &validPodTemplate.Template,
},
Status: api.ReplicationControllerStatus{
Replicas: 3,
ObservedGeneration: int64(11),
},
}
StatusStrategy.PrepareForUpdate(ctx, newController, oldController)
if newController.Status.Replicas != 3 {
t.Errorf("Replication controller status updates should allow change of replicas: %v", newController.Status.Replicas)
}
if newController.Spec.Replicas != 3 {
t.Errorf("PrepareForUpdate should have preferred spec")
}
errs := StatusStrategy.ValidateUpdate(ctx, newController, oldController)
if len(errs) != 0 {
t.Errorf("Unexpected error %v", errs)
}
}
func TestSelectableFieldLabelConversions(t *testing.T) {
apitesting.TestSelectableFieldLabelConversionsOfKind(t,
legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion.String(),
"ReplicationController",
ControllerToSelectableFields(&api.ReplicationController{}),
nil,
)
}
func TestValidateUpdate(t *testing.T) {
ctx := genericapirequest.NewDefaultContext()
validSelector := map[string]string{"a": "b"}
validPodTemplate := api.PodTemplate{
Template: api.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: validSelector,
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyAlways,
DNSPolicy: api.DNSClusterFirst,
Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
},
},
}
oldController := &api.ReplicationController{
ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault, ResourceVersion: "10", Annotations: make(map[string]string)},
Spec: api.ReplicationControllerSpec{
Replicas: 3,
Selector: validSelector,
Template: &validPodTemplate.Template,
},
Status: api.ReplicationControllerStatus{
Replicas: 1,
ObservedGeneration: int64(10),
},
}
// Conversion sets this annotation
oldController.Annotations[api.NonConvertibleAnnotationPrefix+"/"+"spec.selector"] = "no way"
// Deep-copy so we won't mutate both selectors.
newController := oldController.DeepCopy()
// Irrelevant (to the selector) update for the replication controller.
newController.Spec.Replicas = 5
// If they didn't try to update the selector then we should not return any error.
errs := Strategy.ValidateUpdate(ctx, newController, oldController)
if len(errs) > 0 {
t.Fatalf("unexpected errors: %v", errs)
}
// Update the selector - validation should return an error.
newController.Spec.Selector["shiny"] = "newlabel"
newController.Spec.Template.Labels["shiny"] = "newlabel"
errs = Strategy.ValidateUpdate(ctx, newController, oldController)
for _, err := range errs {
t.Logf("%#v\n", err)
}
if len(errs) != 1 {
t.Fatalf("expected a validation error")
}
if !strings.Contains(errs[0].Error(), "selector") {
t.Fatalf("expected error related to the selector")
}
}
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'wsc', 'km', {
btnIgnore: 'មិនផ្លាស់ប្តូរ',
btnIgnoreAll: 'មិនផ្លាស់ប្តូរ ទាំងអស់',
btnReplace: 'ជំនួស',
btnReplaceAll: 'ជំនួសទាំងអស់',
btnUndo: 'សារឡើងវិញ',
changeTo: 'ផ្លាស់ប្តូរទៅ',
errorLoading: 'Error loading application service host: %s.',
ieSpellDownload: 'ពុំមានកម្មវិធីពិនិត្យអក្ខរាវិរុទ្ធ ។ តើចង់ទាញយកពីណា?',
manyChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: %1 ពាក្យបានផ្លាស់ប្តូរ',
noChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពុំមានផ្លាស់ប្តូរ',
noMispell: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: គ្មានកំហុស',
noSuggestions: '- គ្មានសំណើរ -',
notAvailable: 'Sorry, but service is unavailable now.',
notInDic: 'គ្មានក្នុងវចនានុក្រម',
oneChange: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពាក្យមួយត្រូចបានផ្លាស់ប្តូរ',
progress: 'កំពុងពិនិត្យអក្ខរាវិរុទ្ធ...',
title: 'Spell Checker',
toolbar: 'ពិនិត្យអក្ខរាវិរុទ្ធ'
});
|
/*
* linux/fs/ext2/balloc.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* Enhanced block allocation by Stephen Tweedie (sct@redhat.com), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include "ext2.h"
#include <linux/quotaops.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/cred.h>
#include <linux/buffer_head.h>
#include <linux/capability.h>
/*
* balloc.c contains the blocks allocation and deallocation routines
*/
/*
* The free blocks are managed by bitmaps. A file system contains several
* blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap
* block for inodes, N blocks for the inode table and data blocks.
*
* The file system contains group descriptors which are located after the
* super block. Each descriptor contains the number of the bitmap block and
* the free blocks count in the block. The descriptors are loaded in memory
* when a file system is mounted (see ext2_fill_super).
*/
#define in_range(b, first, len) ((b) >= (first) && (b) <= (first) + (len) - 1)
struct ext2_group_desc * ext2_get_group_desc(struct super_block * sb,
unsigned int block_group,
struct buffer_head ** bh)
{
unsigned long group_desc;
unsigned long offset;
struct ext2_group_desc * desc;
struct ext2_sb_info *sbi = EXT2_SB(sb);
if (block_group >= sbi->s_groups_count) {
ext2_error (sb, "ext2_get_group_desc",
"block_group >= groups_count - "
"block_group = %d, groups_count = %lu",
block_group, sbi->s_groups_count);
return NULL;
}
group_desc = block_group >> EXT2_DESC_PER_BLOCK_BITS(sb);
offset = block_group & (EXT2_DESC_PER_BLOCK(sb) - 1);
if (!sbi->s_group_desc[group_desc]) {
ext2_error (sb, "ext2_get_group_desc",
"Group descriptor not loaded - "
"block_group = %d, group_desc = %lu, desc = %lu",
block_group, group_desc, offset);
return NULL;
}
desc = (struct ext2_group_desc *) sbi->s_group_desc[group_desc]->b_data;
if (bh)
*bh = sbi->s_group_desc[group_desc];
return desc + offset;
}
static int ext2_valid_block_bitmap(struct super_block *sb,
struct ext2_group_desc *desc,
unsigned int block_group,
struct buffer_head *bh)
{
ext2_grpblk_t offset;
ext2_grpblk_t next_zero_bit;
ext2_fsblk_t bitmap_blk;
ext2_fsblk_t group_first_block;
group_first_block = ext2_group_first_block_no(sb, block_group);
/* check whether block bitmap block number is set */
bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
offset = bitmap_blk - group_first_block;
if (!ext2_test_bit(offset, bh->b_data))
/* bad block bitmap */
goto err_out;
/* check whether the inode bitmap block number is set */
bitmap_blk = le32_to_cpu(desc->bg_inode_bitmap);
offset = bitmap_blk - group_first_block;
if (!ext2_test_bit(offset, bh->b_data))
/* bad block bitmap */
goto err_out;
/* check whether the inode table block number is set */
bitmap_blk = le32_to_cpu(desc->bg_inode_table);
offset = bitmap_blk - group_first_block;
next_zero_bit = ext2_find_next_zero_bit(bh->b_data,
offset + EXT2_SB(sb)->s_itb_per_group,
offset);
if (next_zero_bit >= offset + EXT2_SB(sb)->s_itb_per_group)
/* good bitmap for inode tables */
return 1;
err_out:
ext2_error(sb, __func__,
"Invalid block bitmap - "
"block_group = %d, block = %lu",
block_group, bitmap_blk);
return 0;
}
/*
* Read the bitmap for a given block_group,and validate the
* bits for block/inode/inode tables are set in the bitmaps
*
* Return buffer_head on success or NULL in case of failure.
*/
static struct buffer_head *
read_block_bitmap(struct super_block *sb, unsigned int block_group)
{
struct ext2_group_desc * desc;
struct buffer_head * bh = NULL;
ext2_fsblk_t bitmap_blk;
desc = ext2_get_group_desc(sb, block_group, NULL);
if (!desc)
return NULL;
bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
bh = sb_getblk(sb, bitmap_blk);
if (unlikely(!bh)) {
ext2_error(sb, __func__,
"Cannot read block bitmap - "
"block_group = %d, block_bitmap = %u",
block_group, le32_to_cpu(desc->bg_block_bitmap));
return NULL;
}
if (likely(bh_uptodate_or_lock(bh)))
return bh;
if (bh_submit_read(bh) < 0) {
brelse(bh);
ext2_error(sb, __func__,
"Cannot read block bitmap - "
"block_group = %d, block_bitmap = %u",
block_group, le32_to_cpu(desc->bg_block_bitmap));
return NULL;
}
ext2_valid_block_bitmap(sb, desc, block_group, bh);
/*
* file system mounted not to panic on error, continue with corrupt
* bitmap
*/
return bh;
}
static void group_adjust_blocks(struct super_block *sb, int group_no,
struct ext2_group_desc *desc, struct buffer_head *bh, int count)
{
if (count) {
struct ext2_sb_info *sbi = EXT2_SB(sb);
unsigned free_blocks;
spin_lock(sb_bgl_lock(sbi, group_no));
free_blocks = le16_to_cpu(desc->bg_free_blocks_count);
desc->bg_free_blocks_count = cpu_to_le16(free_blocks + count);
spin_unlock(sb_bgl_lock(sbi, group_no));
mark_buffer_dirty(bh);
}
}
/*
* The reservation window structure operations
* --------------------------------------------
* Operations include:
* dump, find, add, remove, is_empty, find_next_reservable_window, etc.
*
* We use a red-black tree to represent per-filesystem reservation
* windows.
*
*/
/**
* __rsv_window_dump() -- Dump the filesystem block allocation reservation map
* @rb_root: root of per-filesystem reservation rb tree
* @verbose: verbose mode
* @fn: function which wishes to dump the reservation map
*
* If verbose is turned on, it will print the whole block reservation
* windows(start, end). Otherwise, it will only print out the "bad" windows,
* those windows that overlap with their immediate neighbors.
*/
#if 1
static void __rsv_window_dump(struct rb_root *root, int verbose,
const char *fn)
{
struct rb_node *n;
struct ext2_reserve_window_node *rsv, *prev;
int bad;
restart:
n = rb_first(root);
bad = 0;
prev = NULL;
printk("Block Allocation Reservation Windows Map (%s):\n", fn);
while (n) {
rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
if (verbose)
printk("reservation window 0x%p "
"start: %lu, end: %lu\n",
rsv, rsv->rsv_start, rsv->rsv_end);
if (rsv->rsv_start && rsv->rsv_start >= rsv->rsv_end) {
printk("Bad reservation %p (start >= end)\n",
rsv);
bad = 1;
}
if (prev && prev->rsv_end >= rsv->rsv_start) {
printk("Bad reservation %p (prev->end >= start)\n",
rsv);
bad = 1;
}
if (bad) {
if (!verbose) {
printk("Restarting reservation walk in verbose mode\n");
verbose = 1;
goto restart;
}
}
n = rb_next(n);
prev = rsv;
}
printk("Window map complete.\n");
BUG_ON(bad);
}
#define rsv_window_dump(root, verbose) \
__rsv_window_dump((root), (verbose), __func__)
#else
#define rsv_window_dump(root, verbose) do {} while (0)
#endif
/**
* goal_in_my_reservation()
* @rsv: inode's reservation window
* @grp_goal: given goal block relative to the allocation block group
* @group: the current allocation block group
* @sb: filesystem super block
*
* Test if the given goal block (group relative) is within the file's
* own block reservation window range.
*
* If the reservation window is outside the goal allocation group, return 0;
* grp_goal (given goal block) could be -1, which means no specific
* goal block. In this case, always return 1.
* If the goal block is within the reservation window, return 1;
* otherwise, return 0;
*/
static int
goal_in_my_reservation(struct ext2_reserve_window *rsv, ext2_grpblk_t grp_goal,
unsigned int group, struct super_block * sb)
{
ext2_fsblk_t group_first_block, group_last_block;
group_first_block = ext2_group_first_block_no(sb, group);
group_last_block = group_first_block + EXT2_BLOCKS_PER_GROUP(sb) - 1;
if ((rsv->_rsv_start > group_last_block) ||
(rsv->_rsv_end < group_first_block))
return 0;
if ((grp_goal >= 0) && ((grp_goal + group_first_block < rsv->_rsv_start)
|| (grp_goal + group_first_block > rsv->_rsv_end)))
return 0;
return 1;
}
/**
* search_reserve_window()
* @rb_root: root of reservation tree
* @goal: target allocation block
*
* Find the reserved window which includes the goal, or the previous one
* if the goal is not in any window.
* Returns NULL if there are no windows or if all windows start after the goal.
*/
static struct ext2_reserve_window_node *
search_reserve_window(struct rb_root *root, ext2_fsblk_t goal)
{
struct rb_node *n = root->rb_node;
struct ext2_reserve_window_node *rsv;
if (!n)
return NULL;
do {
rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
if (goal < rsv->rsv_start)
n = n->rb_left;
else if (goal > rsv->rsv_end)
n = n->rb_right;
else
return rsv;
} while (n);
/*
* We've fallen off the end of the tree: the goal wasn't inside
* any particular node. OK, the previous node must be to one
* side of the interval containing the goal. If it's the RHS,
* we need to back up one.
*/
if (rsv->rsv_start > goal) {
n = rb_prev(&rsv->rsv_node);
rsv = rb_entry(n, struct ext2_reserve_window_node, rsv_node);
}
return rsv;
}
/*
* ext2_rsv_window_add() -- Insert a window to the block reservation rb tree.
* @sb: super block
* @rsv: reservation window to add
*
* Must be called with rsv_lock held.
*/
void ext2_rsv_window_add(struct super_block *sb,
struct ext2_reserve_window_node *rsv)
{
struct rb_root *root = &EXT2_SB(sb)->s_rsv_window_root;
struct rb_node *node = &rsv->rsv_node;
ext2_fsblk_t start = rsv->rsv_start;
struct rb_node ** p = &root->rb_node;
struct rb_node * parent = NULL;
struct ext2_reserve_window_node *this;
while (*p)
{
parent = *p;
this = rb_entry(parent, struct ext2_reserve_window_node, rsv_node);
if (start < this->rsv_start)
p = &(*p)->rb_left;
else if (start > this->rsv_end)
p = &(*p)->rb_right;
else {
rsv_window_dump(root, 1);
BUG();
}
}
rb_link_node(node, parent, p);
rb_insert_color(node, root);
}
/**
* rsv_window_remove() -- unlink a window from the reservation rb tree
* @sb: super block
* @rsv: reservation window to remove
*
* Mark the block reservation window as not allocated, and unlink it
* from the filesystem reservation window rb tree. Must be called with
* rsv_lock held.
*/
static void rsv_window_remove(struct super_block *sb,
struct ext2_reserve_window_node *rsv)
{
rsv->rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_alloc_hit = 0;
rb_erase(&rsv->rsv_node, &EXT2_SB(sb)->s_rsv_window_root);
}
/*
* rsv_is_empty() -- Check if the reservation window is allocated.
* @rsv: given reservation window to check
*
* returns 1 if the end block is EXT2_RESERVE_WINDOW_NOT_ALLOCATED.
*/
static inline int rsv_is_empty(struct ext2_reserve_window *rsv)
{
/* a valid reservation end block could not be 0 */
return (rsv->_rsv_end == EXT2_RESERVE_WINDOW_NOT_ALLOCATED);
}
/**
* ext2_init_block_alloc_info()
* @inode: file inode structure
*
* Allocate and initialize the reservation window structure, and
* link the window to the ext2 inode structure at last
*
* The reservation window structure is only dynamically allocated
* and linked to ext2 inode the first time the open file
* needs a new block. So, before every ext2_new_block(s) call, for
* regular files, we should check whether the reservation window
* structure exists or not. In the latter case, this function is called.
* Fail to do so will result in block reservation being turned off for that
* open file.
*
* This function is called from ext2_get_blocks_handle(), also called
* when setting the reservation window size through ioctl before the file
* is open for write (needs block allocation).
*
* Needs truncate_mutex protection prior to calling this function.
*/
void ext2_init_block_alloc_info(struct inode *inode)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct ext2_block_alloc_info *block_i;
struct super_block *sb = inode->i_sb;
block_i = kmalloc(sizeof(*block_i), GFP_NOFS);
if (block_i) {
struct ext2_reserve_window_node *rsv = &block_i->rsv_window_node;
rsv->rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
/*
* if filesystem is mounted with NORESERVATION, the goal
* reservation window size is set to zero to indicate
* block reservation is off
*/
if (!test_opt(sb, RESERVATION))
rsv->rsv_goal_size = 0;
else
rsv->rsv_goal_size = EXT2_DEFAULT_RESERVE_BLOCKS;
rsv->rsv_alloc_hit = 0;
block_i->last_alloc_logical_block = 0;
block_i->last_alloc_physical_block = 0;
}
ei->i_block_alloc_info = block_i;
}
/**
* ext2_discard_reservation()
* @inode: inode
*
* Discard(free) block reservation window on last file close, or truncate
* or at last iput().
*
* It is being called in three cases:
* ext2_release_file(): last writer closes the file
* ext2_clear_inode(): last iput(), when nobody links to this file.
* ext2_truncate(): when the block indirect map is about to change.
*/
void ext2_discard_reservation(struct inode *inode)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct ext2_block_alloc_info *block_i = ei->i_block_alloc_info;
struct ext2_reserve_window_node *rsv;
spinlock_t *rsv_lock = &EXT2_SB(inode->i_sb)->s_rsv_window_lock;
if (!block_i)
return;
rsv = &block_i->rsv_window_node;
if (!rsv_is_empty(&rsv->rsv_window)) {
spin_lock(rsv_lock);
if (!rsv_is_empty(&rsv->rsv_window))
rsv_window_remove(inode->i_sb, rsv);
spin_unlock(rsv_lock);
}
}
/**
* ext2_free_blocks() -- Free given blocks and update quota and i_blocks
* @inode: inode
* @block: start physical block to free
* @count: number of blocks to free
*/
void ext2_free_blocks (struct inode * inode, unsigned long block,
unsigned long count)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head * bh2;
unsigned long block_group;
unsigned long bit;
unsigned long i;
unsigned long overflow;
struct super_block * sb = inode->i_sb;
struct ext2_sb_info * sbi = EXT2_SB(sb);
struct ext2_group_desc * desc;
struct ext2_super_block * es = sbi->s_es;
unsigned freed = 0, group_freed;
if (block < le32_to_cpu(es->s_first_data_block) ||
block + count < block ||
block + count > le32_to_cpu(es->s_blocks_count)) {
ext2_error (sb, "ext2_free_blocks",
"Freeing blocks not in datazone - "
"block = %lu, count = %lu", block, count);
goto error_return;
}
ext2_debug ("freeing block(s) %lu-%lu\n", block, block + count - 1);
do_more:
overflow = 0;
block_group = (block - le32_to_cpu(es->s_first_data_block)) /
EXT2_BLOCKS_PER_GROUP(sb);
bit = (block - le32_to_cpu(es->s_first_data_block)) %
EXT2_BLOCKS_PER_GROUP(sb);
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (bit + count > EXT2_BLOCKS_PER_GROUP(sb)) {
overflow = bit + count - EXT2_BLOCKS_PER_GROUP(sb);
count -= overflow;
}
brelse(bitmap_bh);
bitmap_bh = read_block_bitmap(sb, block_group);
if (!bitmap_bh)
goto error_return;
desc = ext2_get_group_desc (sb, block_group, &bh2);
if (!desc)
goto error_return;
if (in_range (le32_to_cpu(desc->bg_block_bitmap), block, count) ||
in_range (le32_to_cpu(desc->bg_inode_bitmap), block, count) ||
in_range (block, le32_to_cpu(desc->bg_inode_table),
sbi->s_itb_per_group) ||
in_range (block + count - 1, le32_to_cpu(desc->bg_inode_table),
sbi->s_itb_per_group)) {
ext2_error (sb, "ext2_free_blocks",
"Freeing blocks in system zones - "
"Block = %lu, count = %lu",
block, count);
goto error_return;
}
for (i = 0, group_freed = 0; i < count; i++) {
if (!ext2_clear_bit_atomic(sb_bgl_lock(sbi, block_group),
bit + i, bitmap_bh->b_data)) {
ext2_error(sb, __func__,
"bit already cleared for block %lu", block + i);
} else {
group_freed++;
}
}
mark_buffer_dirty(bitmap_bh);
if (sb->s_flags & MS_SYNCHRONOUS)
sync_dirty_buffer(bitmap_bh);
group_adjust_blocks(sb, block_group, desc, bh2, group_freed);
freed += group_freed;
if (overflow) {
block += count;
count = overflow;
goto do_more;
}
error_return:
brelse(bitmap_bh);
if (freed) {
percpu_counter_add(&sbi->s_freeblocks_counter, freed);
dquot_free_block_nodirty(inode, freed);
mark_inode_dirty(inode);
}
}
/**
* bitmap_search_next_usable_block()
* @start: the starting block (group relative) of the search
* @bh: bufferhead contains the block group bitmap
* @maxblocks: the ending block (group relative) of the reservation
*
* The bitmap search --- search forward through the actual bitmap on disk until
* we find a bit free.
*/
static ext2_grpblk_t
bitmap_search_next_usable_block(ext2_grpblk_t start, struct buffer_head *bh,
ext2_grpblk_t maxblocks)
{
ext2_grpblk_t next;
next = ext2_find_next_zero_bit(bh->b_data, maxblocks, start);
if (next >= maxblocks)
return -1;
return next;
}
/**
* find_next_usable_block()
* @start: the starting block (group relative) to find next
* allocatable block in bitmap.
* @bh: bufferhead contains the block group bitmap
* @maxblocks: the ending block (group relative) for the search
*
* Find an allocatable block in a bitmap. We perform the "most
* appropriate allocation" algorithm of looking for a free block near
* the initial goal; then for a free byte somewhere in the bitmap;
* then for any free bit in the bitmap.
*/
static ext2_grpblk_t
find_next_usable_block(int start, struct buffer_head *bh, int maxblocks)
{
ext2_grpblk_t here, next;
char *p, *r;
if (start > 0) {
/*
* The goal was occupied; search forward for a free
* block within the next XX blocks.
*
* end_goal is more or less random, but it has to be
* less than EXT2_BLOCKS_PER_GROUP. Aligning up to the
* next 64-bit boundary is simple..
*/
ext2_grpblk_t end_goal = (start + 63) & ~63;
if (end_goal > maxblocks)
end_goal = maxblocks;
here = ext2_find_next_zero_bit(bh->b_data, end_goal, start);
if (here < end_goal)
return here;
ext2_debug("Bit not found near goal\n");
}
here = start;
if (here < 0)
here = 0;
p = ((char *)bh->b_data) + (here >> 3);
r = memscan(p, 0, ((maxblocks + 7) >> 3) - (here >> 3));
next = (r - ((char *)bh->b_data)) << 3;
if (next < maxblocks && next >= here)
return next;
here = bitmap_search_next_usable_block(here, bh, maxblocks);
return here;
}
/**
* ext2_try_to_allocate()
* @sb: superblock
* @group: given allocation block group
* @bitmap_bh: bufferhead holds the block bitmap
* @grp_goal: given target block within the group
* @count: target number of blocks to allocate
* @my_rsv: reservation window
*
* Attempt to allocate blocks within a give range. Set the range of allocation
* first, then find the first free bit(s) from the bitmap (within the range),
* and at last, allocate the blocks by claiming the found free bit as allocated.
*
* To set the range of this allocation:
* if there is a reservation window, only try to allocate block(s)
* from the file's own reservation window;
* Otherwise, the allocation range starts from the give goal block,
* ends at the block group's last block.
*
* If we failed to allocate the desired block then we may end up crossing to a
* new bitmap.
*/
static int
ext2_try_to_allocate(struct super_block *sb, int group,
struct buffer_head *bitmap_bh, ext2_grpblk_t grp_goal,
unsigned long *count,
struct ext2_reserve_window *my_rsv)
{
ext2_fsblk_t group_first_block;
ext2_grpblk_t start, end;
unsigned long num = 0;
/* we do allocation within the reservation window if we have a window */
if (my_rsv) {
group_first_block = ext2_group_first_block_no(sb, group);
if (my_rsv->_rsv_start >= group_first_block)
start = my_rsv->_rsv_start - group_first_block;
else
/* reservation window cross group boundary */
start = 0;
end = my_rsv->_rsv_end - group_first_block + 1;
if (end > EXT2_BLOCKS_PER_GROUP(sb))
/* reservation window crosses group boundary */
end = EXT2_BLOCKS_PER_GROUP(sb);
if ((start <= grp_goal) && (grp_goal < end))
start = grp_goal;
else
grp_goal = -1;
} else {
if (grp_goal > 0)
start = grp_goal;
else
start = 0;
end = EXT2_BLOCKS_PER_GROUP(sb);
}
BUG_ON(start > EXT2_BLOCKS_PER_GROUP(sb));
repeat:
if (grp_goal < 0) {
grp_goal = find_next_usable_block(start, bitmap_bh, end);
if (grp_goal < 0)
goto fail_access;
if (!my_rsv) {
int i;
for (i = 0; i < 7 && grp_goal > start &&
!ext2_test_bit(grp_goal - 1,
bitmap_bh->b_data);
i++, grp_goal--)
;
}
}
start = grp_goal;
if (ext2_set_bit_atomic(sb_bgl_lock(EXT2_SB(sb), group), grp_goal,
bitmap_bh->b_data)) {
/*
* The block was allocated by another thread, or it was
* allocated and then freed by another thread
*/
start++;
grp_goal++;
if (start >= end)
goto fail_access;
goto repeat;
}
num++;
grp_goal++;
while (num < *count && grp_goal < end
&& !ext2_set_bit_atomic(sb_bgl_lock(EXT2_SB(sb), group),
grp_goal, bitmap_bh->b_data)) {
num++;
grp_goal++;
}
*count = num;
return grp_goal - num;
fail_access:
*count = num;
return -1;
}
/**
* find_next_reservable_window():
* find a reservable space within the given range.
* It does not allocate the reservation window for now:
* alloc_new_reservation() will do the work later.
*
* @search_head: the head of the searching list;
* This is not necessarily the list head of the whole filesystem
*
* We have both head and start_block to assist the search
* for the reservable space. The list starts from head,
* but we will shift to the place where start_block is,
* then start from there, when looking for a reservable space.
*
* @size: the target new reservation window size
*
* @group_first_block: the first block we consider to start
* the real search from
*
* @last_block:
* the maximum block number that our goal reservable space
* could start from. This is normally the last block in this
* group. The search will end when we found the start of next
* possible reservable space is out of this boundary.
* This could handle the cross boundary reservation window
* request.
*
* basically we search from the given range, rather than the whole
* reservation double linked list, (start_block, last_block)
* to find a free region that is of my size and has not
* been reserved.
*
*/
static int find_next_reservable_window(
struct ext2_reserve_window_node *search_head,
struct ext2_reserve_window_node *my_rsv,
struct super_block * sb,
ext2_fsblk_t start_block,
ext2_fsblk_t last_block)
{
struct rb_node *next;
struct ext2_reserve_window_node *rsv, *prev;
ext2_fsblk_t cur;
int size = my_rsv->rsv_goal_size;
/* TODO: make the start of the reservation window byte-aligned */
/* cur = *start_block & ~7;*/
cur = start_block;
rsv = search_head;
if (!rsv)
return -1;
while (1) {
if (cur <= rsv->rsv_end)
cur = rsv->rsv_end + 1;
/* TODO?
* in the case we could not find a reservable space
* that is what is expected, during the re-search, we could
* remember what's the largest reservable space we could have
* and return that one.
*
* For now it will fail if we could not find the reservable
* space with expected-size (or more)...
*/
if (cur > last_block)
return -1; /* fail */
prev = rsv;
next = rb_next(&rsv->rsv_node);
rsv = rb_entry(next,struct ext2_reserve_window_node,rsv_node);
/*
* Reached the last reservation, we can just append to the
* previous one.
*/
if (!next)
break;
if (cur + size <= rsv->rsv_start) {
/*
* Found a reserveable space big enough. We could
* have a reservation across the group boundary here
*/
break;
}
}
/*
* we come here either :
* when we reach the end of the whole list,
* and there is empty reservable space after last entry in the list.
* append it to the end of the list.
*
* or we found one reservable space in the middle of the list,
* return the reservation window that we could append to.
* succeed.
*/
if ((prev != my_rsv) && (!rsv_is_empty(&my_rsv->rsv_window)))
rsv_window_remove(sb, my_rsv);
/*
* Let's book the whole available window for now. We will check the
* disk bitmap later and then, if there are free blocks then we adjust
* the window size if it's larger than requested.
* Otherwise, we will remove this node from the tree next time
* call find_next_reservable_window.
*/
my_rsv->rsv_start = cur;
my_rsv->rsv_end = cur + size - 1;
my_rsv->rsv_alloc_hit = 0;
if (prev != my_rsv)
ext2_rsv_window_add(sb, my_rsv);
return 0;
}
/**
* alloc_new_reservation()--allocate a new reservation window
*
* To make a new reservation, we search part of the filesystem
* reservation list (the list that inside the group). We try to
* allocate a new reservation window near the allocation goal,
* or the beginning of the group, if there is no goal.
*
* We first find a reservable space after the goal, then from
* there, we check the bitmap for the first free block after
* it. If there is no free block until the end of group, then the
* whole group is full, we failed. Otherwise, check if the free
* block is inside the expected reservable space, if so, we
* succeed.
* If the first free block is outside the reservable space, then
* start from the first free block, we search for next available
* space, and go on.
*
* on succeed, a new reservation will be found and inserted into the list
* It contains at least one free block, and it does not overlap with other
* reservation windows.
*
* failed: we failed to find a reservation window in this group
*
* @rsv: the reservation
*
* @grp_goal: The goal (group-relative). It is where the search for a
* free reservable space should start from.
* if we have a goal(goal >0 ), then start from there,
* no goal(goal = -1), we start from the first block
* of the group.
*
* @sb: the super block
* @group: the group we are trying to allocate in
* @bitmap_bh: the block group block bitmap
*
*/
static int alloc_new_reservation(struct ext2_reserve_window_node *my_rsv,
ext2_grpblk_t grp_goal, struct super_block *sb,
unsigned int group, struct buffer_head *bitmap_bh)
{
struct ext2_reserve_window_node *search_head;
ext2_fsblk_t group_first_block, group_end_block, start_block;
ext2_grpblk_t first_free_block;
struct rb_root *fs_rsv_root = &EXT2_SB(sb)->s_rsv_window_root;
unsigned long size;
int ret;
spinlock_t *rsv_lock = &EXT2_SB(sb)->s_rsv_window_lock;
group_first_block = ext2_group_first_block_no(sb, group);
group_end_block = group_first_block + (EXT2_BLOCKS_PER_GROUP(sb) - 1);
if (grp_goal < 0)
start_block = group_first_block;
else
start_block = grp_goal + group_first_block;
size = my_rsv->rsv_goal_size;
if (!rsv_is_empty(&my_rsv->rsv_window)) {
/*
* if the old reservation is cross group boundary
* and if the goal is inside the old reservation window,
* we will come here when we just failed to allocate from
* the first part of the window. We still have another part
* that belongs to the next group. In this case, there is no
* point to discard our window and try to allocate a new one
* in this group(which will fail). we should
* keep the reservation window, just simply move on.
*
* Maybe we could shift the start block of the reservation
* window to the first block of next group.
*/
if ((my_rsv->rsv_start <= group_end_block) &&
(my_rsv->rsv_end > group_end_block) &&
(start_block >= my_rsv->rsv_start))
return -1;
if ((my_rsv->rsv_alloc_hit >
(my_rsv->rsv_end - my_rsv->rsv_start + 1) / 2)) {
/*
* if the previously allocation hit ratio is
* greater than 1/2, then we double the size of
* the reservation window the next time,
* otherwise we keep the same size window
*/
size = size * 2;
if (size > EXT2_MAX_RESERVE_BLOCKS)
size = EXT2_MAX_RESERVE_BLOCKS;
my_rsv->rsv_goal_size= size;
}
}
spin_lock(rsv_lock);
/*
* shift the search start to the window near the goal block
*/
search_head = search_reserve_window(fs_rsv_root, start_block);
/*
* find_next_reservable_window() simply finds a reservable window
* inside the given range(start_block, group_end_block).
*
* To make sure the reservation window has a free bit inside it, we
* need to check the bitmap after we found a reservable window.
*/
retry:
ret = find_next_reservable_window(search_head, my_rsv, sb,
start_block, group_end_block);
if (ret == -1) {
if (!rsv_is_empty(&my_rsv->rsv_window))
rsv_window_remove(sb, my_rsv);
spin_unlock(rsv_lock);
return -1;
}
/*
* On success, find_next_reservable_window() returns the
* reservation window where there is a reservable space after it.
* Before we reserve this reservable space, we need
* to make sure there is at least a free block inside this region.
*
* Search the first free bit on the block bitmap. Search starts from
* the start block of the reservable space we just found.
*/
spin_unlock(rsv_lock);
first_free_block = bitmap_search_next_usable_block(
my_rsv->rsv_start - group_first_block,
bitmap_bh, group_end_block - group_first_block + 1);
if (first_free_block < 0) {
/*
* no free block left on the bitmap, no point
* to reserve the space. return failed.
*/
spin_lock(rsv_lock);
if (!rsv_is_empty(&my_rsv->rsv_window))
rsv_window_remove(sb, my_rsv);
spin_unlock(rsv_lock);
return -1; /* failed */
}
start_block = first_free_block + group_first_block;
/*
* check if the first free block is within the
* free space we just reserved
*/
if (start_block >= my_rsv->rsv_start && start_block <= my_rsv->rsv_end)
return 0; /* success */
/*
* if the first free bit we found is out of the reservable space
* continue search for next reservable space,
* start from where the free block is,
* we also shift the list head to where we stopped last time
*/
search_head = my_rsv;
spin_lock(rsv_lock);
goto retry;
}
/**
* try_to_extend_reservation()
* @my_rsv: given reservation window
* @sb: super block
* @size: the delta to extend
*
* Attempt to expand the reservation window large enough to have
* required number of free blocks
*
* Since ext2_try_to_allocate() will always allocate blocks within
* the reservation window range, if the window size is too small,
* multiple blocks allocation has to stop at the end of the reservation
* window. To make this more efficient, given the total number of
* blocks needed and the current size of the window, we try to
* expand the reservation window size if necessary on a best-effort
* basis before ext2_new_blocks() tries to allocate blocks.
*/
static void try_to_extend_reservation(struct ext2_reserve_window_node *my_rsv,
struct super_block *sb, int size)
{
struct ext2_reserve_window_node *next_rsv;
struct rb_node *next;
spinlock_t *rsv_lock = &EXT2_SB(sb)->s_rsv_window_lock;
if (!spin_trylock(rsv_lock))
return;
next = rb_next(&my_rsv->rsv_node);
if (!next)
my_rsv->rsv_end += size;
else {
next_rsv = rb_entry(next, struct ext2_reserve_window_node, rsv_node);
if ((next_rsv->rsv_start - my_rsv->rsv_end - 1) >= size)
my_rsv->rsv_end += size;
else
my_rsv->rsv_end = next_rsv->rsv_start - 1;
}
spin_unlock(rsv_lock);
}
/**
* ext2_try_to_allocate_with_rsv()
* @sb: superblock
* @group: given allocation block group
* @bitmap_bh: bufferhead holds the block bitmap
* @grp_goal: given target block within the group
* @count: target number of blocks to allocate
* @my_rsv: reservation window
*
* This is the main function used to allocate a new block and its reservation
* window.
*
* Each time when a new block allocation is need, first try to allocate from
* its own reservation. If it does not have a reservation window, instead of
* looking for a free bit on bitmap first, then look up the reservation list to
* see if it is inside somebody else's reservation window, we try to allocate a
* reservation window for it starting from the goal first. Then do the block
* allocation within the reservation window.
*
* This will avoid keeping on searching the reservation list again and
* again when somebody is looking for a free block (without
* reservation), and there are lots of free blocks, but they are all
* being reserved.
*
* We use a red-black tree for the per-filesystem reservation list.
*/
static ext2_grpblk_t
ext2_try_to_allocate_with_rsv(struct super_block *sb, unsigned int group,
struct buffer_head *bitmap_bh, ext2_grpblk_t grp_goal,
struct ext2_reserve_window_node * my_rsv,
unsigned long *count)
{
ext2_fsblk_t group_first_block, group_last_block;
ext2_grpblk_t ret = 0;
unsigned long num = *count;
/*
* we don't deal with reservation when
* filesystem is mounted without reservation
* or the file is not a regular file
* or last attempt to allocate a block with reservation turned on failed
*/
if (my_rsv == NULL) {
return ext2_try_to_allocate(sb, group, bitmap_bh,
grp_goal, count, NULL);
}
/*
* grp_goal is a group relative block number (if there is a goal)
* 0 <= grp_goal < EXT2_BLOCKS_PER_GROUP(sb)
* first block is a filesystem wide block number
* first block is the block number of the first block in this group
*/
group_first_block = ext2_group_first_block_no(sb, group);
group_last_block = group_first_block + (EXT2_BLOCKS_PER_GROUP(sb) - 1);
/*
* Basically we will allocate a new block from inode's reservation
* window.
*
* We need to allocate a new reservation window, if:
* a) inode does not have a reservation window; or
* b) last attempt to allocate a block from existing reservation
* failed; or
* c) we come here with a goal and with a reservation window
*
* We do not need to allocate a new reservation window if we come here
* at the beginning with a goal and the goal is inside the window, or
* we don't have a goal but already have a reservation window.
* then we could go to allocate from the reservation window directly.
*/
while (1) {
if (rsv_is_empty(&my_rsv->rsv_window) || (ret < 0) ||
!goal_in_my_reservation(&my_rsv->rsv_window,
grp_goal, group, sb)) {
if (my_rsv->rsv_goal_size < *count)
my_rsv->rsv_goal_size = *count;
ret = alloc_new_reservation(my_rsv, grp_goal, sb,
group, bitmap_bh);
if (ret < 0)
break; /* failed */
if (!goal_in_my_reservation(&my_rsv->rsv_window,
grp_goal, group, sb))
grp_goal = -1;
} else if (grp_goal >= 0) {
int curr = my_rsv->rsv_end -
(grp_goal + group_first_block) + 1;
if (curr < *count)
try_to_extend_reservation(my_rsv, sb,
*count - curr);
}
if ((my_rsv->rsv_start > group_last_block) ||
(my_rsv->rsv_end < group_first_block)) {
rsv_window_dump(&EXT2_SB(sb)->s_rsv_window_root, 1);
BUG();
}
ret = ext2_try_to_allocate(sb, group, bitmap_bh, grp_goal,
&num, &my_rsv->rsv_window);
if (ret >= 0) {
my_rsv->rsv_alloc_hit += num;
*count = num;
break; /* succeed */
}
num = *count;
}
return ret;
}
/**
* ext2_has_free_blocks()
* @sbi: in-core super block structure.
*
* Check if filesystem has at least 1 free block available for allocation.
*/
static int ext2_has_free_blocks(struct ext2_sb_info *sbi)
{
ext2_fsblk_t free_blocks, root_blocks;
free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
root_blocks = le32_to_cpu(sbi->s_es->s_r_blocks_count);
if (free_blocks < root_blocks + 1 && !capable(CAP_SYS_RESOURCE) &&
!uid_eq(sbi->s_resuid, current_fsuid()) &&
(gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) ||
!in_group_p (sbi->s_resgid))) {
return 0;
}
return 1;
}
/*
* Returns 1 if the passed-in block region is valid; 0 if some part overlaps
* with filesystem metadata blocksi.
*/
int ext2_data_block_valid(struct ext2_sb_info *sbi, ext2_fsblk_t start_blk,
unsigned int count)
{
if ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(start_blk + count < start_blk) ||
(start_blk > le32_to_cpu(sbi->s_es->s_blocks_count)))
return 0;
/* Ensure we do not step over superblock */
if ((start_blk <= sbi->s_sb_block) &&
(start_blk + count >= sbi->s_sb_block))
return 0;
return 1;
}
/*
* ext2_new_blocks() -- core block(s) allocation function
* @inode: file inode
* @goal: given target block(filesystem wide)
* @count: target number of blocks to allocate
* @errp: error code
*
* ext2_new_blocks uses a goal block to assist allocation. If the goal is
* free, or there is a free block within 32 blocks of the goal, that block
* is allocated. Otherwise a forward search is made for a free block; within
* each block group the search first looks for an entire free byte in the block
* bitmap, and then for any free bit if that fails.
* This function also updates quota and i_blocks field.
*/
ext2_fsblk_t ext2_new_blocks(struct inode *inode, ext2_fsblk_t goal,
unsigned long *count, int *errp)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *gdp_bh;
int group_no;
int goal_group;
ext2_grpblk_t grp_target_blk; /* blockgroup relative goal block */
ext2_grpblk_t grp_alloc_blk; /* blockgroup-relative allocated block*/
ext2_fsblk_t ret_block; /* filesyetem-wide allocated block */
int bgi; /* blockgroup iteration index */
int performed_allocation = 0;
ext2_grpblk_t free_blocks; /* number of free blocks in a group */
struct super_block *sb;
struct ext2_group_desc *gdp;
struct ext2_super_block *es;
struct ext2_sb_info *sbi;
struct ext2_reserve_window_node *my_rsv = NULL;
struct ext2_block_alloc_info *block_i;
unsigned short windowsz = 0;
unsigned long ngroups;
unsigned long num = *count;
int ret;
*errp = -ENOSPC;
sb = inode->i_sb;
/*
* Check quota for allocation of this block.
*/
ret = dquot_alloc_block(inode, num);
if (ret) {
*errp = ret;
return 0;
}
sbi = EXT2_SB(sb);
es = EXT2_SB(sb)->s_es;
ext2_debug("goal=%lu.\n", goal);
/*
* Allocate a block from reservation only when
* filesystem is mounted with reservation(default,-o reservation), and
* it's a regular file, and
* the desired window size is greater than 0 (One could use ioctl
* command EXT2_IOC_SETRSVSZ to set the window size to 0 to turn off
* reservation on that particular file)
*/
block_i = EXT2_I(inode)->i_block_alloc_info;
if (block_i) {
windowsz = block_i->rsv_window_node.rsv_goal_size;
if (windowsz > 0)
my_rsv = &block_i->rsv_window_node;
}
if (!ext2_has_free_blocks(sbi)) {
*errp = -ENOSPC;
goto out;
}
/*
* First, test whether the goal block is free.
*/
if (goal < le32_to_cpu(es->s_first_data_block) ||
goal >= le32_to_cpu(es->s_blocks_count))
goal = le32_to_cpu(es->s_first_data_block);
group_no = (goal - le32_to_cpu(es->s_first_data_block)) /
EXT2_BLOCKS_PER_GROUP(sb);
goal_group = group_no;
retry_alloc:
gdp = ext2_get_group_desc(sb, group_no, &gdp_bh);
if (!gdp)
goto io_error;
free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
/*
* if there is not enough free blocks to make a new resevation
* turn off reservation for this allocation
*/
if (my_rsv && (free_blocks < windowsz)
&& (free_blocks > 0)
&& (rsv_is_empty(&my_rsv->rsv_window)))
my_rsv = NULL;
if (free_blocks > 0) {
grp_target_blk = ((goal - le32_to_cpu(es->s_first_data_block)) %
EXT2_BLOCKS_PER_GROUP(sb));
bitmap_bh = read_block_bitmap(sb, group_no);
if (!bitmap_bh)
goto io_error;
grp_alloc_blk = ext2_try_to_allocate_with_rsv(sb, group_no,
bitmap_bh, grp_target_blk,
my_rsv, &num);
if (grp_alloc_blk >= 0)
goto allocated;
}
ngroups = EXT2_SB(sb)->s_groups_count;
smp_rmb();
/*
* Now search the rest of the groups. We assume that
* group_no and gdp correctly point to the last group visited.
*/
for (bgi = 0; bgi < ngroups; bgi++) {
group_no++;
if (group_no >= ngroups)
group_no = 0;
gdp = ext2_get_group_desc(sb, group_no, &gdp_bh);
if (!gdp)
goto io_error;
free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
/*
* skip this group (and avoid loading bitmap) if there
* are no free blocks
*/
if (!free_blocks)
continue;
/*
* skip this group if the number of
* free blocks is less than half of the reservation
* window size.
*/
if (my_rsv && (free_blocks <= (windowsz/2)))
continue;
brelse(bitmap_bh);
bitmap_bh = read_block_bitmap(sb, group_no);
if (!bitmap_bh)
goto io_error;
/*
* try to allocate block(s) from this group, without a goal(-1).
*/
grp_alloc_blk = ext2_try_to_allocate_with_rsv(sb, group_no,
bitmap_bh, -1, my_rsv, &num);
if (grp_alloc_blk >= 0)
goto allocated;
}
/*
* We may end up a bogus earlier ENOSPC error due to
* filesystem is "full" of reservations, but
* there maybe indeed free blocks available on disk
* In this case, we just forget about the reservations
* just do block allocation as without reservations.
*/
if (my_rsv) {
my_rsv = NULL;
windowsz = 0;
group_no = goal_group;
goto retry_alloc;
}
/* No space left on the device */
*errp = -ENOSPC;
goto out;
allocated:
ext2_debug("using block group %d(%d)\n",
group_no, gdp->bg_free_blocks_count);
ret_block = grp_alloc_blk + ext2_group_first_block_no(sb, group_no);
if (in_range(le32_to_cpu(gdp->bg_block_bitmap), ret_block, num) ||
in_range(le32_to_cpu(gdp->bg_inode_bitmap), ret_block, num) ||
in_range(ret_block, le32_to_cpu(gdp->bg_inode_table),
EXT2_SB(sb)->s_itb_per_group) ||
in_range(ret_block + num - 1, le32_to_cpu(gdp->bg_inode_table),
EXT2_SB(sb)->s_itb_per_group)) {
ext2_error(sb, "ext2_new_blocks",
"Allocating block in system zone - "
"blocks from "E2FSBLK", length %lu",
ret_block, num);
/*
* ext2_try_to_allocate marked the blocks we allocated as in
* use. So we may want to selectively mark some of the blocks
* as free
*/
goto retry_alloc;
}
performed_allocation = 1;
if (ret_block + num - 1 >= le32_to_cpu(es->s_blocks_count)) {
ext2_error(sb, "ext2_new_blocks",
"block("E2FSBLK") >= blocks count(%d) - "
"block_group = %d, es == %p ", ret_block,
le32_to_cpu(es->s_blocks_count), group_no, es);
goto out;
}
group_adjust_blocks(sb, group_no, gdp, gdp_bh, -num);
percpu_counter_sub(&sbi->s_freeblocks_counter, num);
mark_buffer_dirty(bitmap_bh);
if (sb->s_flags & MS_SYNCHRONOUS)
sync_dirty_buffer(bitmap_bh);
*errp = 0;
brelse(bitmap_bh);
if (num < *count) {
dquot_free_block_nodirty(inode, *count-num);
mark_inode_dirty(inode);
*count = num;
}
return ret_block;
io_error:
*errp = -EIO;
out:
/*
* Undo the block allocation
*/
if (!performed_allocation) {
dquot_free_block_nodirty(inode, *count);
mark_inode_dirty(inode);
}
brelse(bitmap_bh);
return 0;
}
ext2_fsblk_t ext2_new_block(struct inode *inode, unsigned long goal, int *errp)
{
unsigned long count = 1;
return ext2_new_blocks(inode, goal, &count, errp);
}
#ifdef EXT2FS_DEBUG
unsigned long ext2_count_free(struct buffer_head *map, unsigned int numchars)
{
return numchars * BITS_PER_BYTE - memweight(map->b_data, numchars);
}
#endif /* EXT2FS_DEBUG */
unsigned long ext2_count_free_blocks (struct super_block * sb)
{
struct ext2_group_desc * desc;
unsigned long desc_count = 0;
int i;
#ifdef EXT2FS_DEBUG
unsigned long bitmap_count, x;
struct ext2_super_block *es;
es = EXT2_SB(sb)->s_es;
desc_count = 0;
bitmap_count = 0;
desc = NULL;
for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
struct buffer_head *bitmap_bh;
desc = ext2_get_group_desc (sb, i, NULL);
if (!desc)
continue;
desc_count += le16_to_cpu(desc->bg_free_blocks_count);
bitmap_bh = read_block_bitmap(sb, i);
if (!bitmap_bh)
continue;
x = ext2_count_free(bitmap_bh, sb->s_blocksize);
printk ("group %d: stored = %d, counted = %lu\n",
i, le16_to_cpu(desc->bg_free_blocks_count), x);
bitmap_count += x;
brelse(bitmap_bh);
}
printk("ext2_count_free_blocks: stored = %lu, computed = %lu, %lu\n",
(long)le32_to_cpu(es->s_free_blocks_count),
desc_count, bitmap_count);
return bitmap_count;
#else
for (i = 0; i < EXT2_SB(sb)->s_groups_count; i++) {
desc = ext2_get_group_desc (sb, i, NULL);
if (!desc)
continue;
desc_count += le16_to_cpu(desc->bg_free_blocks_count);
}
return desc_count;
#endif
}
static inline int test_root(int a, int b)
{
int num = b;
while (a > num)
num *= b;
return num == a;
}
static int ext2_group_sparse(int group)
{
if (group <= 1)
return 1;
return (test_root(group, 3) || test_root(group, 5) ||
test_root(group, 7));
}
/**
* ext2_bg_has_super - number of blocks used by the superblock in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the superblock (primary or backup)
* in this group. Currently this will be only 0 or 1.
*/
int ext2_bg_has_super(struct super_block *sb, int group)
{
if (EXT2_HAS_RO_COMPAT_FEATURE(sb,EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)&&
!ext2_group_sparse(group))
return 0;
return 1;
}
/**
* ext2_bg_num_gdb - number of blocks used by the group table in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the group descriptor table
* (primary or backup) in this group. In the future there may be a
* different number of descriptor blocks in each group.
*/
unsigned long ext2_bg_num_gdb(struct super_block *sb, int group)
{
return ext2_bg_has_super(sb, group) ? EXT2_SB(sb)->s_gdb_count : 0;
}
|
<h1 id="key">Manifest - Key</h1>
<p>
This value can be used to control
the unique ID of an extension, app, or theme when
it is loaded during development.
</p>
<p class="note">
<b>Note:</b> You don't usually need to
use this value. Instead, write your
code so that the key value doesn't matter
by using <a href="http://developer.chrome.com/extensions/overview#relative-urls">relative paths</a>
and <a href="http://developer.chrome.com/extensions/extension#method-getURL">extension.getURL</a>.
</p>
<p>
To get a suitable key value, first
install your extension from a <code>.crx</code> file
(you may need to
<a href="https://chrome.google.com/webstore/developer/dashboard">upload your extension</a>
or <a href="http://developer.chrome.com/extensions/packaging">package it manually</a>).
Then, in your
<a href="http://www.chromium.org/user-experience/user-data-directory">user
data directory</a>, look in the file
<code>Default/Extensions/<em><extensionId></em>/<em><versionString></em>/manifest.json</code>.
You will see the key value filled in there.
</p>
|
<?php
namespace app;
$app = new \Silex\Application();
$app->register(new \Silex\Provider\SessionServiceProvider());
$def = realpath(__DIR__.'/../vendor/behat/mink/driver-testsuite/web-fixtures');
$ovr = realpath(__DIR__.'/web-fixtures');
$cbk = function ($file) use ($app, $def, $ovr) {
$file = str_replace('.file', '.php', $file);
$path = file_exists($ovr.'/'.$file) ? $ovr.'/'.$file : $def.'/'.$file;
$resp = null;
ob_start();
include($path);
$content = ob_get_clean();
if ($resp) {
if ('' === $resp->getContent()) {
$resp->setContent($content);
}
return $resp;
}
return $content;
};
$app->get('/{file}', $cbk)->assert('file', '.*');
$app->post('/{file}', $cbk)->assert('file', '.*');
$app['debug'] = true;
$app['exception_handler']->disable();
$app['session.test'] = true;
return $app;
|
#!/bin/sh
#
# $Id: topinfo_iorsize_stats.sh 91813 2010-09-17 07:52:52Z johnnyw $
#
if [ $# -lt 4 ]; then
echo "Usage: $0 [ROOT] [DEST] [USER] [OPTIMIZED]"
exit 0
fi
ROOT=$1
DEST=$2
US=$3
OPT=$4
DATE=`date +%Y/%m/%d-%H:%M`
cd $ROOT
ACE_ROOT=$ROOT
export ACE_ROOT
LD_LIBRARY_PATH=$ACE_ROOT/ace
export LD_LIBRARY_PATH
PATH=/usr/bin:/bin:$PATH
export PATH
cd TAO/performance-tests/Memory/IORsize
# start the server. If OPT == 1 then start the optimized version, else
# the non-optimized version
if test $OPT == 1
then ./server -ORBSvcConf server.conf &
else ./server &
fi
s_id=$!;
server_start_size=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;
# Just sleep for 2 seconds.
sleep 2;
# Check whether the server has started
file="test.ior"
if test -f $file
then
# start the client
./client &
c_id=$!;
# Wait till all the invocations are done
sleep 30;
# Get the size once the client has made sufficient invocations.
s_invocations=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;
let "actual_server_growth=${s_invocations}-${server_start_size}";
if test $OPT == 1
then
echo $DATE $s_invocations >> $DEST/source/server_opt_ior_size.txt
echo $DATE $actual_server_growth >> $DEST/source/opt_ior_size.txt
else
echo $DATE $s_invocations >> $DEST/source/server_ior_size.txt
echo $DATE $actual_server_growth >> $DEST/source/actual_ior_size.txt
fi
# Kill the server and client. We will look at better ways of doing
# this later.
kill -9 $c_id;
kill -9 $s_id;
rm -f $file
else
echo $file doesnt exist
fi
cd $DEST/source
STRING="for 50000 IORs"
FILES="server_opt opt server actual"
for i in $FILES ; do
/usr/bin/tac ${i}_ior_size.txt > $DEST/data/${i}_ior_size.txt
/usr/bin/tail -5 ${i}_ior_size.txt > $DEST/data/LAST_${i}_ior_size.txt
$ROOT/bin/generate_topinfo_charts.sh ${i}_ior_size.txt $DEST/images/${i}_ior_size.png ${i}_ior_size.txt
done
|
DELETE FROM `gameobject_template` WHERE `entry` IN (231217,233249,236187,236186,231964,236188,236177,236176,233248,236175,236185,230867);
INSERT INTO `gameobject_template` (`entry`,`type`,`displayId`,`name`,`IconName`,`castBarCaption`,`unk1`,`faction`,`flags`,`size`,`Data0`,`Data1`,`Data2`,`Data3`,`Data4`,`Data5`,`Data6`,`Data7`,`Data8`,`Data9`,`Data10`,`Data11`,`Data12`,`Data13`,`Data14`,`Data15`,`Data16`,`Data17`,`Data18`,`Data19`,`Data20`,`Data21`,`Data22`,`Data23`,`Data24`,`Data25`,`Data26`,`Data27`,`Data28`,`Data29`,`Data30`,`Data31`,`Data32`,`unkInt32`,`AIName`,`ScriptName`,`VerifiedBuild`) VALUES
(231217,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,162743,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(233249,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,166877,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236187,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172105,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236186,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172104,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(231964,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,164610,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236188,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172414,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236177,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172056,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236176,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172043,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(233248,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,163215,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236175,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172040,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(236185,10,18018,'Finalize Garrison Plot','architect','Finalizing','',0,0,2,1691,0,0,3000,0,0,0,0,0,0,172083,0,0,0,83562,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,'','',19865),
(230867,5,16265,'Under Construction Cloud','','','',0,32,0.35,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'','',19865);
UPDATE `creature_template` SET `minlevel`=90,`maxlevel`=90,`faction`=714,`unit_flags`=0x8000 WHERE `entry`=78467;
UPDATE `creature_model_info` SET `BoundingRadius`=0.372,`CombatReach`=1.5 WHERE `DisplayID`=59254;
SET @PEON := 228;
DELETE FROM `creature` WHERE `guid` BETWEEN @PEON AND @PEON+28;
INSERT INTO `creature` (`guid`,`id`,`map`,`spawnMask`,`phaseId`,`position_x`,`position_y`,`position_z`,`orientation`,`spawntimesecs`,`spawndist`,`MovementType`) VALUES
(@PEON+00,78467,1353,2,0,-1.037787,0.272035,2.163010,3.930394,7200,0,0),
(@PEON+01,78467,1353,2,0,-2.149102,3.247060,2.163010,2.693754,7200,0,0),
(@PEON+02,78467,1353,2,0,1.758662,8.978440,2.163010,3.050084,7200,0,0),
(@PEON+03,78467,1353,2,0,10.771531,2.919150,2.163010,2.724154,7200,0,0),
(@PEON+04,78467,1353,2,0,10.959270,-2.766289,2.163010,3.920824,7200,0,0),
(@PEON+05,78467,1353,2,0,13.544037,-6.562311,8.610001,5.424888,7200,0,0),
(@PEON+06,78467,1353,2,0,15.100115,-6.952090,11.637009,3.331964,7200,0,0),
(@PEON+07,78467,1353,2,0,2.979650,-9.391919,2.161011,2.745454,7200,0,0),
(@PEON+08,78467,1353,2,0,6.507762,-14.418222,2.163010,4.573184,7200,0,0),
(@PEON+09,78467,1353,2,0,6.980373,21.202633,8.955002,0.177844,7200,0,0),
(@PEON+10,78467,1353,2,0,9.172408,12.214418,2.163010,1.355784,7200,0,0),
(@PEON+11,78467,1354,2,0,-2.376850,-1.938201,1.178009,3.765444,7200,0,0),
(@PEON+12,78467,1354,2,0,-3.979343,-6.312402,7.108002,2.176954,7200,0,0),
(@PEON+13,78467,1354,2,0,-4.827291,4.064543,1.178009,4.593574,7200,0,0),
(@PEON+14,78467,1354,2,0,10.152680,0.077213,1.178009,2.171654,7200,0,0),
(@PEON+15,78467,1354,2,0,14.417463,0.781982,1.178009,2.831924,7200,0,0),
(@PEON+16,78467,1354,2,0,15.252268,-3.258279,1.178009,4.914564,7200,0,0),
(@PEON+17,78467,1354,2,0,3.077893,-9.743636,1.163010,3.424174,7200,0,0),
(@PEON+18,78467,1354,2,0,3.734778,9.195932,7.473999,4.934684,7200,0,0),
(@PEON+19,78467,1354,2,0,5.343877,2.729449,1.178009,2.157304,7200,0,0),
(@PEON+20,78467,1354,2,0,6.048157,-6.359730,1.178009,5.548074,7200,0,0),
(@PEON+21,78467,1354,2,0,6.890800,-10.220474,4.296005,1.145594,7200,0,0),
(@PEON+22,78467,1371,2,0,-3.689185,-1.491618,3.751007,3.119459,7200,0,0),
(@PEON+23,78467,1371,2,0,-5.583674,-3.473835,6.037003,4.445419,7200,0,0),
(@PEON+24,78467,1371,2,0,0.410911,-1.188165,1.052002,3.581499,7200,0,0),
(@PEON+25,78467,1371,2,0,1.241397,5.063163,1.052002,2.175249,7200,0,0),
(@PEON+26,78467,1371,2,0,1.437477,8.185573,1.174004,5.726631,7200,0,0),
(@PEON+27,78467,1371,2,0,2.748763,-6.646344,1.052002,4.194179,7200,0,0),
(@PEON+28,78467,1371,2,0,4.704940,-7.203648,6.174004,0.718819,7200,0,0);
DELETE FROM `creature_addon` WHERE `guid` IN (@PEON+6,@PEON+12,@PEON+23,@PEON+28);
INSERT INTO `creature_addon` (`guid`,`mount`,`bytes1`,`bytes2`,`auras`) VALUES
(@PEON+06,0,0x1000003,0x1,'55474'), -- Frostwall Peon - Cosmetic - Sleep Zzz
(@PEON+12,0,0x1000003,0x1,'55474'), -- Frostwall Peon - Cosmetic - Sleep Zzz
(@PEON+23,0,0x1000003,0x1,'55474'), -- Frostwall Peon - Cosmetic - Sleep Zzz
(@PEON+28,0,0x8,0x1,''); -- Frostwall Peon
DELETE FROM `creature_template_addon` WHERE `entry`=78467;
INSERT INTO `creature_template_addon` (`entry`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(78467,0,0x0,0x1,173,''); -- Frostwall Peon
DELETE FROM `creature_equip_template` WHERE `CreatureID`=78467;
INSERT INTO `creature_equip_template` (`CreatureID`,`ID`,`ItemID1`,`ItemID2`,`ItemID3`) VALUES
(78467,1,5956,0,0); -- Frostwall Peon
SET @CLOUD := 22;
DELETE FROM `gameobject` WHERE `guid` BETWEEN @CLOUD AND @CLOUD+21;
INSERT INTO `gameobject` (`guid`,`id`,`map`,`spawnMask`,`phaseId`,`position_x`,`position_y`,`position_z`,`orientation`,`rotation0`,`rotation1`,`rotation2`,`rotation3`,`spawntimesecs`,`animprogress`,`state`) VALUES
(@CLOUD+00,230867,1353,2,0,-1.602455,-0.805748,2.080002,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+01,230867,1353,2,0,-2.184269,4.333852,3.819000,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+02,230867,1353,2,0,-3.610352,3.829465,3.322998,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+03,230867,1353,2,0,0.507770,9.083573,2.085007,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+04,230867,1353,2,0,1.141878,-8.836224,2.078003,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+05,230867,1353,2,0,2.937370,-8.619312,2.079010,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+06,230867,1353,2,0,7.302363,-16.362539,2.080002,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+07,230867,1353,2,0,8.685335,3.850828,3.316010,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+08,230867,1353,2,0,9.477190,-3.942071,3.108002,0.000001,0,0,0,1,7200,255,1),
(@CLOUD+09,230867,1354,2,0,-2.885510,-3.267375,2.942001,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+10,230867,1354,2,0,-5.703460,-2.703973,2.419006,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+11,230867,1354,2,0,12.723060,2.317318,7.229004,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+12,230867,1354,2,0,13.395262,1.437059,2.212997,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+13,230867,1354,2,0,2.362132,-5.047787,0.326996,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+14,230867,1354,2,0,4.062244,-9.205985,5.154999,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+15,230867,1354,2,0,6.416709,-7.086459,2.380005,6.195914,0,0,0,1,7200,255,1),
(@CLOUD+16,230867,1371,2,0,-0.286411,5.867835,2.477005,0.000000,0,0,0,1,7200,255,1),
(@CLOUD+17,230867,1371,2,0,-0.435432,-1.463116,2.343002,0.000000,0,0,0,1,7200,255,1),
(@CLOUD+18,230867,1371,2,0,-5.173488,-1.854540,4.764000,0.000000,0,0,0,1,7200,255,1),
(@CLOUD+19,230867,1371,2,0,2.071243,8.033276,2.346001,0.000000,0,0,0,1,7200,255,1),
(@CLOUD+20,230867,1371,2,0,2.267101,-7.889375,2.452003,0.000000,0,0,0,1,7200,255,1),
(@CLOUD+21,230867,1371,2,0,5.497054,-5.979848,6.371002,0.000000,0,0,0,1,7200,255,1);
|
#include <linux/smp.h>
#include <linux/timex.h>
#include <linux/string.h>
#include <linux/seq_file.h>
#include <linux/cpufreq.h>
/*
* Get CPU information for use by the procfs.
*/
static void show_cpuinfo_core(struct seq_file *m, struct cpuinfo_x86 *c,
unsigned int cpu)
{
#ifdef CONFIG_SMP
if (c->x86_max_cores * smp_num_siblings > 1) {
seq_printf(m, "physical id\t: %d\n", c->phys_proc_id);
seq_printf(m, "siblings\t: %d\n",
cpumask_weight(cpu_core_mask(cpu)));
seq_printf(m, "core id\t\t: %d\n", c->cpu_core_id);
seq_printf(m, "cpu cores\t: %d\n", c->booted_cores);
seq_printf(m, "apicid\t\t: %d\n", c->apicid);
seq_printf(m, "initial apicid\t: %d\n", c->initial_apicid);
}
#endif
}
#ifdef CONFIG_X86_32
static void show_cpuinfo_misc(struct seq_file *m, struct cpuinfo_x86 *c)
{
/*
* We use exception 16 if we have hardware math and we've either seen
* it or the CPU claims it is internal
*/
int fpu_exception = c->hard_math && (ignore_fpu_irq || cpu_has_fpu);
seq_printf(m,
"fdiv_bug\t: %s\n"
"hlt_bug\t\t: %s\n"
"f00f_bug\t: %s\n"
"coma_bug\t: %s\n"
"fpu\t\t: %s\n"
"fpu_exception\t: %s\n"
"cpuid level\t: %d\n"
"wp\t\t: %s\n",
c->fdiv_bug ? "yes" : "no",
c->hlt_works_ok ? "no" : "yes",
c->f00f_bug ? "yes" : "no",
c->coma_bug ? "yes" : "no",
c->hard_math ? "yes" : "no",
fpu_exception ? "yes" : "no",
c->cpuid_level,
c->wp_works_ok ? "yes" : "no");
}
#else
static void show_cpuinfo_misc(struct seq_file *m, struct cpuinfo_x86 *c)
{
seq_printf(m,
"fpu\t\t: yes\n"
"fpu_exception\t: yes\n"
"cpuid level\t: %d\n"
"wp\t\t: yes\n",
c->cpuid_level);
}
#endif
static int show_cpuinfo(struct seq_file *m, void *v)
{
struct cpuinfo_x86 *c = v;
unsigned int cpu;
int i;
cpu = c->cpu_index;
seq_printf(m, "processor\t: %u\n"
"vendor_id\t: %s\n"
"cpu family\t: %d\n"
"model\t\t: %u\n"
"model name\t: %s\n",
cpu,
c->x86_vendor_id[0] ? c->x86_vendor_id : "unknown",
c->x86,
c->x86_model,
c->x86_model_id[0] ? c->x86_model_id : "unknown");
if (c->x86_mask || c->cpuid_level >= 0)
seq_printf(m, "stepping\t: %d\n", c->x86_mask);
else
seq_printf(m, "stepping\t: unknown\n");
if (c->microcode)
seq_printf(m, "microcode\t: 0x%x\n", c->microcode);
if (cpu_has(c, X86_FEATURE_TSC)) {
unsigned int freq = cpufreq_quick_get(cpu);
if (!freq)
freq = cpu_khz;
seq_printf(m, "cpu MHz\t\t: %u.%03u\n",
freq / 1000, (freq % 1000));
}
/* Cache size */
if (c->x86_cache_size >= 0)
seq_printf(m, "cache size\t: %d KB\n", c->x86_cache_size);
show_cpuinfo_core(m, c, cpu);
show_cpuinfo_misc(m, c);
seq_printf(m, "flags\t\t:");
for (i = 0; i < 32*NCAPINTS; i++)
if (cpu_has(c, i) && x86_cap_flags[i] != NULL)
seq_printf(m, " %s", x86_cap_flags[i]);
seq_printf(m, "\nbogomips\t: %lu.%02lu\n",
c->loops_per_jiffy/(500000/HZ),
(c->loops_per_jiffy/(5000/HZ)) % 100);
#ifdef CONFIG_X86_64
if (c->x86_tlbsize > 0)
seq_printf(m, "TLB size\t: %d 4K pages\n", c->x86_tlbsize);
#endif
seq_printf(m, "clflush size\t: %u\n", c->x86_clflush_size);
seq_printf(m, "cache_alignment\t: %d\n", c->x86_cache_alignment);
seq_printf(m, "address sizes\t: %u bits physical, %u bits virtual\n",
c->x86_phys_bits, c->x86_virt_bits);
seq_printf(m, "power management:");
for (i = 0; i < 32; i++) {
if (c->x86_power & (1 << i)) {
if (i < ARRAY_SIZE(x86_power_flags) &&
x86_power_flags[i])
seq_printf(m, "%s%s",
x86_power_flags[i][0] ? " " : "",
x86_power_flags[i]);
else
seq_printf(m, " [%d]", i);
}
}
seq_printf(m, "\n\n");
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
if (*pos == 0) /* just in case, cpu 0 is not the first */
*pos = cpumask_first(cpu_online_mask);
else
*pos = cpumask_next(*pos - 1, cpu_online_mask);
if ((*pos) < nr_cpu_ids)
return &cpu_data(*pos);
return NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
|
<?php
namespace Gedmo\Mapping;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\Mapping\Driver\DriverChain;
use Doctrine\ORM\Mapping\Driver\YamlDriver;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Gedmo\Mapping\ExtensionMetadataFactory;
use Tool\BaseTestCaseOM;
/**
* These are mapping extension tests
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class MultiManagerMappingTest extends BaseTestCaseOM
{
/**
* @var Doctrine\ORM\EntityManager
*/
private $em1;
/**
* @var Doctrine\ORM\EntityManager
*/
private $em2;
/**
* @var Doctrine\ODM\MongoDB\DocumentManager
*/
private $dm1;
public function setUp()
{
parent::setUp();
// EM with standard annotation mapping
$this->em1 = $this->getMockSqliteEntityManager(array(
'Sluggable\Fixture\Article'
));
// EM with yaml and annotation mapping
$reader = new AnnotationReader();
$annotationDriver = new AnnotationDriver($reader);
$reader = new AnnotationReader();
$annotationDriver2 = new AnnotationDriver($reader);
$yamlDriver = new YamlDriver(__DIR__.'/Driver/Yaml');
$chain = new DriverChain;
$chain->addDriver($annotationDriver, 'Translatable\Fixture');
$chain->addDriver($yamlDriver, 'Mapping\Fixture\Yaml');
$chain->addDriver($annotationDriver2, 'Gedmo\Translatable');
$this->em2 = $this->getMockSqliteEntityManager(array(
'Translatable\Fixture\PersonTranslation',
'Mapping\Fixture\Yaml\User',
), $chain);
// DM with standard annotation mapping
$this->dm1 = $this->getMockDocumentManager('gedmo_extensions_test');
}
public function testTwoDiferentManager()
{
$meta = $this->dm1->getClassMetadata('Sluggable\Fixture\Document\Article');
$dmArticle = new \Sluggable\Fixture\Document\Article;
$dmArticle->setCode('code');
$dmArticle->setTitle('title');
$this->dm1->persist($dmArticle);
$this->dm1->flush();
$this->assertEquals('title-code', $dmArticle->getSlug());
$em1Article = new \Sluggable\Fixture\Article;
$em1Article->setCode('code');
$em1Article->setTitle('title');
$this->em1->persist($em1Article);
$this->em1->flush();
$this->assertEquals('title-code', $em1Article->getSlug());
}
public function testTwoSameManagers()
{
$em1Article = new \Sluggable\Fixture\Article;
$em1Article->setCode('code');
$em1Article->setTitle('title');
$this->em1->persist($em1Article);
$this->em1->flush();
$this->assertEquals('title-code', $em1Article->getSlug());
$user = new \Mapping\Fixture\Yaml\User;
$user->setUsername('user');
$user->setPassword('secret');
$this->em2->persist($user);
$this->em2->flush();
$this->assertEquals(1, $user->getId());
}
}
|
// Type definitions for fs-readfile-promise 3.0
// Project: https://github.com/shinnn/fs-readfile-promise
// Definitions by: Motosugi Murata <https://github.com/mtsg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { PathLike } from "fs";
type PathType = PathLike | number;
type OptionsType = { encoding: string; flag?: string; } | string;
export = fsReadFilePromise;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
declare function fsReadFilePromise(path: PathType, options: OptionsType): Promise<string>;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
*/
declare function fsReadFilePromise(path: PathType, options?: null): Promise<Buffer>;
declare namespace fsReadFilePromise { }
|
/*
* linux/drivers/video/backlight/pwm_bl.c
*
* simple PWM based backlight control, board code has to setup
* 1) pin configuration so PWM waveforms can output
* 2) platform_data being correctly configured
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio/consumer.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/pwm.h>
#include <linux/pwm_backlight.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
struct pwm_bl_data {
struct pwm_device *pwm;
struct device *dev;
unsigned int period;
unsigned int lth_brightness;
unsigned int *levels;
bool enabled;
struct regulator *power_supply;
struct gpio_desc *enable_gpio;
unsigned int scale;
bool legacy;
int (*notify)(struct device *,
int brightness);
void (*notify_after)(struct device *,
int brightness);
int (*check_fb)(struct device *, struct fb_info *);
void (*exit)(struct device *);
};
static void pwm_backlight_power_on(struct pwm_bl_data *pb, int brightness)
{
int err;
if (pb->enabled)
return;
err = regulator_enable(pb->power_supply);
if (err < 0)
dev_err(pb->dev, "failed to enable power supply\n");
if (pb->enable_gpio)
gpiod_set_value(pb->enable_gpio, 1);
pwm_enable(pb->pwm);
pb->enabled = true;
}
static void pwm_backlight_power_off(struct pwm_bl_data *pb)
{
if (!pb->enabled)
return;
pwm_config(pb->pwm, 0, pb->period);
pwm_disable(pb->pwm);
if (pb->enable_gpio)
gpiod_set_value(pb->enable_gpio, 0);
regulator_disable(pb->power_supply);
pb->enabled = false;
}
static int compute_duty_cycle(struct pwm_bl_data *pb, int brightness)
{
unsigned int lth = pb->lth_brightness;
int duty_cycle;
if (pb->levels)
duty_cycle = pb->levels[brightness];
else
duty_cycle = brightness;
return (duty_cycle * (pb->period - lth) / pb->scale) + lth;
}
static int pwm_backlight_update_status(struct backlight_device *bl)
{
struct pwm_bl_data *pb = bl_get_data(bl);
int brightness = bl->props.brightness;
int duty_cycle;
if (bl->props.power != FB_BLANK_UNBLANK ||
bl->props.fb_blank != FB_BLANK_UNBLANK ||
bl->props.state & BL_CORE_FBBLANK)
brightness = 0;
if (pb->notify)
brightness = pb->notify(pb->dev, brightness);
if (brightness > 0) {
duty_cycle = compute_duty_cycle(pb, brightness);
pwm_config(pb->pwm, duty_cycle, pb->period);
pwm_backlight_power_on(pb, brightness);
} else
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, brightness);
return 0;
}
static int pwm_backlight_check_fb(struct backlight_device *bl,
struct fb_info *info)
{
struct pwm_bl_data *pb = bl_get_data(bl);
return !pb->check_fb || pb->check_fb(pb->dev, info);
}
static const struct backlight_ops pwm_backlight_ops = {
.update_status = pwm_backlight_update_status,
.check_fb = pwm_backlight_check_fb,
};
#ifdef CONFIG_OF
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
struct device_node *node = dev->of_node;
struct property *prop;
int length;
u32 value;
int ret;
if (!node)
return -ENODEV;
memset(data, 0, sizeof(*data));
/* determine the number of brightness levels */
prop = of_find_property(node, "brightness-levels", &length);
if (!prop)
return -EINVAL;
data->max_brightness = length / sizeof(u32);
/* read brightness levels from DT property */
if (data->max_brightness > 0) {
size_t size = sizeof(*data->levels) * data->max_brightness;
data->levels = devm_kzalloc(dev, size, GFP_KERNEL);
if (!data->levels)
return -ENOMEM;
ret = of_property_read_u32_array(node, "brightness-levels",
data->levels,
data->max_brightness);
if (ret < 0)
return ret;
ret = of_property_read_u32(node, "default-brightness-level",
&value);
if (ret < 0)
return ret;
data->dft_brightness = value;
data->max_brightness--;
}
data->enable_gpio = -EINVAL;
return 0;
}
static struct of_device_id pwm_backlight_of_match[] = {
{ .compatible = "pwm-backlight" },
{ }
};
MODULE_DEVICE_TABLE(of, pwm_backlight_of_match);
#else
static int pwm_backlight_parse_dt(struct device *dev,
struct platform_pwm_backlight_data *data)
{
return -ENODEV;
}
#endif
static int pwm_backlight_probe(struct platform_device *pdev)
{
struct platform_pwm_backlight_data *data = dev_get_platdata(&pdev->dev);
struct platform_pwm_backlight_data defdata;
struct backlight_properties props;
struct backlight_device *bl;
struct device_node *node = pdev->dev.of_node;
struct pwm_bl_data *pb;
int initial_blank = FB_BLANK_UNBLANK;
struct pwm_args pargs;
int ret;
if (!data) {
ret = pwm_backlight_parse_dt(&pdev->dev, &defdata);
if (ret < 0) {
dev_err(&pdev->dev, "failed to find platform data\n");
return ret;
}
data = &defdata;
}
if (data->init) {
ret = data->init(&pdev->dev);
if (ret < 0)
return ret;
}
pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL);
if (!pb) {
ret = -ENOMEM;
goto err_alloc;
}
if (data->levels) {
unsigned int i;
for (i = 0; i <= data->max_brightness; i++)
if (data->levels[i] > pb->scale)
pb->scale = data->levels[i];
pb->levels = data->levels;
} else
pb->scale = data->max_brightness;
pb->notify = data->notify;
pb->notify_after = data->notify_after;
pb->check_fb = data->check_fb;
pb->exit = data->exit;
pb->dev = &pdev->dev;
pb->enabled = false;
pb->enable_gpio = devm_gpiod_get_optional(&pdev->dev, "enable",
GPIOD_ASIS);
if (IS_ERR(pb->enable_gpio)) {
ret = PTR_ERR(pb->enable_gpio);
goto err_alloc;
}
/*
* Compatibility fallback for drivers still using the integer GPIO
* platform data. Must go away soon.
*/
if (!pb->enable_gpio && gpio_is_valid(data->enable_gpio)) {
ret = devm_gpio_request_one(&pdev->dev, data->enable_gpio,
GPIOF_OUT_INIT_HIGH, "enable");
if (ret < 0) {
dev_err(&pdev->dev, "failed to request GPIO#%d: %d\n",
data->enable_gpio, ret);
goto err_alloc;
}
pb->enable_gpio = gpio_to_desc(data->enable_gpio);
}
if (pb->enable_gpio) {
/*
* If the driver is probed from the device tree and there is a
* phandle link pointing to the backlight node, it is safe to
* assume that another driver will enable the backlight at the
* appropriate time. Therefore, if it is disabled, keep it so.
*/
if (node && node->phandle &&
gpiod_get_direction(pb->enable_gpio) == GPIOF_DIR_OUT &&
gpiod_get_value(pb->enable_gpio) == 0)
initial_blank = FB_BLANK_POWERDOWN;
else
gpiod_direction_output(pb->enable_gpio, 1);
}
pb->power_supply = devm_regulator_get(&pdev->dev, "power");
if (IS_ERR(pb->power_supply)) {
ret = PTR_ERR(pb->power_supply);
goto err_alloc;
}
if (node && node->phandle && !regulator_is_enabled(pb->power_supply))
initial_blank = FB_BLANK_POWERDOWN;
pb->pwm = devm_pwm_get(&pdev->dev, NULL);
if (IS_ERR(pb->pwm) && PTR_ERR(pb->pwm) != -EPROBE_DEFER && !node) {
dev_err(&pdev->dev, "unable to request PWM, trying legacy API\n");
pb->legacy = true;
pb->pwm = pwm_request(data->pwm_id, "pwm-backlight");
}
if (IS_ERR(pb->pwm)) {
ret = PTR_ERR(pb->pwm);
if (ret != -EPROBE_DEFER)
dev_err(&pdev->dev, "unable to request PWM\n");
goto err_alloc;
}
dev_dbg(&pdev->dev, "got pwm for backlight\n");
/*
* FIXME: pwm_apply_args() should be removed when switching to
* the atomic PWM API.
*/
pwm_apply_args(pb->pwm);
/*
* The DT case will set the pwm_period_ns field to 0 and store the
* period, parsed from the DT, in the PWM device. For the non-DT case,
* set the period from platform data if it has not already been set
* via the PWM lookup table.
*/
pwm_get_args(pb->pwm, &pargs);
pb->period = pargs.period;
if (!pb->period && (data->pwm_period_ns > 0))
pb->period = data->pwm_period_ns;
pb->lth_brightness = data->lth_brightness * (pb->period / pb->scale);
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_RAW;
props.max_brightness = data->max_brightness;
bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb,
&pwm_backlight_ops, &props);
if (IS_ERR(bl)) {
dev_err(&pdev->dev, "failed to register backlight\n");
ret = PTR_ERR(bl);
if (pb->legacy)
pwm_free(pb->pwm);
goto err_alloc;
}
if (data->dft_brightness > data->max_brightness) {
dev_warn(&pdev->dev,
"invalid default brightness level: %u, using %u\n",
data->dft_brightness, data->max_brightness);
data->dft_brightness = data->max_brightness;
}
bl->props.brightness = data->dft_brightness;
bl->props.power = initial_blank;
backlight_update_status(bl);
platform_set_drvdata(pdev, bl);
return 0;
err_alloc:
if (data->exit)
data->exit(&pdev->dev);
return ret;
}
static int pwm_backlight_remove(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
backlight_device_unregister(bl);
pwm_backlight_power_off(pb);
if (pb->exit)
pb->exit(&pdev->dev);
if (pb->legacy)
pwm_free(pb->pwm);
return 0;
}
static void pwm_backlight_shutdown(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct pwm_bl_data *pb = bl_get_data(bl);
pwm_backlight_power_off(pb);
}
#ifdef CONFIG_PM_SLEEP
static int pwm_backlight_suspend(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
struct pwm_bl_data *pb = bl_get_data(bl);
if (pb->notify)
pb->notify(pb->dev, 0);
pwm_backlight_power_off(pb);
if (pb->notify_after)
pb->notify_after(pb->dev, 0);
return 0;
}
static int pwm_backlight_resume(struct device *dev)
{
struct backlight_device *bl = dev_get_drvdata(dev);
backlight_update_status(bl);
return 0;
}
#endif
static const struct dev_pm_ops pwm_backlight_pm_ops = {
#ifdef CONFIG_PM_SLEEP
.suspend = pwm_backlight_suspend,
.resume = pwm_backlight_resume,
.poweroff = pwm_backlight_suspend,
.restore = pwm_backlight_resume,
#endif
};
static struct platform_driver pwm_backlight_driver = {
.driver = {
.name = "pwm-backlight",
.pm = &pwm_backlight_pm_ops,
.of_match_table = of_match_ptr(pwm_backlight_of_match),
},
.probe = pwm_backlight_probe,
.remove = pwm_backlight_remove,
.shutdown = pwm_backlight_shutdown,
};
module_platform_driver(pwm_backlight_driver);
MODULE_DESCRIPTION("PWM based Backlight Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pwm-backlight");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.