code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Data
{
[Flags]
public enum DataRowAction
{
Nothing = 0, // 0 0x00
Delete = (1 << 0), // 1 0x01
Change = (1 << 1), // 2 0x02
Rollback = (1 << 2), // 4 0x04
Commit = (1 << 3), // 8 0x08
Add = (1 << 4), // 16 0x10
ChangeOriginal = (1 << 5), // 32 0x20
ChangeCurrentAndOriginal = (1 << 6), // 64 0x40
}
}
|
nbarbettini/corefx
|
src/System.Data.Common/src/System/Data/DataRowAction.cs
|
C#
|
mit
| 614
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace AppUIBasics.Common
{
/// <summary>
/// SuspensionManager captures global session state to simplify process lifetime management
/// for an application. Note that session state will be automatically cleared under a variety
/// of conditions and should only be used to store information that would be convenient to
/// carry across sessions, but that should be discarded when an application crashes or is
/// upgraded.
/// </summary>
internal sealed class SuspensionManager
{
private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
private static List<Type> _knownTypes = new List<Type>();
private const string sessionStateFilename = "_sessionState.xml";
/// <summary>
/// Provides access to global session state for the current session. This state is
/// serialized by <see cref="SaveAsync"/> and restored by
/// <see cref="RestoreAsync"/>, so values must be serializable by
/// <see cref="DataContractSerializer"/> and should be as compact as possible. Strings
/// and other self-contained data types are strongly recommended.
/// </summary>
public static Dictionary<string, object> SessionState
{
get { return _sessionState; }
}
/// <summary>
/// List of custom types provided to the <see cref="DataContractSerializer"/> when
/// reading and writing session state. Initially empty, additional types may be
/// added to customize the serialization process.
/// </summary>
public static List<Type> KnownTypes
{
get { return _knownTypes; }
}
/// <summary>
/// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also preserve their current
/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
/// to save its state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
public static async Task SaveAsync()
{
try
{
// Save the navigation state for all registered frames
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame))
{
SaveFrameNavigationState(frame);
}
}
// Serialize the session state synchronously to avoid asynchronous access to shared
// state
MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
serializer.WriteObject(sessionData, _sessionState);
// Get an output stream for the SessionState file and write the state asynchronously
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
sessionData.Seek(0, SeekOrigin.Begin);
await sessionData.CopyToAsync(fileStream);
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
/// <summary>
/// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
/// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
/// state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been read. The
/// content of <see cref="SessionState"/> should not be relied upon until this task
/// completes.</returns>
public static async Task RestoreAsync()
{
_sessionState = new Dictionary<String, Object>();
try
{
// Get the input stream for the SessionState file
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
// Deserialize the Session State
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
_sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
}
// Restore any registered frames to their saved state
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame))
{
frame.ClearValue(FrameSessionStateProperty);
RestoreFrameNavigationState(frame);
}
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
private static DependencyProperty FrameSessionStateKeyProperty =
DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
private static DependencyProperty FrameSessionStateProperty =
DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);
private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
/// <summary>
/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
/// and restored from <see cref="SessionState"/>. Frames should be registered once
/// immediately after creation if they will participate in session state management. Upon
/// registration if state has already been restored for the specified key
/// the navigation history will immediately be restored. Subsequent invocations of
/// <see cref="RestoreAsync"/> will also restore navigation history.
/// </summary>
/// <param name="frame">An instance whose navigation history should be managed by
/// <see cref="SuspensionManager"/></param>
/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
/// store navigation-related information.</param>
public static void RegisterFrame(Frame frame, String sessionStateKey)
{
if (frame.GetValue(FrameSessionStateKeyProperty) != null)
{
throw new InvalidOperationException("Frames can only be registered to one session state key");
}
if (frame.GetValue(FrameSessionStateProperty) != null)
{
throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
}
// Use a dependency property to associate the session key with a frame, and keep a list of frames whose
// navigation state should be managed
frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
_registeredFrames.Add(new WeakReference<Frame>(frame));
// Check to see if navigation state can be restored
RestoreFrameNavigationState(frame);
}
/// <summary>
/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
/// from <see cref="SessionState"/>. Any navigation state previously captured will be
/// removed.
/// </summary>
/// <param name="frame">An instance whose navigation history should no longer be
/// managed.</param>
public static void UnregisterFrame(Frame frame)
{
// Remove session state and remove the frame from the list of frames whose navigation
// state will be saved (along with any weak references that are no longer reachable)
SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
_registeredFrames.RemoveAll((weakFrameReference) =>
{
Frame testFrame;
return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
});
}
/// <summary>
/// Provides storage for session state associated with the specified <see cref="Frame"/>.
/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
/// their session state saved and restored automatically as a part of the global
/// <see cref="SessionState"/>. Frames that are not registered have transient state
/// that can still be useful when restoring pages that have been discarded from the
/// navigation cache.
/// </summary>
/// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage
/// page-specific state instead of working with frame session state directly.</remarks>
/// <param name="frame">The instance for which session state is desired.</param>
/// <returns>A collection of state subject to the same serialization mechanism as
/// <see cref="SessionState"/>.</returns>
public static Dictionary<String, Object> SessionStateForFrame(Frame frame)
{
var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
if (frameState == null)
{
var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
if (frameSessionKey != null)
{
// Registered frames reflect the corresponding session state
if (!_sessionState.ContainsKey(frameSessionKey))
{
_sessionState[frameSessionKey] = new Dictionary<String, Object>();
}
frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
}
else
{
// Frames that aren't registered have transient state
frameState = new Dictionary<String, Object>();
}
frame.SetValue(FrameSessionStateProperty, frameState);
}
return frameState;
}
private static void RestoreFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
if (frameState.ContainsKey("Navigation"))
{
frame.SetNavigationState((String)frameState["Navigation"]);
}
}
private static void SaveFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
frameState["Navigation"] = frame.GetNavigationState();
}
}
public class SuspensionManagerException : Exception
{
public SuspensionManagerException()
{
}
public SuspensionManagerException(Exception e)
: base("SuspensionManager failed", e)
{
}
}
}
|
williamsrz/Windows-universal-samples
|
xaml_xamluibasics/CS/AppUIBasics/Common/SuspensionManager.cs
|
C#
|
mit
| 12,098
|
! PR fortran/16861
! { dg-do run }
module foo
integer :: i
end module foo
module bar
contains
subroutine baz(j)
use foo
integer, dimension(i) :: j
integer :: n
do n = 1, i
if (j(n) /= n**2) call abort
end do
end subroutine baz
end module bar
subroutine quus()
use foo
use bar
i = 2
call baz ((/1,4/))
i = 7
call baz ((/1,4,9,16,25,36,49/))
end subroutine quus
program test
call quus
end program test
|
selmentdev/selment-toolchain
|
source/gcc-latest/gcc/testsuite/gfortran.dg/pr16861.f90
|
FORTRAN
|
gpl-3.0
| 451
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts Amqp related classes to array representation.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
class AmqpCaster
{
private static $flags = array(
AMQP_DURABLE => 'AMQP_DURABLE',
AMQP_PASSIVE => 'AMQP_PASSIVE',
AMQP_EXCLUSIVE => 'AMQP_EXCLUSIVE',
AMQP_AUTODELETE => 'AMQP_AUTODELETE',
AMQP_INTERNAL => 'AMQP_INTERNAL',
AMQP_NOLOCAL => 'AMQP_NOLOCAL',
AMQP_AUTOACK => 'AMQP_AUTOACK',
AMQP_IFEMPTY => 'AMQP_IFEMPTY',
AMQP_IFUNUSED => 'AMQP_IFUNUSED',
AMQP_MANDATORY => 'AMQP_MANDATORY',
AMQP_IMMEDIATE => 'AMQP_IMMEDIATE',
AMQP_MULTIPLE => 'AMQP_MULTIPLE',
AMQP_NOWAIT => 'AMQP_NOWAIT',
AMQP_REQUEUE => 'AMQP_REQUEUE',
);
private static $exchangeTypes = array(
AMQP_EX_TYPE_DIRECT => 'AMQP_EX_TYPE_DIRECT',
AMQP_EX_TYPE_FANOUT => 'AMQP_EX_TYPE_FANOUT',
AMQP_EX_TYPE_TOPIC => 'AMQP_EX_TYPE_TOPIC',
AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS',
);
public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
$a += array(
$prefix.'is_connected' => $c->isConnected(),
);
// Recent version of the extension already expose private properties
if (isset($a["\x00AMQPConnection\x00login"])) {
return $a;
}
// BC layer in the amqp lib
if (method_exists($c, 'getReadTimeout')) {
$timeout = $c->getReadTimeout();
} else {
$timeout = $c->getTimeout();
}
$a += array(
$prefix.'is_connected' => $c->isConnected(),
$prefix.'login' => $c->getLogin(),
$prefix.'password' => $c->getPassword(),
$prefix.'host' => $c->getHost(),
$prefix.'vhost' => $c->getVhost(),
$prefix.'port' => $c->getPort(),
$prefix.'read_timeout' => $timeout,
);
return $a;
}
public static function castChannel(\AMQPChannel $c, array $a, Stub $stub, $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
$a += array(
$prefix.'is_connected' => $c->isConnected(),
$prefix.'channel_id' => $c->getChannelId(),
);
// Recent version of the extension already expose private properties
if (isset($a["\x00AMQPChannel\x00connection"])) {
return $a;
}
$a += array(
$prefix.'connection' => $c->getConnection(),
$prefix.'prefetch_size' => $c->getPrefetchSize(),
$prefix.'prefetch_count' => $c->getPrefetchCount(),
);
return $a;
}
public static function castQueue(\AMQPQueue $c, array $a, Stub $stub, $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
$a += array(
$prefix.'flags' => self::extractFlags($c->getFlags()),
);
// Recent version of the extension already expose private properties
if (isset($a["\x00AMQPQueue\x00name"])) {
return $a;
}
$a += array(
$prefix.'connection' => $c->getConnection(),
$prefix.'channel' => $c->getChannel(),
$prefix.'name' => $c->getName(),
$prefix.'arguments' => $c->getArguments(),
);
return $a;
}
public static function castExchange(\AMQPExchange $c, array $a, Stub $stub, $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
$a += array(
$prefix.'flags' => self::extractFlags($c->getFlags()),
);
$type = isset(self::$exchangeTypes[$c->getType()]) ? new ConstStub(self::$exchangeTypes[$c->getType()], $c->getType()) : $c->getType();
// Recent version of the extension already expose private properties
if (isset($a["\x00AMQPExchange\x00name"])) {
$a["\x00AMQPExchange\x00type"] = $type;
return $a;
}
$a += array(
$prefix.'connection' => $c->getConnection(),
$prefix.'channel' => $c->getChannel(),
$prefix.'name' => $c->getName(),
$prefix.'type' => $type,
$prefix.'arguments' => $c->getArguments(),
);
return $a;
}
public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, $isNested, $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;
$deliveryMode = new ConstStub($c->getDeliveryMode().(2 === $c->getDeliveryMode() ? ' (persistent)' : ' (non-persistent)'), $c->getDeliveryMode());
// Recent version of the extension already expose private properties
if (isset($a["\x00AMQPEnvelope\x00body"])) {
$a["\0AMQPEnvelope\0delivery_mode"] = $deliveryMode;
return $a;
}
if (!($filter & Caster::EXCLUDE_VERBOSE)) {
$a += array($prefix.'body' => $c->getBody());
}
$a += array(
$prefix.'delivery_tag' => $c->getDeliveryTag(),
$prefix.'is_redelivery' => $c->isRedelivery(),
$prefix.'exchange_name' => $c->getExchangeName(),
$prefix.'routing_key' => $c->getRoutingKey(),
$prefix.'content_type' => $c->getContentType(),
$prefix.'content_encoding' => $c->getContentEncoding(),
$prefix.'headers' => $c->getHeaders(),
$prefix.'delivery_mode' => $deliveryMode,
$prefix.'priority' => $c->getPriority(),
$prefix.'correlation_id' => $c->getCorrelationId(),
$prefix.'reply_to' => $c->getReplyTo(),
$prefix.'expiration' => $c->getExpiration(),
$prefix.'message_id' => $c->getMessageId(),
$prefix.'timestamp' => $c->getTimeStamp(),
$prefix.'type' => $c->getType(),
$prefix.'user_id' => $c->getUserId(),
$prefix.'app_id' => $c->getAppId(),
);
return $a;
}
private static function extractFlags($flags)
{
$flagsArray = array();
foreach (self::$flags as $value => $name) {
if ($flags & $value) {
$flagsArray[] = $name;
}
}
if (!$flagsArray) {
$flagsArray = array('AMQP_NOPARAM');
}
return new ConstStub(implode('|', $flagsArray), $flags);
}
}
|
bkostrowiecki/devnote
|
www/vendor/symfony/var-dumper/Caster/AmqpCaster.php
|
PHP
|
gpl-3.0
| 6,693
|
import * as dedent from 'dedent';
const lines: string = dedent`
first
second
third
`;
const text: string = dedent(`
A test argument.
`);
|
markogresak/DefinitelyTyped
|
types/dedent/dedent-tests.ts
|
TypeScript
|
mit
| 155
|
/* $Id: sph_jh.h 216 2010-06-08 09:46:57Z tp $ */
/**
* JH interface. JH is a family of functions which differ by
* their output size; this implementation defines JH for output
* sizes 224, 256, 384 and 512 bits.
*
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
*
* @file sph_jh.h
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
*/
#ifndef SPH_JH_H__
#define SPH_JH_H__
#ifdef __cplusplus
extern "C"{
#endif
#include <stddef.h>
#include "sph_types.h"
#define QSTATIC static
/**
* Output size (in bits) for JH-512.
*/
#define SPH_SIZE_jh512 512
/**
* This structure is a context for JH computations: it contains the
* intermediate values and some data from the last entered block. Once
* a JH computation has been performed, the context can be reused for
* another computation.
*
* The contents of this structure are private. A running JH computation
* can be cloned by copying the context (e.g. with a simple
* <code>memcpy()</code>).
*/
typedef struct {
#ifndef DOXYGEN_IGNORE
size_t ptr;
union {
sph_u64 wide[16];
sph_u32 narrow[32];
} H;
sph_u64 block_count;
} sph_jh_context;
/**
* Type for a JH-512 context (identical to the common context).
*/
typedef sph_jh_context sph_jh512_context;
/**
* Initialize a JH-512 context. This process performs no memory allocation.
*
* @param cc the JH-512 context (pointer to a
* <code>sph_jh512_context</code>)
*/
QSTATIC void sph_jh512_init(void *cc);
/**
* Process some data bytes. It is acceptable that <code>len</code> is zero
* (in which case this function does nothing).
*
* @param cc the JH-512 context
* @param data the input data
* @param len the input data length (in bytes)
*/
QSTATIC void sph_jh512(void *cc, const void *data, size_t len);
/**
* Terminate the current JH-512 computation and output the result into
* the provided buffer. The destination buffer must be wide enough to
* accomodate the result (64 bytes). The context is automatically
* reinitialized.
*
* @param cc the JH-512 context
* @param dst the destination buffer
*/
QSTATIC void sph_jh512_close(void *cc, void *dst);
/**
* Add a few additional bits (0 to 7) to the current computation, then
* terminate it and output the result in the provided buffer, which must
* be wide enough to accomodate the result (64 bytes). If bit number i
* in <code>ub</code> has value 2^i, then the extra bits are those
* numbered 7 downto 8-n (this is the big-endian convention at the byte
* level). The context is automatically reinitialized.
*
* @param cc the JH-512 context
* @param ub the extra bits
* @param n the number of extra bits (0 to 7)
* @param dst the destination buffer
*/
QSTATIC void sph_jh512_addbits_and_close(
void *cc, unsigned ub, unsigned n, void *dst);
#ifdef __cplusplus
}
#endif
#endif
|
RalfFreeh2/Ralf
|
x6/sph_jh.h
|
C
|
gpl-2.0
| 4,079
|
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#if !defined( __WLAN_QCT_PAL_STATUS_H )
#define __WLAN_QCT_PAL_STATUS_H
/**=========================================================================
\file wlan_qct_pal_status.h
\brief define status PAL exports. wpt = (Wlan Pal Type)
Definitions for platform independent.
Copyright 2010 (c) Qualcomm, Incorporated. All Rights Reserved.
Qualcomm Confidential and Proprietary.
========================================================================*/
typedef enum
{
/// Request succeeded!
eWLAN_PAL_STATUS_SUCCESS,
/// Request failed because system resources (other than memory) to
/// fulfill request are not available.
eWLAN_PAL_STATUS_E_RESOURCES,
/// Request failed because not enough memory is available to
/// fulfill the request.
eWLAN_PAL_STATUS_E_NOMEM,
/// Request failed because there of an invalid request. This is
/// typically the result of invalid parameters on the request.
eWLAN_PAL_STATUS_E_INVAL,
/// Request failed because handling the request would cause a
/// system fault. This error is typically returned when an
/// invalid pointer to memory is detected.
eWLAN_PAL_STATUS_E_FAULT,
/// Request failed because device or resource is busy.
eWLAN_PAL_STATUS_E_BUSY,
/// Request did not complete because it was canceled.
eWLAN_PAL_STATUS_E_CANCELED,
/// Request did not complete because it was aborted.
eWLAN_PAL_STATUS_E_ABORTED,
/// Request failed because the request is valid, though not supported
/// by the entity processing the request.
eWLAN_PAL_STATUS_E_NOSUPPORT,
/// Request failed because of an empty condition
eWLAN_PAL_STATUS_E_EMPTY,
/// Existance failure. Operation could not be completed because
/// something exists or does not exist.
eWLAN_PAL_STATUS_E_EXISTS,
/// Operation timed out
eWLAN_PAL_STATUS_E_TIMEOUT,
/// Request failed for some unknown reason. Note don't use this
/// status unless nothing else applies
eWLAN_PAL_STATUS_E_FAILURE,
} wpt_status;
#define WLAN_PAL_IS_STATUS_SUCCESS(status) ( eWLAN_PAL_STATUS_SUCCESS == (status) )
#endif // __WLAN_QCT_PAL_STATUS_H
|
keeeener/nicki
|
kernel/drivers/staging/prima/CORE/WDI/WPAL/inc/wlan_qct_pal_status.h
|
C
|
gpl-2.0
| 3,112
|
var test = require('tape');
var oldToNew = require('../index').oldToNew;
var newToOld = require('../index').newToOld;
test('plugin mappings exist', function(t) {
t.plan(2);
t.equal('cordova-plugin-device', oldToNew['org.apache.cordova.device']);
t.equal('org.apache.cordova.device', newToOld['cordova-plugin-device']);
})
|
zendey/Zendey
|
zendey/platforms/android/cordova/node_modules/cordova-common/node_modules/cordova-registry-mapper/tests/test.js
|
JavaScript
|
gpl-3.0
| 337
|
/*
* MPLS GSO Support
*
* Authors: Simon Horman (horms@verge.net.au)
*
* 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.
*
* Based on: GSO portions of net/ipv4/gre.c
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/err.h>
#include <linux/module.h>
#include <linux/netdev_features.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
static struct sk_buff *mpls_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
netdev_features_t mpls_features;
__be16 mpls_protocol;
if (unlikely(skb_shinfo(skb)->gso_type &
~(SKB_GSO_TCPV4 |
SKB_GSO_TCPV6 |
SKB_GSO_UDP |
SKB_GSO_DODGY |
SKB_GSO_TCP_ECN |
SKB_GSO_GRE |
SKB_GSO_GRE_CSUM |
SKB_GSO_IPIP |
SKB_GSO_MPLS)))
goto out;
/* Setup inner SKB. */
mpls_protocol = skb->protocol;
skb->protocol = skb->inner_protocol;
/* Push back the mac header that skb_mac_gso_segment() has pulled.
* It will be re-pulled by the call to skb_mac_gso_segment() below
*/
__skb_push(skb, skb->mac_len);
/* Segment inner packet. */
mpls_features = skb->dev->mpls_features & netif_skb_features(skb);
segs = skb_mac_gso_segment(skb, mpls_features);
/* Restore outer protocol. */
skb->protocol = mpls_protocol;
/* Re-pull the mac header that the call to skb_mac_gso_segment()
* above pulled. It will be re-pushed after returning
* skb_mac_gso_segment(), an indirect caller of this function.
*/
__skb_push(skb, skb->data - skb_mac_header(skb));
out:
return segs;
}
static int mpls_gso_send_check(struct sk_buff *skb)
{
return 0;
}
static struct packet_offload mpls_mc_offload = {
.type = cpu_to_be16(ETH_P_MPLS_MC),
.callbacks = {
.gso_send_check = mpls_gso_send_check,
.gso_segment = mpls_gso_segment,
},
};
static struct packet_offload mpls_uc_offload = {
.type = cpu_to_be16(ETH_P_MPLS_UC),
.callbacks = {
.gso_send_check = mpls_gso_send_check,
.gso_segment = mpls_gso_segment,
},
};
static int __init mpls_gso_init(void)
{
pr_info("MPLS GSO support\n");
dev_add_offload(&mpls_uc_offload);
dev_add_offload(&mpls_mc_offload);
return 0;
}
static void __exit mpls_gso_exit(void)
{
dev_remove_offload(&mpls_uc_offload);
dev_remove_offload(&mpls_mc_offload);
}
module_init(mpls_gso_init);
module_exit(mpls_gso_exit);
MODULE_DESCRIPTION("MPLS GSO support");
MODULE_AUTHOR("Simon Horman (horms@verge.net.au)");
MODULE_LICENSE("GPL");
|
tusharbehera/linux
|
net/mpls/mpls_gso.c
|
C
|
gpl-2.0
| 2,665
|
#!/bin/bash
export ARG="$1"
curl -s "https://github.com/meteor/meteor/commit/$(git log --format=%H -1 --author "$1")" | perl -nle 'm!<span class="author-name"><a href="/([^"]+)"! and do { my $name = $1; $ENV{ARG} =~ /(<.+>)/; print "GITHUB: $name $1"; exit 0 }'
|
sitexa/meteor
|
scripts/admin/find-author-github.sh
|
Shell
|
mit
| 263
|
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2018 Oleksij Rempel <linux@rempel-privat.de>
*
* Driver for Alcor Micro AU6601 and AU6621 controllers
*/
/* Note: this driver was created without any documentation. Based
* on sniffing, testing and in some cases mimic of original driver.
* As soon as some one with documentation or more experience in SD/MMC, or
* reverse engineering then me, please review this driver and question every
* thing what I did. 2018 Oleksij Rempel <linux@rempel-privat.de>
*/
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/pm.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/alcor_pci.h>
enum alcor_cookie {
COOKIE_UNMAPPED,
COOKIE_PRE_MAPPED,
COOKIE_MAPPED,
};
struct alcor_pll_conf {
unsigned int clk_src_freq;
unsigned int clk_src_reg;
unsigned int min_div;
unsigned int max_div;
};
struct alcor_sdmmc_host {
struct device *dev;
struct alcor_pci_priv *alcor_pci;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
unsigned int dma_on:1;
struct mutex cmd_mutex;
struct delayed_work timeout_work;
struct sg_mapping_iter sg_miter; /* SG state for PIO */
struct scatterlist *sg;
unsigned int blocks; /* remaining PIO blocks */
int sg_count;
u32 irq_status_sd;
unsigned char cur_power_mode;
};
static const struct alcor_pll_conf alcor_pll_cfg[] = {
/* MHZ, CLK src, max div, min div */
{ 31250000, AU6601_CLK_31_25_MHZ, 1, 511},
{ 48000000, AU6601_CLK_48_MHZ, 1, 511},
{125000000, AU6601_CLK_125_MHZ, 1, 511},
{384000000, AU6601_CLK_384_MHZ, 1, 511},
};
static inline void alcor_rmw8(struct alcor_sdmmc_host *host, unsigned int addr,
u8 clear, u8 set)
{
struct alcor_pci_priv *priv = host->alcor_pci;
u32 var;
var = alcor_read8(priv, addr);
var &= ~clear;
var |= set;
alcor_write8(priv, var, addr);
}
/* As soon as irqs are masked, some status updates may be missed.
* Use this with care.
*/
static inline void alcor_mask_sd_irqs(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
alcor_write32(priv, 0, AU6601_REG_INT_ENABLE);
}
static inline void alcor_unmask_sd_irqs(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
alcor_write32(priv, AU6601_INT_CMD_MASK | AU6601_INT_DATA_MASK |
AU6601_INT_CARD_INSERT | AU6601_INT_CARD_REMOVE |
AU6601_INT_OVER_CURRENT_ERR,
AU6601_REG_INT_ENABLE);
}
static void alcor_reset(struct alcor_sdmmc_host *host, u8 val)
{
struct alcor_pci_priv *priv = host->alcor_pci;
int i;
alcor_write8(priv, val | AU6601_BUF_CTRL_RESET,
AU6601_REG_SW_RESET);
for (i = 0; i < 100; i++) {
if (!(alcor_read8(priv, AU6601_REG_SW_RESET) & val))
return;
udelay(50);
}
dev_err(host->dev, "%s: timeout\n", __func__);
}
/*
* Perform DMA I/O of a single page.
*/
static void alcor_data_set_dma(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
u32 addr;
if (!host->sg_count)
return;
if (!host->sg) {
dev_err(host->dev, "have blocks, but no SG\n");
return;
}
if (!sg_dma_len(host->sg)) {
dev_err(host->dev, "DMA SG len == 0\n");
return;
}
addr = (u32)sg_dma_address(host->sg);
alcor_write32(priv, addr, AU6601_REG_SDMA_ADDR);
host->sg = sg_next(host->sg);
host->sg_count--;
}
static void alcor_trigger_data_transfer(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
struct mmc_data *data = host->data;
u8 ctrl = 0;
if (data->flags & MMC_DATA_WRITE)
ctrl |= AU6601_DATA_WRITE;
if (data->host_cookie == COOKIE_MAPPED) {
/*
* For DMA transfers, this function is called just once,
* at the start of the operation. The hardware can only
* perform DMA I/O on a single page at a time, so here
* we kick off the transfer with the first page, and expect
* subsequent pages to be transferred upon IRQ events
* indicating that the single-page DMA was completed.
*/
alcor_data_set_dma(host);
ctrl |= AU6601_DATA_DMA_MODE;
host->dma_on = 1;
alcor_write32(priv, data->sg_count * 0x1000,
AU6601_REG_BLOCK_SIZE);
} else {
/*
* For PIO transfers, we break down each operation
* into several sector-sized transfers. When one sector has
* complete, the IRQ handler will call this function again
* to kick off the transfer of the next sector.
*/
alcor_write32(priv, data->blksz, AU6601_REG_BLOCK_SIZE);
}
alcor_write8(priv, ctrl | AU6601_DATA_START_XFER,
AU6601_DATA_XFER_CTRL);
}
static void alcor_trf_block_pio(struct alcor_sdmmc_host *host, bool read)
{
struct alcor_pci_priv *priv = host->alcor_pci;
size_t blksize, len;
u8 *buf;
if (!host->blocks)
return;
if (host->dma_on) {
dev_err(host->dev, "configured DMA but got PIO request.\n");
return;
}
if (!!(host->data->flags & MMC_DATA_READ) != read) {
dev_err(host->dev, "got unexpected direction %i != %i\n",
!!(host->data->flags & MMC_DATA_READ), read);
}
if (!sg_miter_next(&host->sg_miter))
return;
blksize = host->data->blksz;
len = min(host->sg_miter.length, blksize);
dev_dbg(host->dev, "PIO, %s block size: 0x%zx\n",
read ? "read" : "write", blksize);
host->sg_miter.consumed = len;
host->blocks--;
buf = host->sg_miter.addr;
if (read)
ioread32_rep(priv->iobase + AU6601_REG_BUFFER, buf, len >> 2);
else
iowrite32_rep(priv->iobase + AU6601_REG_BUFFER, buf, len >> 2);
sg_miter_stop(&host->sg_miter);
}
static void alcor_prepare_sg_miter(struct alcor_sdmmc_host *host)
{
unsigned int flags = SG_MITER_ATOMIC;
struct mmc_data *data = host->data;
if (data->flags & MMC_DATA_READ)
flags |= SG_MITER_TO_SG;
else
flags |= SG_MITER_FROM_SG;
sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);
}
static void alcor_prepare_data(struct alcor_sdmmc_host *host,
struct mmc_command *cmd)
{
struct alcor_pci_priv *priv = host->alcor_pci;
struct mmc_data *data = cmd->data;
if (!data)
return;
host->data = data;
host->data->bytes_xfered = 0;
host->blocks = data->blocks;
host->sg = data->sg;
host->sg_count = data->sg_count;
dev_dbg(host->dev, "prepare DATA: sg %i, blocks: %i\n",
host->sg_count, host->blocks);
if (data->host_cookie != COOKIE_MAPPED)
alcor_prepare_sg_miter(host);
alcor_write8(priv, 0, AU6601_DATA_XFER_CTRL);
}
static void alcor_send_cmd(struct alcor_sdmmc_host *host,
struct mmc_command *cmd, bool set_timeout)
{
struct alcor_pci_priv *priv = host->alcor_pci;
unsigned long timeout = 0;
u8 ctrl = 0;
host->cmd = cmd;
alcor_prepare_data(host, cmd);
dev_dbg(host->dev, "send CMD. opcode: 0x%02x, arg; 0x%08x\n",
cmd->opcode, cmd->arg);
alcor_write8(priv, cmd->opcode | 0x40, AU6601_REG_CMD_OPCODE);
alcor_write32be(priv, cmd->arg, AU6601_REG_CMD_ARG);
switch (mmc_resp_type(cmd)) {
case MMC_RSP_NONE:
ctrl = AU6601_CMD_NO_RESP;
break;
case MMC_RSP_R1:
ctrl = AU6601_CMD_6_BYTE_CRC;
break;
case MMC_RSP_R1B:
ctrl = AU6601_CMD_6_BYTE_CRC | AU6601_CMD_STOP_WAIT_RDY;
break;
case MMC_RSP_R2:
ctrl = AU6601_CMD_17_BYTE_CRC;
break;
case MMC_RSP_R3:
ctrl = AU6601_CMD_6_BYTE_WO_CRC;
break;
default:
dev_err(host->dev, "%s: cmd->flag (0x%02x) is not valid\n",
mmc_hostname(mmc_from_priv(host)), mmc_resp_type(cmd));
break;
}
if (set_timeout) {
if (!cmd->data && cmd->busy_timeout)
timeout = cmd->busy_timeout;
else
timeout = 10000;
schedule_delayed_work(&host->timeout_work,
msecs_to_jiffies(timeout));
}
dev_dbg(host->dev, "xfer ctrl: 0x%02x; timeout: %lu\n", ctrl, timeout);
alcor_write8(priv, ctrl | AU6601_CMD_START_XFER,
AU6601_CMD_XFER_CTRL);
}
static void alcor_request_complete(struct alcor_sdmmc_host *host,
bool cancel_timeout)
{
struct mmc_request *mrq;
/*
* If this work gets rescheduled while running, it will
* be run again afterwards but without any active request.
*/
if (!host->mrq)
return;
if (cancel_timeout)
cancel_delayed_work(&host->timeout_work);
mrq = host->mrq;
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
host->dma_on = 0;
mmc_request_done(mmc_from_priv(host), mrq);
}
static void alcor_finish_data(struct alcor_sdmmc_host *host)
{
struct mmc_data *data;
data = host->data;
host->data = NULL;
host->dma_on = 0;
/*
* The specification states that the block count register must
* be updated, but it does not specify at what point in the
* data flow. That makes the register entirely useless to read
* back so we have to assume that nothing made it to the card
* in the event of an error.
*/
if (data->error)
data->bytes_xfered = 0;
else
data->bytes_xfered = data->blksz * data->blocks;
/*
* Need to send CMD12 if -
* a) open-ended multiblock transfer (no CMD23)
* b) error in multiblock transfer
*/
if (data->stop &&
(data->error ||
!host->mrq->sbc)) {
/*
* The controller needs a reset of internal state machines
* upon error conditions.
*/
if (data->error)
alcor_reset(host, AU6601_RESET_CMD | AU6601_RESET_DATA);
alcor_unmask_sd_irqs(host);
alcor_send_cmd(host, data->stop, false);
return;
}
alcor_request_complete(host, 1);
}
static void alcor_err_irq(struct alcor_sdmmc_host *host, u32 intmask)
{
dev_dbg(host->dev, "ERR IRQ %x\n", intmask);
if (host->cmd) {
if (intmask & AU6601_INT_CMD_TIMEOUT_ERR)
host->cmd->error = -ETIMEDOUT;
else
host->cmd->error = -EILSEQ;
}
if (host->data) {
if (intmask & AU6601_INT_DATA_TIMEOUT_ERR)
host->data->error = -ETIMEDOUT;
else
host->data->error = -EILSEQ;
host->data->bytes_xfered = 0;
}
alcor_reset(host, AU6601_RESET_CMD | AU6601_RESET_DATA);
alcor_request_complete(host, 1);
}
static int alcor_cmd_irq_done(struct alcor_sdmmc_host *host, u32 intmask)
{
struct alcor_pci_priv *priv = host->alcor_pci;
intmask &= AU6601_INT_CMD_END;
if (!intmask)
return true;
/* got CMD_END but no CMD is in progress, wake thread an process the
* error
*/
if (!host->cmd)
return false;
if (host->cmd->flags & MMC_RSP_PRESENT) {
struct mmc_command *cmd = host->cmd;
cmd->resp[0] = alcor_read32be(priv, AU6601_REG_CMD_RSP0);
dev_dbg(host->dev, "RSP0: 0x%04x\n", cmd->resp[0]);
if (host->cmd->flags & MMC_RSP_136) {
cmd->resp[1] =
alcor_read32be(priv, AU6601_REG_CMD_RSP1);
cmd->resp[2] =
alcor_read32be(priv, AU6601_REG_CMD_RSP2);
cmd->resp[3] =
alcor_read32be(priv, AU6601_REG_CMD_RSP3);
dev_dbg(host->dev, "RSP1,2,3: 0x%04x 0x%04x 0x%04x\n",
cmd->resp[1], cmd->resp[2], cmd->resp[3]);
}
}
host->cmd->error = 0;
/* Processed actual command. */
if (!host->data)
return false;
alcor_trigger_data_transfer(host);
host->cmd = NULL;
return true;
}
static void alcor_cmd_irq_thread(struct alcor_sdmmc_host *host, u32 intmask)
{
intmask &= AU6601_INT_CMD_END;
if (!intmask)
return;
if (!host->cmd && intmask & AU6601_INT_CMD_END) {
dev_dbg(host->dev, "Got command interrupt 0x%08x even though no command operation was in progress.\n",
intmask);
}
/* Processed actual command. */
if (!host->data)
alcor_request_complete(host, 1);
else
alcor_trigger_data_transfer(host);
host->cmd = NULL;
}
static int alcor_data_irq_done(struct alcor_sdmmc_host *host, u32 intmask)
{
u32 tmp;
intmask &= AU6601_INT_DATA_MASK;
/* nothing here to do */
if (!intmask)
return 1;
/* we was too fast and got DATA_END after it was processed?
* lets ignore it for now.
*/
if (!host->data && intmask == AU6601_INT_DATA_END)
return 1;
/* looks like an error, so lets handle it. */
if (!host->data)
return 0;
tmp = intmask & (AU6601_INT_READ_BUF_RDY | AU6601_INT_WRITE_BUF_RDY
| AU6601_INT_DMA_END);
switch (tmp) {
case 0:
break;
case AU6601_INT_READ_BUF_RDY:
alcor_trf_block_pio(host, true);
return 1;
case AU6601_INT_WRITE_BUF_RDY:
alcor_trf_block_pio(host, false);
return 1;
case AU6601_INT_DMA_END:
if (!host->sg_count)
break;
alcor_data_set_dma(host);
break;
default:
dev_err(host->dev, "Got READ_BUF_RDY and WRITE_BUF_RDY at same time\n");
break;
}
if (intmask & AU6601_INT_DATA_END) {
if (!host->dma_on && host->blocks) {
alcor_trigger_data_transfer(host);
return 1;
} else {
return 0;
}
}
return 1;
}
static void alcor_data_irq_thread(struct alcor_sdmmc_host *host, u32 intmask)
{
intmask &= AU6601_INT_DATA_MASK;
if (!intmask)
return;
if (!host->data) {
dev_dbg(host->dev, "Got data interrupt 0x%08x even though no data operation was in progress.\n",
intmask);
alcor_reset(host, AU6601_RESET_DATA);
return;
}
if (alcor_data_irq_done(host, intmask))
return;
if ((intmask & AU6601_INT_DATA_END) || !host->blocks ||
(host->dma_on && !host->sg_count))
alcor_finish_data(host);
}
static void alcor_cd_irq(struct alcor_sdmmc_host *host, u32 intmask)
{
dev_dbg(host->dev, "card %s\n",
intmask & AU6601_INT_CARD_REMOVE ? "removed" : "inserted");
if (host->mrq) {
dev_dbg(host->dev, "cancel all pending tasks.\n");
if (host->data)
host->data->error = -ENOMEDIUM;
if (host->cmd)
host->cmd->error = -ENOMEDIUM;
else
host->mrq->cmd->error = -ENOMEDIUM;
alcor_request_complete(host, 1);
}
mmc_detect_change(mmc_from_priv(host), msecs_to_jiffies(1));
}
static irqreturn_t alcor_irq_thread(int irq, void *d)
{
struct alcor_sdmmc_host *host = d;
irqreturn_t ret = IRQ_HANDLED;
u32 intmask, tmp;
mutex_lock(&host->cmd_mutex);
intmask = host->irq_status_sd;
/* some thing bad */
if (unlikely(!intmask || AU6601_INT_ALL_MASK == intmask)) {
dev_dbg(host->dev, "unexpected IRQ: 0x%04x\n", intmask);
ret = IRQ_NONE;
goto exit;
}
tmp = intmask & (AU6601_INT_CMD_MASK | AU6601_INT_DATA_MASK);
if (tmp) {
if (tmp & AU6601_INT_ERROR_MASK)
alcor_err_irq(host, tmp);
else {
alcor_cmd_irq_thread(host, tmp);
alcor_data_irq_thread(host, tmp);
}
intmask &= ~(AU6601_INT_CMD_MASK | AU6601_INT_DATA_MASK);
}
if (intmask & (AU6601_INT_CARD_INSERT | AU6601_INT_CARD_REMOVE)) {
alcor_cd_irq(host, intmask);
intmask &= ~(AU6601_INT_CARD_INSERT | AU6601_INT_CARD_REMOVE);
}
if (intmask & AU6601_INT_OVER_CURRENT_ERR) {
dev_warn(host->dev,
"warning: over current detected!\n");
intmask &= ~AU6601_INT_OVER_CURRENT_ERR;
}
if (intmask)
dev_dbg(host->dev, "got not handled IRQ: 0x%04x\n", intmask);
exit:
mutex_unlock(&host->cmd_mutex);
alcor_unmask_sd_irqs(host);
return ret;
}
static irqreturn_t alcor_irq(int irq, void *d)
{
struct alcor_sdmmc_host *host = d;
struct alcor_pci_priv *priv = host->alcor_pci;
u32 status, tmp;
irqreturn_t ret;
int cmd_done, data_done;
status = alcor_read32(priv, AU6601_REG_INT_STATUS);
if (!status)
return IRQ_NONE;
alcor_write32(priv, status, AU6601_REG_INT_STATUS);
tmp = status & (AU6601_INT_READ_BUF_RDY | AU6601_INT_WRITE_BUF_RDY
| AU6601_INT_DATA_END | AU6601_INT_DMA_END
| AU6601_INT_CMD_END);
if (tmp == status) {
cmd_done = alcor_cmd_irq_done(host, tmp);
data_done = alcor_data_irq_done(host, tmp);
/* use fast path for simple tasks */
if (cmd_done && data_done) {
ret = IRQ_HANDLED;
goto alcor_irq_done;
}
}
host->irq_status_sd = status;
ret = IRQ_WAKE_THREAD;
alcor_mask_sd_irqs(host);
alcor_irq_done:
return ret;
}
static void alcor_set_clock(struct alcor_sdmmc_host *host, unsigned int clock)
{
struct alcor_pci_priv *priv = host->alcor_pci;
int i, diff = 0x7fffffff, tmp_clock = 0;
u16 clk_src = 0;
u8 clk_div = 0;
if (clock == 0) {
alcor_write16(priv, 0, AU6601_CLK_SELECT);
return;
}
for (i = 0; i < ARRAY_SIZE(alcor_pll_cfg); i++) {
unsigned int tmp_div, tmp_diff;
const struct alcor_pll_conf *cfg = &alcor_pll_cfg[i];
tmp_div = DIV_ROUND_UP(cfg->clk_src_freq, clock);
if (cfg->min_div > tmp_div || tmp_div > cfg->max_div)
continue;
tmp_clock = DIV_ROUND_UP(cfg->clk_src_freq, tmp_div);
tmp_diff = abs(clock - tmp_clock);
if (tmp_diff < diff) {
diff = tmp_diff;
clk_src = cfg->clk_src_reg;
clk_div = tmp_div;
}
}
clk_src |= ((clk_div - 1) << 8);
clk_src |= AU6601_CLK_ENABLE;
dev_dbg(host->dev, "set freq %d cal freq %d, use div %d, mod %x\n",
clock, tmp_clock, clk_div, clk_src);
alcor_write16(priv, clk_src, AU6601_CLK_SELECT);
}
static void alcor_set_timing(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
if (ios->timing == MMC_TIMING_LEGACY) {
alcor_rmw8(host, AU6601_CLK_DELAY,
AU6601_CLK_POSITIVE_EDGE_ALL, 0);
} else {
alcor_rmw8(host, AU6601_CLK_DELAY,
0, AU6601_CLK_POSITIVE_EDGE_ALL);
}
}
static void alcor_set_bus_width(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct alcor_pci_priv *priv = host->alcor_pci;
if (ios->bus_width == MMC_BUS_WIDTH_1) {
alcor_write8(priv, 0, AU6601_REG_BUS_CTRL);
} else if (ios->bus_width == MMC_BUS_WIDTH_4) {
alcor_write8(priv, AU6601_BUS_WIDTH_4BIT,
AU6601_REG_BUS_CTRL);
} else
dev_err(host->dev, "Unknown BUS mode\n");
}
static int alcor_card_busy(struct mmc_host *mmc)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct alcor_pci_priv *priv = host->alcor_pci;
u8 status;
/* Check whether dat[0:3] low */
status = alcor_read8(priv, AU6601_DATA_PIN_STATE);
return !(status & AU6601_BUS_STAT_DAT_MASK);
}
static int alcor_get_cd(struct mmc_host *mmc)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct alcor_pci_priv *priv = host->alcor_pci;
u8 detect;
detect = alcor_read8(priv, AU6601_DETECT_STATUS)
& AU6601_DETECT_STATUS_M;
/* check if card is present then send command and data */
return (detect == AU6601_SD_DETECTED);
}
static int alcor_get_ro(struct mmc_host *mmc)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct alcor_pci_priv *priv = host->alcor_pci;
u8 status;
/* get write protect pin status */
status = alcor_read8(priv, AU6601_INTERFACE_MODE_CTRL);
return !!(status & AU6601_SD_CARD_WP);
}
static void alcor_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
mutex_lock(&host->cmd_mutex);
host->mrq = mrq;
/* check if card is present then send command and data */
if (alcor_get_cd(mmc))
alcor_send_cmd(host, mrq->cmd, true);
else {
mrq->cmd->error = -ENOMEDIUM;
alcor_request_complete(host, 1);
}
mutex_unlock(&host->cmd_mutex);
}
static void alcor_pre_req(struct mmc_host *mmc,
struct mmc_request *mrq)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct mmc_data *data = mrq->data;
struct mmc_command *cmd = mrq->cmd;
struct scatterlist *sg;
unsigned int i, sg_len;
if (!data || !cmd)
return;
data->host_cookie = COOKIE_UNMAPPED;
/* FIXME: looks like the DMA engine works only with CMD18 */
if (cmd->opcode != MMC_READ_MULTIPLE_BLOCK
&& cmd->opcode != MMC_WRITE_MULTIPLE_BLOCK)
return;
/*
* We don't do DMA on "complex" transfers, i.e. with
* non-word-aligned buffers or lengths. A future improvement
* could be made to use temporary DMA bounce-buffers when these
* requirements are not met.
*
* Also, we don't bother with all the DMA setup overhead for
* short transfers.
*/
if (data->blocks * data->blksz < AU6601_MAX_DMA_BLOCK_SIZE)
return;
if (data->blksz & 3)
return;
for_each_sg(data->sg, sg, data->sg_len, i) {
if (sg->length != AU6601_MAX_DMA_BLOCK_SIZE)
return;
if (sg->offset != 0)
return;
}
/* This data might be unmapped at this time */
sg_len = dma_map_sg(host->dev, data->sg, data->sg_len,
mmc_get_dma_dir(data));
if (sg_len)
data->host_cookie = COOKIE_MAPPED;
data->sg_count = sg_len;
}
static void alcor_post_req(struct mmc_host *mmc,
struct mmc_request *mrq,
int err)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct mmc_data *data = mrq->data;
if (!data)
return;
if (data->host_cookie == COOKIE_MAPPED) {
dma_unmap_sg(host->dev,
data->sg,
data->sg_len,
mmc_get_dma_dir(data));
}
data->host_cookie = COOKIE_UNMAPPED;
}
static void alcor_set_power_mode(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
struct alcor_pci_priv *priv = host->alcor_pci;
switch (ios->power_mode) {
case MMC_POWER_OFF:
alcor_set_clock(host, ios->clock);
/* set all pins to input */
alcor_write8(priv, 0, AU6601_OUTPUT_ENABLE);
/* turn of VDD */
alcor_write8(priv, 0, AU6601_POWER_CONTROL);
break;
case MMC_POWER_UP:
break;
case MMC_POWER_ON:
/* This is most trickiest part. The order and timings of
* instructions seems to play important role. Any changes may
* confuse internal state engine if this HW.
* FIXME: If we will ever get access to documentation, then this
* part should be reviewed again.
*/
/* enable SD card mode */
alcor_write8(priv, AU6601_SD_CARD,
AU6601_ACTIVE_CTRL);
/* set signal voltage to 3.3V */
alcor_write8(priv, 0, AU6601_OPT);
/* no documentation about clk delay, for now just try to mimic
* original driver.
*/
alcor_write8(priv, 0x20, AU6601_CLK_DELAY);
/* set BUS width to 1 bit */
alcor_write8(priv, 0, AU6601_REG_BUS_CTRL);
/* set CLK first time */
alcor_set_clock(host, ios->clock);
/* power on VDD */
alcor_write8(priv, AU6601_SD_CARD,
AU6601_POWER_CONTROL);
/* wait until the CLK will get stable */
mdelay(20);
/* set CLK again, mimic original driver. */
alcor_set_clock(host, ios->clock);
/* enable output */
alcor_write8(priv, AU6601_SD_CARD,
AU6601_OUTPUT_ENABLE);
/* The clk will not work on au6621. We need to trigger data
* transfer.
*/
alcor_write8(priv, AU6601_DATA_WRITE,
AU6601_DATA_XFER_CTRL);
/* configure timeout. Not clear what exactly it means. */
alcor_write8(priv, 0x7d, AU6601_TIME_OUT_CTRL);
mdelay(100);
break;
default:
dev_err(host->dev, "Unknown power parameter\n");
}
}
static void alcor_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
mutex_lock(&host->cmd_mutex);
dev_dbg(host->dev, "set ios. bus width: %x, power mode: %x\n",
ios->bus_width, ios->power_mode);
if (ios->power_mode != host->cur_power_mode) {
alcor_set_power_mode(mmc, ios);
host->cur_power_mode = ios->power_mode;
} else {
alcor_set_timing(mmc, ios);
alcor_set_bus_width(mmc, ios);
alcor_set_clock(host, ios->clock);
}
mutex_unlock(&host->cmd_mutex);
}
static int alcor_signal_voltage_switch(struct mmc_host *mmc,
struct mmc_ios *ios)
{
struct alcor_sdmmc_host *host = mmc_priv(mmc);
mutex_lock(&host->cmd_mutex);
switch (ios->signal_voltage) {
case MMC_SIGNAL_VOLTAGE_330:
alcor_rmw8(host, AU6601_OPT, AU6601_OPT_SD_18V, 0);
break;
case MMC_SIGNAL_VOLTAGE_180:
alcor_rmw8(host, AU6601_OPT, 0, AU6601_OPT_SD_18V);
break;
default:
/* No signal voltage switch required */
break;
}
mutex_unlock(&host->cmd_mutex);
return 0;
}
static const struct mmc_host_ops alcor_sdc_ops = {
.card_busy = alcor_card_busy,
.get_cd = alcor_get_cd,
.get_ro = alcor_get_ro,
.post_req = alcor_post_req,
.pre_req = alcor_pre_req,
.request = alcor_request,
.set_ios = alcor_set_ios,
.start_signal_voltage_switch = alcor_signal_voltage_switch,
};
static void alcor_timeout_timer(struct work_struct *work)
{
struct delayed_work *d = to_delayed_work(work);
struct alcor_sdmmc_host *host = container_of(d, struct alcor_sdmmc_host,
timeout_work);
mutex_lock(&host->cmd_mutex);
dev_dbg(host->dev, "triggered timeout\n");
if (host->mrq) {
dev_err(host->dev, "Timeout waiting for hardware interrupt.\n");
if (host->data) {
host->data->error = -ETIMEDOUT;
} else {
if (host->cmd)
host->cmd->error = -ETIMEDOUT;
else
host->mrq->cmd->error = -ETIMEDOUT;
}
alcor_reset(host, AU6601_RESET_CMD | AU6601_RESET_DATA);
alcor_request_complete(host, 0);
}
mutex_unlock(&host->cmd_mutex);
}
static void alcor_hw_init(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
struct alcor_dev_cfg *cfg = priv->cfg;
/* FIXME: This part is a mimics HW init of original driver.
* If we will ever get access to documentation, then this part
* should be reviewed again.
*/
/* reset command state engine */
alcor_reset(host, AU6601_RESET_CMD);
alcor_write8(priv, 0, AU6601_DMA_BOUNDARY);
/* enable sd card mode */
alcor_write8(priv, AU6601_SD_CARD, AU6601_ACTIVE_CTRL);
/* set BUS width to 1 bit */
alcor_write8(priv, 0, AU6601_REG_BUS_CTRL);
/* reset data state engine */
alcor_reset(host, AU6601_RESET_DATA);
/* Not sure if a voodoo with AU6601_DMA_BOUNDARY is really needed */
alcor_write8(priv, 0, AU6601_DMA_BOUNDARY);
alcor_write8(priv, 0, AU6601_INTERFACE_MODE_CTRL);
/* not clear what we are doing here. */
alcor_write8(priv, 0x44, AU6601_PAD_DRIVE0);
alcor_write8(priv, 0x44, AU6601_PAD_DRIVE1);
alcor_write8(priv, 0x00, AU6601_PAD_DRIVE2);
/* for 6601 - dma_boundary; for 6621 - dma_page_cnt
* exact meaning of this register is not clear.
*/
alcor_write8(priv, cfg->dma, AU6601_DMA_BOUNDARY);
/* make sure all pins are set to input and VDD is off */
alcor_write8(priv, 0, AU6601_OUTPUT_ENABLE);
alcor_write8(priv, 0, AU6601_POWER_CONTROL);
alcor_write8(priv, AU6601_DETECT_EN, AU6601_DETECT_STATUS);
/* now we should be safe to enable IRQs */
alcor_unmask_sd_irqs(host);
}
static void alcor_hw_uninit(struct alcor_sdmmc_host *host)
{
struct alcor_pci_priv *priv = host->alcor_pci;
alcor_mask_sd_irqs(host);
alcor_reset(host, AU6601_RESET_CMD | AU6601_RESET_DATA);
alcor_write8(priv, 0, AU6601_DETECT_STATUS);
alcor_write8(priv, 0, AU6601_OUTPUT_ENABLE);
alcor_write8(priv, 0, AU6601_POWER_CONTROL);
alcor_write8(priv, 0, AU6601_OPT);
}
static void alcor_init_mmc(struct alcor_sdmmc_host *host)
{
struct mmc_host *mmc = mmc_from_priv(host);
mmc->f_min = AU6601_MIN_CLOCK;
mmc->f_max = AU6601_MAX_CLOCK;
mmc->ocr_avail = MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_SD_HIGHSPEED
| MMC_CAP_UHS_SDR12 | MMC_CAP_UHS_SDR25 | MMC_CAP_UHS_SDR50
| MMC_CAP_UHS_SDR104 | MMC_CAP_UHS_DDR50;
mmc->caps2 = MMC_CAP2_NO_SDIO;
mmc->ops = &alcor_sdc_ops;
/* The hardware does DMA data transfer of 4096 bytes to/from a single
* buffer address. Scatterlists are not supported at the hardware
* level, however we can work with them at the driver level,
* provided that each segment is exactly 4096 bytes in size.
* Upon DMA completion of a single segment (signalled via IRQ), we
* immediately proceed to transfer the next segment from the
* scatterlist.
*
* The overall request is limited to 240 sectors, matching the
* original vendor driver.
*/
mmc->max_segs = AU6601_MAX_DMA_SEGMENTS;
mmc->max_seg_size = AU6601_MAX_DMA_BLOCK_SIZE;
mmc->max_blk_count = 240;
mmc->max_req_size = mmc->max_blk_count * mmc->max_blk_size;
dma_set_max_seg_size(host->dev, mmc->max_seg_size);
}
static int alcor_pci_sdmmc_drv_probe(struct platform_device *pdev)
{
struct alcor_pci_priv *priv = pdev->dev.platform_data;
struct mmc_host *mmc;
struct alcor_sdmmc_host *host;
int ret;
mmc = mmc_alloc_host(sizeof(*host), &pdev->dev);
if (!mmc) {
dev_err(&pdev->dev, "Can't allocate MMC\n");
return -ENOMEM;
}
host = mmc_priv(mmc);
host->dev = &pdev->dev;
host->cur_power_mode = MMC_POWER_UNDEFINED;
host->alcor_pci = priv;
/* make sure irqs are disabled */
alcor_write32(priv, 0, AU6601_REG_INT_ENABLE);
alcor_write32(priv, 0, AU6601_MS_INT_ENABLE);
ret = devm_request_threaded_irq(&pdev->dev, priv->irq,
alcor_irq, alcor_irq_thread, IRQF_SHARED,
DRV_NAME_ALCOR_PCI_SDMMC, host);
if (ret) {
dev_err(&pdev->dev, "Failed to get irq for data line\n");
goto free_host;
}
mutex_init(&host->cmd_mutex);
INIT_DELAYED_WORK(&host->timeout_work, alcor_timeout_timer);
alcor_init_mmc(host);
alcor_hw_init(host);
dev_set_drvdata(&pdev->dev, host);
mmc_add_host(mmc);
return 0;
free_host:
mmc_free_host(mmc);
return ret;
}
static int alcor_pci_sdmmc_drv_remove(struct platform_device *pdev)
{
struct alcor_sdmmc_host *host = dev_get_drvdata(&pdev->dev);
struct mmc_host *mmc = mmc_from_priv(host);
if (cancel_delayed_work_sync(&host->timeout_work))
alcor_request_complete(host, 0);
alcor_hw_uninit(host);
mmc_remove_host(mmc);
mmc_free_host(mmc);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int alcor_pci_sdmmc_suspend(struct device *dev)
{
struct alcor_sdmmc_host *host = dev_get_drvdata(dev);
if (cancel_delayed_work_sync(&host->timeout_work))
alcor_request_complete(host, 0);
alcor_hw_uninit(host);
return 0;
}
static int alcor_pci_sdmmc_resume(struct device *dev)
{
struct alcor_sdmmc_host *host = dev_get_drvdata(dev);
alcor_hw_init(host);
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(alcor_mmc_pm_ops, alcor_pci_sdmmc_suspend,
alcor_pci_sdmmc_resume);
static const struct platform_device_id alcor_pci_sdmmc_ids[] = {
{
.name = DRV_NAME_ALCOR_PCI_SDMMC,
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(platform, alcor_pci_sdmmc_ids);
static struct platform_driver alcor_pci_sdmmc_driver = {
.probe = alcor_pci_sdmmc_drv_probe,
.remove = alcor_pci_sdmmc_drv_remove,
.id_table = alcor_pci_sdmmc_ids,
.driver = {
.name = DRV_NAME_ALCOR_PCI_SDMMC,
.probe_type = PROBE_PREFER_ASYNCHRONOUS,
.pm = &alcor_mmc_pm_ops
},
};
module_platform_driver(alcor_pci_sdmmc_driver);
MODULE_AUTHOR("Oleksij Rempel <linux@rempel-privat.de>");
MODULE_DESCRIPTION("PCI driver for Alcor Micro AU6601 Secure Digital Host Controller Interface");
MODULE_LICENSE("GPL");
|
GuillaumeSeren/linux
|
drivers/mmc/host/alcor.c
|
C
|
gpl-2.0
| 29,650
|
/*!
* Qoopido.js library v3.4.3, 2014-6-11
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*//*!
* Qoopido.js library
*
* version: 3.4.3
* date: 2014-6-11
* author: Dirk Lueth <info@qoopido.com>
* website: https://github.com/dlueth/qoopido.js
*
* Copyright (c) 2014 Dirk Lueth
*
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*/
!function(t){window.qoopido.register("support/element/canvas/todataurl",t,["../../../support","../canvas"])}(function(t,e,n,o,a,s,r){"use strict";var c=t.support;return c.addTest("/element/canvas/todataurl",function(e){t["support/element/canvas"]().then(function(){var t=c.pool?c.pool.obtain("canvas"):s.createElement("canvas");t.toDataURL!==r?e.resolve():e.reject(),t.dispose&&t.dispose()},function(){e.reject()}).done()})});
|
tonytomov/cdnjs
|
ajax/libs/qoopido.js/3.4.3/support/element/canvas/todataurl.js
|
JavaScript
|
mit
| 903
|
// SPDX-License-Identifier: GPL-2.0
/* Copyright(c) 2009-2012 Realtek Corporation.*/
#include "../wifi.h"
#include "../usb.h"
#include "reg.h"
#include "led.h"
static void _rtl92cu_init_led(struct ieee80211_hw *hw,
struct rtl_led *pled, enum rtl_led_pin ledpin)
{
pled->hw = hw;
pled->ledpin = ledpin;
pled->ledon = false;
}
static void rtl92cu_deinit_led(struct rtl_led *pled)
{
}
void rtl92cu_sw_led_on(struct ieee80211_hw *hw, struct rtl_led *pled)
{
u8 ledcfg;
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl_dbg(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n",
REG_LEDCFG2, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
rtl_write_byte(rtlpriv,
REG_LEDCFG2, (ledcfg & 0xf0) | BIT(5) | BIT(6));
break;
case LED_PIN_LED1:
rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg & 0x0f) | BIT(5));
break;
default:
pr_err("switch case %#x not processed\n",
pled->ledpin);
break;
}
pled->ledon = true;
}
void rtl92cu_sw_led_off(struct ieee80211_hw *hw, struct rtl_led *pled)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 ledcfg;
rtl_dbg(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n",
REG_LEDCFG2, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
ledcfg &= 0xf0;
if (rtlpriv->ledctl.led_opendrain)
rtl_write_byte(rtlpriv, REG_LEDCFG2,
(ledcfg | BIT(1) | BIT(5) | BIT(6)));
else
rtl_write_byte(rtlpriv, REG_LEDCFG2,
(ledcfg | BIT(3) | BIT(5) | BIT(6)));
break;
case LED_PIN_LED1:
ledcfg &= 0x0f;
rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg | BIT(3)));
break;
default:
pr_err("switch case %#x not processed\n",
pled->ledpin);
break;
}
pled->ledon = false;
}
void rtl92cu_init_sw_leds(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
_rtl92cu_init_led(hw, &rtlpriv->ledctl.sw_led0, LED_PIN_LED0);
_rtl92cu_init_led(hw, &rtlpriv->ledctl.sw_led1, LED_PIN_LED1);
}
void rtl92cu_deinit_sw_leds(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtl92cu_deinit_led(&rtlpriv->ledctl.sw_led0);
rtl92cu_deinit_led(&rtlpriv->ledctl.sw_led1);
}
static void _rtl92cu_sw_led_control(struct ieee80211_hw *hw,
enum led_ctl_mode ledaction)
{
}
void rtl92cu_led_control(struct ieee80211_hw *hw,
enum led_ctl_mode ledaction)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
if ((ppsc->rfoff_reason > RF_CHANGE_BY_PS) &&
(ledaction == LED_CTL_TX ||
ledaction == LED_CTL_RX ||
ledaction == LED_CTL_SITE_SURVEY ||
ledaction == LED_CTL_LINK ||
ledaction == LED_CTL_NO_LINK ||
ledaction == LED_CTL_START_TO_LINK ||
ledaction == LED_CTL_POWER_ON)) {
return;
}
rtl_dbg(rtlpriv, COMP_LED, DBG_LOUD, "ledaction %d\n", ledaction);
_rtl92cu_sw_led_control(hw, ledaction);
}
|
HinTak/linux
|
drivers/net/wireless/realtek/rtlwifi/rtl8192cu/led.c
|
C
|
gpl-2.0
| 2,997
|
var a = {
echo(c) {
return c;
}
};
assert.strictEqual(a.echo(1), 1);
|
stefanpenner/6to5
|
test/fixtures/esnext/es6-object-concise/method-arguments.js
|
JavaScript
|
mit
| 78
|
/**
* @file
* This file contains most of the code for the configuration page.
*/
// Create the drupal ShareThis object for clean code and namespacing:
var drupal_st = {
// These are handlerd for updating the widget pic class.
multiW: function() {
jQuery(".st_widgetPic").addClass("st_multi");
},
classicW: function() {
jQuery(".st_widgetPic").removeClass("st_multi");
},
// These are the handlers for updating the button pic class (stbc = sharethisbuttonclass).
smallChicklet: function () {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_");
},
largeChicklet: function () {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_large");
},
hcount: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_hcount");
},
vcount: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_vcount");
},
button: function() {
drupal_st.removeButtonClasses();
jQuery("#stb_sprite").addClass("stbc_button");
},
// This is a helper function for updating button pictures.
removeButtonClasses: function() {
var toRemove = jQuery("#stb_sprite");
toRemove.removeClass("stbc_");
toRemove.removeClass("stbc_large");
toRemove.removeClass("stbc_hcount");
toRemove.removeClass("stbc_vcount");
toRemove.removeClass("stbc_button");
},
//Write helper functions for saving:
getWidget: function () {
return jQuery(".st_widgetPic").hasClass("st_multiW") ? '5x': '4x';
},
getButtons: function () {
var selectedButton = 'large';
var buttonButtons = jQuery(".st_wIm");
buttonButtons.each(function () {
if (jQuery(this).hasClass("st_select")) {
selectedButton = jQuery(this).attr("id").substring(3);
}
});
console.log(selectedButton);
return selectedButton;
},
setupServiceText: function () {
jQuery("#edit-sharethis-service-option").css({display:"none"});
},
// Function to add various events to our html form elements
addEvents: function() {
jQuery("#edit-sharethis-widget-option-st-multi").click(drupal_st.multiW);
jQuery("#edit-sharethis-widget-option-st-direct").click(drupal_st.classicW);
jQuery("#edit-sharethis-button-option-stbc-").click(drupal_st.smallChicklet);
jQuery("#edit-sharethis-button-option-stbc-large").click(drupal_st.largeChicklet);
jQuery("#edit-sharethis-button-option-stbc-hcount").click(drupal_st.hcount);
jQuery("#edit-sharethis-button-option-stbc-vcount").click(drupal_st.vcount);
jQuery("#edit-sharethis-button-option-stbc-button").click(drupal_st.button);
jQuery(".st_formButtonSave").click(drupal_st.updateOptions);
},
serviceCallback: function() {
var services = stlib_picker.getServices("myPicker");
var outputString = "";
for(i=0;i<services.length;i++) {
outputString += "\"" + _all_services[services[i]].title + ":"
outputString += services[i] + "\","
}
outputString = outputString.substring(0, outputString.length-1);
jQuery("#edit-sharethis-service-option").attr("value", outputString);
}
};
//After the page is loaded, we want to add events to dynamically created elements.
jQuery(document).ready(drupal_st.addEvents);
//After it's all done, hide the text field for the service picker so that no one messes up the data.
jQuery(document).ready(drupal_st.setupServiceText);
|
otavanopisto/pajav2
|
sites/default/modules/sharethis/ShareThisForm.js
|
JavaScript
|
gpl-2.0
| 3,308
|
/* linux/arch/arm/mach-s3c2440/mach-osiris.c
*
* Copyright (c) 2005,2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* 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/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/sysdev.h>
#include <linux/serial_core.h>
#include <linux/clk.h>
#include <linux/i2c.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/osiris-map.h>
#include <mach/osiris-cpld.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <mach/regs-mem.h>
#include <mach/regs-lcd.h>
#include <plat/nand.h>
#include <plat/iic.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
/* onboard perihperal map */
static struct map_desc osiris_iodesc[] __initdata = {
/* ISA IO areas (may be over-written later) */
{
.virtual = (u32)S3C24XX_VA_ISA_BYTE,
.pfn = __phys_to_pfn(S3C2410_CS5),
.length = SZ_16M,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_WORD,
.pfn = __phys_to_pfn(S3C2410_CS5),
.length = SZ_16M,
.type = MT_DEVICE,
},
/* CPLD control registers */
{
.virtual = (u32)OSIRIS_VA_CTRL0,
.pfn = __phys_to_pfn(OSIRIS_PA_CTRL0),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (u32)OSIRIS_VA_CTRL1,
.pfn = __phys_to_pfn(OSIRIS_PA_CTRL1),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (u32)OSIRIS_VA_CTRL2,
.pfn = __phys_to_pfn(OSIRIS_PA_CTRL2),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (u32)OSIRIS_VA_IDREG,
.pfn = __phys_to_pfn(OSIRIS_PA_IDREG),
.length = SZ_16K,
.type = MT_DEVICE,
},
};
#define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c24xx_uart_clksrc osiris_serial_clocks[] = {
[0] = {
.name = "uclk",
.divisor = 1,
.min_baud = 0,
.max_baud = 0,
},
[1] = {
.name = "pclk",
.divisor = 1,
.min_baud = 0,
.max_baud = 0,
}
};
static struct s3c2410_uartcfg osiris_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
.clocks = osiris_serial_clocks,
.clocks_size = ARRAY_SIZE(osiris_serial_clocks),
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
.clocks = osiris_serial_clocks,
.clocks_size = ARRAY_SIZE(osiris_serial_clocks),
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
.clocks = osiris_serial_clocks,
.clocks_size = ARRAY_SIZE(osiris_serial_clocks),
}
};
/* NAND Flash on Osiris board */
static int external_map[] = { 2 };
static int chip0_map[] = { 0 };
static int chip1_map[] = { 1 };
static struct mtd_partition osiris_default_nand_part[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_16K,
.offset = 0,
},
[1] = {
.name = "/boot",
.size = SZ_4M - SZ_16K,
.offset = SZ_16K,
},
[2] = {
.name = "user1",
.offset = SZ_4M,
.size = SZ_32M - SZ_4M,
},
[3] = {
.name = "user2",
.offset = SZ_32M,
.size = MTDPART_SIZ_FULL,
}
};
static struct mtd_partition osiris_default_nand_part_large[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_128K,
.offset = 0,
},
[1] = {
.name = "/boot",
.size = SZ_4M - SZ_128K,
.offset = SZ_128K,
},
[2] = {
.name = "user1",
.offset = SZ_4M,
.size = SZ_32M - SZ_4M,
},
[3] = {
.name = "user2",
.offset = SZ_32M,
.size = MTDPART_SIZ_FULL,
}
};
/* the Osiris has 3 selectable slots for nand-flash, the two
* on-board chip areas, as well as the external slot.
*
* Note, there is no current hot-plug support for the External
* socket.
*/
static struct s3c2410_nand_set osiris_nand_sets[] = {
[1] = {
.name = "External",
.nr_chips = 1,
.nr_map = external_map,
.nr_partitions = ARRAY_SIZE(osiris_default_nand_part),
.partitions = osiris_default_nand_part,
},
[0] = {
.name = "chip0",
.nr_chips = 1,
.nr_map = chip0_map,
.nr_partitions = ARRAY_SIZE(osiris_default_nand_part),
.partitions = osiris_default_nand_part,
},
[2] = {
.name = "chip1",
.nr_chips = 1,
.nr_map = chip1_map,
.nr_partitions = ARRAY_SIZE(osiris_default_nand_part),
.partitions = osiris_default_nand_part,
},
};
static void osiris_nand_select(struct s3c2410_nand_set *set, int slot)
{
unsigned int tmp;
slot = set->nr_map[slot] & 3;
pr_debug("osiris_nand: selecting slot %d (set %p,%p)\n",
slot, set, set->nr_map);
tmp = __raw_readb(OSIRIS_VA_CTRL0);
tmp &= ~OSIRIS_CTRL0_NANDSEL;
tmp |= slot;
pr_debug("osiris_nand: ctrl0 now %02x\n", tmp);
__raw_writeb(tmp, OSIRIS_VA_CTRL0);
}
static struct s3c2410_platform_nand osiris_nand_info = {
.tacls = 25,
.twrph0 = 60,
.twrph1 = 60,
.nr_sets = ARRAY_SIZE(osiris_nand_sets),
.sets = osiris_nand_sets,
.select_chip = osiris_nand_select,
};
/* PCMCIA control and configuration */
static struct resource osiris_pcmcia_resource[] = {
[0] = {
.start = 0x0f000000,
.end = 0x0f100000,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 0x0c000000,
.end = 0x0c100000,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device osiris_pcmcia = {
.name = "osiris-pcmcia",
.id = -1,
.num_resources = ARRAY_SIZE(osiris_pcmcia_resource),
.resource = osiris_pcmcia_resource,
};
/* Osiris power management device */
#ifdef CONFIG_PM
static unsigned char pm_osiris_ctrl0;
static int osiris_pm_suspend(struct sys_device *sd, pm_message_t state)
{
unsigned int tmp;
pm_osiris_ctrl0 = __raw_readb(OSIRIS_VA_CTRL0);
tmp = pm_osiris_ctrl0 & ~OSIRIS_CTRL0_NANDSEL;
/* ensure correct NAND slot is selected on resume */
if ((pm_osiris_ctrl0 & OSIRIS_CTRL0_BOOT_INT) == 0)
tmp |= 2;
__raw_writeb(tmp, OSIRIS_VA_CTRL0);
/* ensure that an nRESET is not generated on resume. */
s3c2410_gpio_setpin(S3C2410_GPA21, 1);
s3c2410_gpio_cfgpin(S3C2410_GPA21, S3C2410_GPA21_OUT);
return 0;
}
static int osiris_pm_resume(struct sys_device *sd)
{
if (pm_osiris_ctrl0 & OSIRIS_CTRL0_FIX8)
__raw_writeb(OSIRIS_CTRL1_FIX8, OSIRIS_VA_CTRL1);
__raw_writeb(pm_osiris_ctrl0, OSIRIS_VA_CTRL0);
s3c2410_gpio_cfgpin(S3C2410_GPA21, S3C2410_GPA21_nRSTOUT);
return 0;
}
#else
#define osiris_pm_suspend NULL
#define osiris_pm_resume NULL
#endif
static struct sysdev_class osiris_pm_sysclass = {
.name = "mach-osiris",
.suspend = osiris_pm_suspend,
.resume = osiris_pm_resume,
};
static struct sys_device osiris_pm_sysdev = {
.cls = &osiris_pm_sysclass,
};
/* I2C devices fitted. */
static struct i2c_board_info osiris_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("tps65011", 0x48),
.irq = IRQ_EINT20,
},
};
/* Standard Osiris devices */
static struct platform_device *osiris_devices[] __initdata = {
&s3c_device_i2c0,
&s3c_device_wdt,
&s3c_device_nand,
&osiris_pcmcia,
};
static struct clk *osiris_clocks[] __initdata = {
&s3c24xx_dclk0,
&s3c24xx_dclk1,
&s3c24xx_clkout0,
&s3c24xx_clkout1,
&s3c24xx_uclk,
};
static void __init osiris_map_io(void)
{
unsigned long flags;
/* initialise the clocks */
s3c24xx_dclk0.parent = &clk_upll;
s3c24xx_dclk0.rate = 12*1000*1000;
s3c24xx_dclk1.parent = &clk_upll;
s3c24xx_dclk1.rate = 24*1000*1000;
s3c24xx_clkout0.parent = &s3c24xx_dclk0;
s3c24xx_clkout1.parent = &s3c24xx_dclk1;
s3c24xx_uclk.parent = &s3c24xx_clkout1;
s3c24xx_register_clocks(osiris_clocks, ARRAY_SIZE(osiris_clocks));
s3c_device_nand.dev.platform_data = &osiris_nand_info;
s3c24xx_init_io(osiris_iodesc, ARRAY_SIZE(osiris_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(osiris_uartcfgs, ARRAY_SIZE(osiris_uartcfgs));
/* check for the newer revision boards with large page nand */
if ((__raw_readb(OSIRIS_VA_IDREG) & OSIRIS_ID_REVMASK) >= 4) {
printk(KERN_INFO "OSIRIS-B detected (revision %d)\n",
__raw_readb(OSIRIS_VA_IDREG) & OSIRIS_ID_REVMASK);
osiris_nand_sets[0].partitions = osiris_default_nand_part_large;
osiris_nand_sets[0].nr_partitions = ARRAY_SIZE(osiris_default_nand_part_large);
} else {
/* write-protect line to the NAND */
s3c2410_gpio_setpin(S3C2410_GPA0, 1);
}
/* fix bus configuration (nBE settings wrong on ABLE pre v2.20) */
local_irq_save(flags);
__raw_writel(__raw_readl(S3C2410_BWSCON) | S3C2410_BWSCON_ST1 | S3C2410_BWSCON_ST2 | S3C2410_BWSCON_ST3 | S3C2410_BWSCON_ST4 | S3C2410_BWSCON_ST5, S3C2410_BWSCON);
local_irq_restore(flags);
}
static void __init osiris_init(void)
{
sysdev_class_register(&osiris_pm_sysclass);
sysdev_register(&osiris_pm_sysdev);
s3c_i2c0_set_platdata(NULL);
i2c_register_board_info(0, osiris_i2c_devs,
ARRAY_SIZE(osiris_i2c_devs));
platform_add_devices(osiris_devices, ARRAY_SIZE(osiris_devices));
};
MACHINE_START(OSIRIS, "Simtec-OSIRIS")
/* Maintainer: Ben Dooks <ben@simtec.co.uk> */
.phys_io = S3C2410_PA_UART,
.io_pg_offst = (((u32)S3C24XX_VA_UART) >> 18) & 0xfffc,
.boot_params = S3C2410_SDRAM_PA + 0x100,
.map_io = osiris_map_io,
.init_machine = osiris_init,
.init_irq = s3c24xx_init_irq,
.init_machine = osiris_init,
.timer = &s3c24xx_timer,
MACHINE_END
|
felixhaedicke/nst-kernel
|
src/arch/arm/mach-s3c2440/mach-osiris.c
|
C
|
gpl-2.0
| 9,761
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_SHELL_APP_PATHS_MAC_H_
#define CONTENT_SHELL_APP_PATHS_MAC_H_
namespace base {
class FilePath;
}
// Sets up base::mac::FrameworkBundle.
void OverrideFrameworkBundlePath();
// Sets up the CHILD_PROCESS_EXE path to properly point to the helper app.
void OverrideChildProcessPath();
// Gets the path to the content shell's pak file.
base::FilePath GetResourcesPakFilePath();
// Gets the path to content shell's Info.plist file.
base::FilePath GetInfoPlistPath();
#endif // CONTENT_SHELL_APP_PATHS_MAC_H_
|
ssaroha/node-webrtc
|
third_party/webrtc/include/chromium/src/content/shell/app/paths_mac.h
|
C
|
bsd-2-clause
| 690
|
// PR c++/56998
class Secret;
char IsNullLiteralHelper(Secret* p);
char (&IsNullLiteralHelper(...))[2];
struct C
{
int val() { return 42; }
};
template <typename T>
unsigned f()
{
return sizeof(IsNullLiteralHelper(C().val()));
}
|
selmentdev/selment-toolchain
|
source/gcc-latest/gcc/testsuite/g++.dg/template/overload13.C
|
C++
|
gpl-3.0
| 236
|
#ifndef HEADER_CURL_LDAP_H
#define HEADER_CURL_LDAP_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifndef CURL_DISABLE_LDAP
extern const struct Curl_handler Curl_handler_ldap;
#if !defined(CURL_DISABLE_LDAPS) && \
((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
(!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
extern const struct Curl_handler Curl_handler_ldaps;
#endif
#endif
#endif /* HEADER_CURL_LDAP_H */
|
Noah-Huppert/Website-2013
|
vhosts/www.noahhuppert.com/htdocs/trex/deps/curl/lib/curl_ldap.h
|
C
|
mit
| 1,408
|
/*
* Copyright 1992, Linus Torvalds.
* Copyright 2010 Tilera Corporation. 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.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#ifndef _ASM_TILE_BITOPS_H
#define _ASM_TILE_BITOPS_H
#include <linux/types.h>
#ifndef _LINUX_BITOPS_H
#error only <linux/bitops.h> can be included directly
#endif
#ifdef __tilegx__
#include <asm/bitops_64.h>
#else
#include <asm/bitops_32.h>
#endif
/**
* __ffs - find first set bit in word
* @word: The word to search
*
* Undefined if no set bit exists, so code should check against 0 first.
*/
static inline unsigned long __ffs(unsigned long word)
{
return __builtin_ctzl(word);
}
/**
* ffz - find first zero bit in word
* @word: The word to search
*
* Undefined if no zero exists, so code should check against ~0UL first.
*/
static inline unsigned long ffz(unsigned long word)
{
return __builtin_ctzl(~word);
}
/**
* __fls - find last set bit in word
* @word: The word to search
*
* Undefined if no set bit exists, so code should check against 0 first.
*/
static inline unsigned long __fls(unsigned long word)
{
return (sizeof(word) * 8) - 1 - __builtin_clzl(word);
}
/**
* ffs - find first set bit in word
* @x: the word to search
*
* This is defined the same way as the libc and compiler builtin ffs
* routines, therefore differs in spirit from the other bitops.
*
* ffs(value) returns 0 if value is 0 or the position of the first
* set bit if value is nonzero. The first (least significant) bit
* is at position 1.
*/
static inline int ffs(int x)
{
return __builtin_ffs(x);
}
/**
* fls - find last set bit in word
* @x: the word to search
*
* This is defined in a similar way as the libc and compiler builtin
* ffs, but returns the position of the most significant set bit.
*
* fls(value) returns 0 if value is 0 or the position of the last
* set bit if value is nonzero. The last (most significant) bit is
* at position 32.
*/
static inline int fls(int x)
{
return (sizeof(int) * 8) - __builtin_clz(x);
}
static inline int fls64(__u64 w)
{
return (sizeof(__u64) * 8) - __builtin_clzll(w);
}
static inline unsigned int __arch_hweight32(unsigned int w)
{
return __builtin_popcount(w);
}
static inline unsigned int __arch_hweight16(unsigned int w)
{
return __builtin_popcount(w & 0xffff);
}
static inline unsigned int __arch_hweight8(unsigned int w)
{
return __builtin_popcount(w & 0xff);
}
static inline unsigned long __arch_hweight64(__u64 w)
{
return __builtin_popcountll(w);
}
#include <asm-generic/bitops/const_hweight.h>
#include <asm-generic/bitops/lock.h>
#include <asm-generic/bitops/find.h>
#include <asm-generic/bitops/sched.h>
#include <asm-generic/bitops/le.h>
#endif /* _ASM_TILE_BITOPS_H */
|
chaoling/test123
|
linux-2.6.39/arch/tile/include/asm/bitops.h
|
C
|
gpl-2.0
| 3,162
|
/* SPDX-License-Identifier: GPL-2.0 */
/* $Id: entity.h,v 1.4 2004/03/21 17:26:01 armin Exp $ */
#ifndef __DIVAS_USER_MODE_IDI_ENTITY__
#define __DIVAS_USER_MODE_IDI_ENTITY__
#define DIVA_UM_IDI_RC_PENDING 0x00000001
#define DIVA_UM_IDI_REMOVE_PENDING 0x00000002
#define DIVA_UM_IDI_TX_FLOW_CONTROL 0x00000004
#define DIVA_UM_IDI_REMOVED 0x00000008
#define DIVA_UM_IDI_ASSIGN_PENDING 0x00000010
typedef struct _divas_um_idi_entity {
struct list_head link;
diva_um_idi_adapter_t *adapter; /* Back to adapter */
ENTITY e;
void *os_ref;
dword status;
void *os_context;
int rc_count;
diva_um_idi_data_queue_t data; /* definad by user 1 ... MAX */
diva_um_idi_data_queue_t rc; /* two entries */
BUFFERS XData;
BUFFERS RData;
byte buffer[2048 + 512];
} divas_um_idi_entity_t;
#endif
|
BPI-SINOVOIP/BPI-Mainline-kernel
|
linux-4.19/drivers/isdn/hardware/eicon/entity.h
|
C
|
gpl-2.0
| 879
|
/*
* 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) 2013 by John Crispin <john@phrozen.org>
*/
#include <linux/clockchips.h>
#include <linux/clocksource.h>
#include <linux/interrupt.h>
#include <linux/reset.h>
#include <linux/init.h>
#include <linux/time.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include <asm/mach-ralink/ralink_regs.h>
#define SYSTICK_FREQ (50 * 1000)
#define SYSTICK_CONFIG 0x00
#define SYSTICK_COMPARE 0x04
#define SYSTICK_COUNT 0x08
/* route systick irq to mips irq 7 instead of the r4k-timer */
#define CFG_EXT_STK_EN 0x2
/* enable the counter */
#define CFG_CNT_EN 0x1
struct systick_device {
void __iomem *membase;
struct clock_event_device dev;
int irq_requested;
int freq_scale;
};
static int systick_set_oneshot(struct clock_event_device *evt);
static int systick_shutdown(struct clock_event_device *evt);
static int systick_next_event(unsigned long delta,
struct clock_event_device *evt)
{
struct systick_device *sdev;
u32 count;
sdev = container_of(evt, struct systick_device, dev);
count = ioread32(sdev->membase + SYSTICK_COUNT);
count = (count + delta) % SYSTICK_FREQ;
iowrite32(count, sdev->membase + SYSTICK_COMPARE);
return 0;
}
static void systick_event_handler(struct clock_event_device *dev)
{
/* noting to do here */
}
static irqreturn_t systick_interrupt(int irq, void *dev_id)
{
struct clock_event_device *dev = (struct clock_event_device *) dev_id;
dev->event_handler(dev);
return IRQ_HANDLED;
}
static struct systick_device systick = {
.dev = {
/*
* cevt-r4k uses 300, make sure systick
* gets used if available
*/
.rating = 310,
.features = CLOCK_EVT_FEAT_ONESHOT,
.set_next_event = systick_next_event,
.set_state_shutdown = systick_shutdown,
.set_state_oneshot = systick_set_oneshot,
.event_handler = systick_event_handler,
},
};
static struct irqaction systick_irqaction = {
.handler = systick_interrupt,
.flags = IRQF_PERCPU | IRQF_TIMER,
.dev_id = &systick.dev,
};
static int systick_shutdown(struct clock_event_device *evt)
{
struct systick_device *sdev;
sdev = container_of(evt, struct systick_device, dev);
if (sdev->irq_requested)
free_irq(systick.dev.irq, &systick_irqaction);
sdev->irq_requested = 0;
iowrite32(0, systick.membase + SYSTICK_CONFIG);
return 0;
}
static int systick_set_oneshot(struct clock_event_device *evt)
{
struct systick_device *sdev;
sdev = container_of(evt, struct systick_device, dev);
if (!sdev->irq_requested)
setup_irq(systick.dev.irq, &systick_irqaction);
sdev->irq_requested = 1;
iowrite32(CFG_EXT_STK_EN | CFG_CNT_EN,
systick.membase + SYSTICK_CONFIG);
return 0;
}
static int __init ralink_systick_init(struct device_node *np)
{
int ret;
systick.membase = of_iomap(np, 0);
if (!systick.membase)
return -ENXIO;
systick_irqaction.name = np->name;
systick.dev.name = np->name;
clockevents_calc_mult_shift(&systick.dev, SYSTICK_FREQ, 60);
systick.dev.max_delta_ns = clockevent_delta2ns(0x7fff, &systick.dev);
systick.dev.max_delta_ticks = 0x7fff;
systick.dev.min_delta_ns = clockevent_delta2ns(0x3, &systick.dev);
systick.dev.min_delta_ticks = 0x3;
systick.dev.irq = irq_of_parse_and_map(np, 0);
if (!systick.dev.irq) {
pr_err("%pOFn: request_irq failed", np);
return -EINVAL;
}
ret = clocksource_mmio_init(systick.membase + SYSTICK_COUNT, np->name,
SYSTICK_FREQ, 301, 16,
clocksource_mmio_readl_up);
if (ret)
return ret;
clockevents_register_device(&systick.dev);
pr_info("%pOFn: running - mult: %d, shift: %d\n",
np, systick.dev.mult, systick.dev.shift);
return 0;
}
TIMER_OF_DECLARE(systick, "ralink,cevt-systick", ralink_systick_init);
|
BPI-SINOVOIP/BPI-Mainline-kernel
|
linux-5.4/arch/mips/ralink/cevt-rt3352.c
|
C
|
gpl-2.0
| 3,859
|
/*
* 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.
*/
#ifndef _ASM_GENERIC_PCI_BRIDGE_H
#define _ASM_GENERIC_PCI_BRIDGE_H
#ifdef __KERNEL__
enum {
/* Force re-assigning all resources (ignore firmware
* setup completely)
*/
PCI_REASSIGN_ALL_RSRC = 0x00000001,
/* Re-assign all bus numbers */
PCI_REASSIGN_ALL_BUS = 0x00000002,
/* Do not try to assign, just use existing setup */
PCI_PROBE_ONLY = 0x00000004,
/* Don't bother with ISA alignment unless the bridge has
* ISA forwarding enabled
*/
PCI_CAN_SKIP_ISA_ALIGN = 0x00000008,
/* Enable domain numbers in /proc */
PCI_ENABLE_PROC_DOMAINS = 0x00000010,
/* ... except for domain 0 */
PCI_COMPAT_DOMAIN_0 = 0x00000020,
};
#ifdef CONFIG_PCI
extern unsigned int pci_flags;
static inline void pci_set_flags(int flags)
{
pci_flags = flags;
}
static inline void pci_add_flags(int flags)
{
pci_flags |= flags;
}
static inline int pci_has_flag(int flag)
{
return pci_flags & flag;
}
#else
static inline void pci_set_flags(int flags) { }
static inline void pci_add_flags(int flags) { }
static inline int pci_has_flag(int flag)
{
return 0;
}
#endif /* CONFIG_PCI */
#endif /* __KERNEL__ */
#endif /* _ASM_GENERIC_PCI_BRIDGE_H */
|
WhiteBearSolutions/WBSAirback
|
packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/include/asm-generic/pci-bridge.h
|
C
|
apache-2.0
| 1,410
|
<?php
/**
* Autorunner which runs all tests cases found in a file
* that includes this module.
* @package SimpleTest
* @version $Id: autorun.php 1721 2008-04-07 19:27:10Z lastcraft $
*/
require_once dirname(__FILE__) . '/unit_tester.php';
require_once dirname(__FILE__) . '/mock_objects.php';
require_once dirname(__FILE__) . '/collector.php';
require_once dirname(__FILE__) . '/default_reporter.php';
$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
register_shutdown_function('simpletest_autorun');
/**
* Exit handler to run all recent test cases if no test has
* so far been run. Uses the DefaultReporter which can have
* it's output controlled with SimpleTest::prefer().
*/
function simpletest_autorun() {
if (tests_have_run()) {
return;
}
$candidates = array_intersect(
capture_new_classes(),
classes_defined_in_initial_file());
$loader = new SimpleFileLoader();
$suite = $loader->createSuiteFromClasses(
basename(initial_file()),
$loader->selectRunnableTests($candidates));
$result = $suite->run(new DefaultReporter());
if (SimpleReporter::inCli()) {
exit($result ? 0 : 1);
}
}
/**
* Checks the current test context to see if a test has
* ever been run.
* @return boolean True if tests have run.
*/
function tests_have_run() {
if ($context = SimpleTest::getContext()) {
return (boolean)$context->getTest();
}
return false;
}
/**
* The first autorun file.
* @return string Filename of first autorun script.
*/
function initial_file() {
static $file = false;
if (! $file) {
$file = reset(get_included_files());
}
return $file;
}
/**
* Just the classes from the first autorun script. May
* get a few false positives, as it just does a regex based
* on following the word "class".
* @return array List of all possible classes in first
* autorun script.
*/
function classes_defined_in_initial_file() {
if (preg_match_all('/\bclass\s+(\w+)/i', file_get_contents(initial_file()), $matches)) {
return array_map('strtolower', $matches[1]);
}
return array();
}
/**
* Every class since the first autorun include. This
* is safe enough if require_once() is alwyas used.
* @return array Class names.
*/
function capture_new_classes() {
global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES;
return array_map('strtolower', array_diff(get_declared_classes(),
$SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ?
$SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array()));
}
?>
|
timjaeger/launcheffect
|
wp-content/themes/launcheffect/inc/campaignmonitor/tests/simpletest/autorun.php
|
PHP
|
gpl-2.0
| 2,729
|
<?php
/*
Requires PHP5, uses built-in DOM extension.
To be used in PHP4 scripts using DOMXML extension: allows PHP4/DOMXML scripts to run on PHP5/DOM.
(Optional: requires PHP5/XSL extension for domxml_xslt functions, PHP>=5.1 for XPath evaluation functions, and PHP>=5.1/libxml for DOMXML error reports)
Typical use:
{
if (PHP_VERSION>='5')
require_once('domxml-php4-to-php5.php');
}
Version 1.21.1a, 2009-03-13, http://alexandre.alapetite.fr/doc-alex/domxml-php4-php5/
------------------------------------------------------------------
Written by Alexandre Alapetite, http://alexandre.alapetite.fr/cv/
Copyright 2004-2009, GNU Lesser General Public License,
http://www.gnu.org/licenses/lgpl.html
This program 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 3 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/lgpl.html>
== Rights and obligations ==
- Attribution: You must give the original author credit.
- Share Alike: If you alter or transform this library,
you may distribute the resulting library only under the same license GNU/LGPL.
- In case of jurisdiction dispute, the French law is authoritative.
- Any of these conditions can be waived if you get permission from Alexandre Alapetite.
- Not required, but please send to Alexandre Alapetite the modifications you make,
in order to improve this file for the benefit of everybody.
If you want to distribute this code, please do it as a link to:
http://alexandre.alapetite.fr/doc-alex/domxml-php4-php5/
*/
define('DOMXML_LOAD_PARSING',0);
define('DOMXML_LOAD_VALIDATING',1);
define('DOMXML_LOAD_RECOVERING',2);
define('DOMXML_LOAD_SUBSTITUTE_ENTITIES',4);
//define('DOMXML_LOAD_COMPLETE_ATTRS',8);
define('DOMXML_LOAD_DONT_KEEP_BLANKS',16);
function domxml_new_doc($version) {return new php4DOMDocument();}
function domxml_new_xmldoc($version) {return new php4DOMDocument();}
function domxml_open_file($filename,$mode=DOMXML_LOAD_PARSING,&$error=null)
{
$dom=new php4DOMDocument($mode);
$errorMode=(func_num_args()>2)&&defined('LIBXML_VERSION');
if ($errorMode) libxml_use_internal_errors(true);
if (!$dom->myDOMNode->load($filename)) $dom=null;
if ($errorMode)
{
$error=array_map('_error_report',libxml_get_errors());
libxml_clear_errors();
}
return $dom;
}
function domxml_open_mem($str,$mode=DOMXML_LOAD_PARSING,&$error=null)
{
$dom=new php4DOMDocument($mode);
$errorMode=(func_num_args()>2)&&defined('LIBXML_VERSION');
if ($errorMode) libxml_use_internal_errors(true);
if (!$dom->myDOMNode->loadXML($str)) $dom=null;
if ($errorMode)
{
$error=array_map('_error_report',libxml_get_errors());
libxml_clear_errors();
}
return $dom;
}
function html_doc($html_doc,$from_file=false)
{
$dom=new php4DOMDocument();
if ($from_file) $result=$dom->myDOMNode->loadHTMLFile($html_doc);
else $result=$dom->myDOMNode->loadHTML($html_doc);
return $result ? $dom : null;
}
function html_doc_file($filename) {return html_doc($filename,true);}
function xmldoc($str) {return domxml_open_mem($str);}
function xmldocfile($filename) {return domxml_open_file($filename);}
function xpath_eval($xpath_context,$eval_str,$contextnode=null) {return $xpath_context->xpath_eval($eval_str,$contextnode);}
function xpath_new_context($dom_document) {return new php4DOMXPath($dom_document);}
function xpath_register_ns($xpath_context,$prefix,$namespaceURI) {return $xpath_context->myDOMXPath->registerNamespace($prefix,$namespaceURI);}
function _entityDecode($text) {return html_entity_decode(strtr($text,array('''=>'\'')),ENT_QUOTES,'UTF-8');}
function _error_report($error) {return array('errormessage'=>$error->message,'nodename'=>'','line'=>$error->line,'col'=>$error->column)+($error->file==''?array():array('directory'=>dirname($error->file),'file'=>basename($error->file)));}
class php4DOMAttr extends php4DOMNode
{
function __get($name)
{
if ($name==='name') return $this->myDOMNode->name;
else return parent::__get($name);
}
function name() {return $this->myDOMNode->name;}
function set_content($text) {}
//function set_value($content) {return $this->myDOMNode->value=htmlspecialchars($content,ENT_QUOTES);}
function specified() {return $this->myDOMNode->specified;}
function value() {return $this->myDOMNode->value;}
}
class php4DOMDocument extends php4DOMNode
{
function php4DOMDocument($mode=DOMXML_LOAD_PARSING)
{
$this->myDOMNode=new DOMDocument();
$this->myOwnerDocument=$this;
if ($mode & DOMXML_LOAD_VALIDATING) $this->myDOMNode->validateOnParse=true;
if ($mode & DOMXML_LOAD_RECOVERING) $this->myDOMNode->recover=true;
if ($mode & DOMXML_LOAD_SUBSTITUTE_ENTITIES) $this->myDOMNode->substituteEntities=true;
if ($mode & DOMXML_LOAD_DONT_KEEP_BLANKS) $this->myDOMNode->preserveWhiteSpace=false;
}
function add_root($name)
{
if ($this->myDOMNode->hasChildNodes()) $this->myDOMNode->removeChild($this->myDOMNode->firstChild);
return new php4DOMElement($this->myDOMNode->appendChild($this->myDOMNode->createElement($name)),$this->myOwnerDocument);
}
function create_attribute($name,$value)
{
$myAttr=$this->myDOMNode->createAttribute($name);
$myAttr->value=htmlspecialchars($value,ENT_QUOTES);
return new php4DOMAttr($myAttr,$this);
}
function create_cdata_section($content) {return new php4DOMNode($this->myDOMNode->createCDATASection($content),$this);}
function create_comment($data) {return new php4DOMNode($this->myDOMNode->createComment($data),$this);}
function create_element($name) {return new php4DOMElement($this->myDOMNode->createElement($name),$this);}
function create_element_ns($uri,$name,$prefix=null)
{
if ($prefix==null) $prefix=$this->myDOMNode->lookupPrefix($uri);
if (($prefix==null)&&(($this->myDOMNode->documentElement==null)||(!$this->myDOMNode->documentElement->isDefaultNamespace($uri)))) $prefix='a'.sprintf('%u',crc32($uri));
return new php4DOMElement($this->myDOMNode->createElementNS($uri,$prefix==null ? $name : $prefix.':'.$name),$this);
}
function create_entity_reference($content) {return new php4DOMNode($this->myDOMNode->createEntityReference($content),$this);} //By Walter Ebert 2007-01-22
function create_processing_instruction($target,$data=''){return new php4DomProcessingInstruction($this->myDOMNode->createProcessingInstruction($target,$data),$this);}
function create_text_node($content) {return new php4DOMText($this->myDOMNode->createTextNode($content),$this);}
function document_element() {return parent::_newDOMElement($this->myDOMNode->documentElement,$this);}
function dump_file($filename,$compressionmode=false,$format=false)
{
$format0=$this->myDOMNode->formatOutput;
$this->myDOMNode->formatOutput=$format;
$res=$this->myDOMNode->save($filename);
$this->myDOMNode->formatOutput=$format0;
return $res;
}
function dump_mem($format=false,$encoding=false)
{
$format0=$this->myDOMNode->formatOutput;
$this->myDOMNode->formatOutput=$format;
$encoding0=$this->myDOMNode->encoding;
if ($encoding) $this->myDOMNode->encoding=$encoding;
$dump=$this->myDOMNode->saveXML();
$this->myDOMNode->formatOutput=$format0;
if ($encoding) $this->myDOMNode->encoding= $encoding0=='' ? 'UTF-8' : $encoding0; //UTF-8 is XML default encoding
return $dump;
}
function free()
{
if ($this->myDOMNode->hasChildNodes()) $this->myDOMNode->removeChild($this->myDOMNode->firstChild);
$this->myDOMNode=null;
$this->myOwnerDocument=null;
}
function get_element_by_id($id) {return parent::_newDOMElement($this->myDOMNode->getElementById($id),$this);}
function get_elements_by_tagname($name)
{
$myDOMNodeList=$this->myDOMNode->getElementsByTagName($name);
$nodeSet=array();
$i=0;
if (isset($myDOMNodeList))
while ($node=$myDOMNodeList->item($i++)) $nodeSet[]=new php4DOMElement($node,$this);
return $nodeSet;
}
function html_dump_mem() {return $this->myDOMNode->saveHTML();}
function root() {return parent::_newDOMElement($this->myDOMNode->documentElement,$this);}
function xinclude() {return $this->myDOMNode->xinclude();}
function xpath_new_context() {return new php4DOMXPath($this);}
}
class php4DOMElement extends php4DOMNode
{
function add_namespace($uri,$prefix)
{
if ($this->myDOMNode->hasAttributeNS('http://www.w3.org/2000/xmlns/',$prefix)) return false;
else
{
$this->myDOMNode->setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:'.$prefix,$uri); //By Daniel Walker 2006-09-08
return true;
}
}
function get_attribute($name) {return $this->myDOMNode->getAttribute($name);}
function get_attribute_node($name) {return parent::_newDOMElement($this->myDOMNode->getAttributeNode($name),$this->myOwnerDocument);}
function get_elements_by_tagname($name)
{
$myDOMNodeList=$this->myDOMNode->getElementsByTagName($name);
$nodeSet=array();
$i=0;
if (isset($myDOMNodeList))
while ($node=$myDOMNodeList->item($i++)) $nodeSet[]=new php4DOMElement($node,$this->myOwnerDocument);
return $nodeSet;
}
function has_attribute($name) {return $this->myDOMNode->hasAttribute($name);}
function remove_attribute($name) {return $this->myDOMNode->removeAttribute($name);}
function set_attribute($name,$value)
{
//return $this->myDOMNode->setAttribute($name,$value); //Does not return a DomAttr
$myAttr=$this->myDOMNode->ownerDocument->createAttribute($name);
$myAttr->value=htmlspecialchars($value,ENT_QUOTES); //Entity problem reported by AL-DesignWorks 2007-09-07
$this->myDOMNode->setAttributeNode($myAttr);
return new php4DOMAttr($myAttr,$this->myOwnerDocument);
}
/*function set_attribute_node($attr)
{
$this->myDOMNode->setAttributeNode($this->_importNode($attr));
return $attr;
}*/
function set_name($name)
{
if ($this->myDOMNode->prefix=='') $newNode=$this->myDOMNode->ownerDocument->createElement($name);
else $newNode=$this->myDOMNode->ownerDocument->createElementNS($this->myDOMNode->namespaceURI,$this->myDOMNode->prefix.':'.$name);
$myDOMNodeList=$this->myDOMNode->attributes;
$i=0;
if (isset($myDOMNodeList))
while ($node=$myDOMNodeList->item($i++))
if ($node->namespaceURI=='') $newNode->setAttribute($node->name,$node->value);
else $newNode->setAttributeNS($node->namespaceURI,$node->nodeName,$node->value);
$myDOMNodeList=$this->myDOMNode->childNodes;
if (isset($myDOMNodeList))
while ($node=$myDOMNodeList->item(0)) $newNode->appendChild($node);
$this->myDOMNode->parentNode->replaceChild($newNode,$this->myDOMNode);
$this->myDOMNode=$newNode;
return true;
}
function tagname() {return $this->tagname;}
}
class php4DOMNode
{
public $myDOMNode;
public $myOwnerDocument;
function php4DOMNode($aDomNode,$aOwnerDocument)
{
$this->myDOMNode=$aDomNode;
$this->myOwnerDocument=$aOwnerDocument;
}
function __get($name)
{
switch ($name)
{
case 'type': return $this->myDOMNode->nodeType;
case 'tagname': return ($this->myDOMNode->nodeType===XML_ELEMENT_NODE) ? $this->myDOMNode->localName : $this->myDOMNode->tagName; //Avoid namespace prefix for DOMElement
case 'content': return $this->myDOMNode->textContent;
case 'value': return $this->myDOMNode->value;
default:
$myErrors=debug_backtrace();
trigger_error('Undefined property: '.get_class($this).'::$'.$name.' ['.$myErrors[0]['file'].':'.$myErrors[0]['line'].']',E_USER_NOTICE);
return false;
}
}
function add_child($newnode) {return $this->append_child($newnode);}
function add_namespace($uri,$prefix) {return false;}
function append_child($newnode) {return self::_newDOMElement($this->myDOMNode->appendChild($this->_importNode($newnode)),$this->myOwnerDocument);}
function append_sibling($newnode) {return self::_newDOMElement($this->myDOMNode->parentNode->appendChild($this->_importNode($newnode)),$this->myOwnerDocument);}
function attributes()
{
$myDOMNodeList=$this->myDOMNode->attributes;
if (!(isset($myDOMNodeList)&&$this->myDOMNode->hasAttributes())) return null;
$nodeSet=array();
$i=0;
while ($node=$myDOMNodeList->item($i++)) $nodeSet[]=new php4DOMAttr($node,$this->myOwnerDocument);
return $nodeSet;
}
function child_nodes()
{
$myDOMNodeList=$this->myDOMNode->childNodes;
$nodeSet=array();
$i=0;
if (isset($myDOMNodeList))
while ($node=$myDOMNodeList->item($i++)) $nodeSet[]=self::_newDOMElement($node,$this->myOwnerDocument);
return $nodeSet;
}
function children() {return $this->child_nodes();}
function clone_node($deep=false) {return self::_newDOMElement($this->myDOMNode->cloneNode($deep),$this->myOwnerDocument);}
//dump_node($node) should only be called on php4DOMDocument
function dump_node($node=null) {return $node==null ? $this->myOwnerDocument->myDOMNode->saveXML($this->myDOMNode) : $this->myOwnerDocument->myDOMNode->saveXML($node->myDOMNode);}
function first_child() {return self::_newDOMElement($this->myDOMNode->firstChild,$this->myOwnerDocument);}
function get_content() {return $this->myDOMNode->textContent;}
function has_attributes() {return $this->myDOMNode->hasAttributes();}
function has_child_nodes() {return $this->myDOMNode->hasChildNodes();}
function insert_before($newnode,$refnode) {return self::_newDOMElement($this->myDOMNode->insertBefore($this->_importNode($newnode),$refnode==null?null:$refnode->myDOMNode),$this->myOwnerDocument);}
function is_blank_node() {return ($this->myDOMNode->nodeType===XML_TEXT_NODE)&&preg_match('%^\s*$%',$this->myDOMNode->nodeValue);}
function last_child() {return self::_newDOMElement($this->myDOMNode->lastChild,$this->myOwnerDocument);}
function new_child($name,$content)
{
$mySubNode=$this->myDOMNode->ownerDocument->createElement($name);
$mySubNode->appendChild($this->myDOMNode->ownerDocument->createTextNode(_entityDecode($content)));
$this->myDOMNode->appendChild($mySubNode);
return new php4DOMElement($mySubNode,$this->myOwnerDocument);
}
function next_sibling() {return self::_newDOMElement($this->myDOMNode->nextSibling,$this->myOwnerDocument);}
function node_name() {return ($this->myDOMNode->nodeType===XML_ELEMENT_NODE) ? $this->myDOMNode->localName : $this->myDOMNode->nodeName;} //Avoid namespace prefix for DOMElement
function node_type() {return $this->myDOMNode->nodeType;}
function node_value() {return $this->myDOMNode->nodeValue;}
function owner_document() {return $this->myOwnerDocument;}
function parent_node() {return self::_newDOMElement($this->myDOMNode->parentNode,$this->myOwnerDocument);}
function prefix() {return $this->myDOMNode->prefix;}
function previous_sibling() {return self::_newDOMElement($this->myDOMNode->previousSibling,$this->myOwnerDocument);}
function remove_child($oldchild) {return self::_newDOMElement($this->myDOMNode->removeChild($oldchild->myDOMNode),$this->myOwnerDocument);}
function replace_child($newnode,$oldnode) {return self::_newDOMElement($this->myDOMNode->replaceChild($this->_importNode($newnode),$oldnode->myDOMNode),$this->myOwnerDocument);}
function replace_node($newnode) {return self::_newDOMElement($this->myDOMNode->parentNode->replaceChild($this->_importNode($newnode),$this->myDOMNode),$this->myOwnerDocument);}
function set_content($text) {return $this->myDOMNode->appendChild($this->myDOMNode->ownerDocument->createTextNode(_entityDecode($text)));} //Entity problem reported by AL-DesignWorks 2007-09-07
//function set_name($name) {return $this->myOwnerDocument->renameNode($this->myDOMNode,$this->myDOMNode->namespaceURI,$name);}
function set_namespace($uri,$prefix=null)
{//Contributions by Daniel Walker 2006-09-08
$nsprefix=$this->myDOMNode->lookupPrefix($uri);
if ($nsprefix==null)
{
$nsprefix= $prefix==null ? $nsprefix='a'.sprintf('%u',crc32($uri)) : $prefix;
if ($this->myDOMNode->nodeType===XML_ATTRIBUTE_NODE)
{
if (($prefix!=null)&&$this->myDOMNode->ownerElement->hasAttributeNS('http://www.w3.org/2000/xmlns/',$nsprefix)&&
($this->myDOMNode->ownerElement->getAttributeNS('http://www.w3.org/2000/xmlns/',$nsprefix)!=$uri))
{//Remove namespace
$parent=$this->myDOMNode->ownerElement;
$parent->removeAttributeNode($this->myDOMNode);
$parent->setAttribute($this->myDOMNode->localName,$this->myDOMNode->nodeValue);
$this->myDOMNode=$parent->getAttributeNode($this->myDOMNode->localName);
return;
}
$this->myDOMNode->ownerElement->setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:'.$nsprefix,$uri);
}
}
if ($this->myDOMNode->nodeType===XML_ATTRIBUTE_NODE)
{
$parent=$this->myDOMNode->ownerElement;
$parent->removeAttributeNode($this->myDOMNode);
$parent->setAttributeNS($uri,$nsprefix.':'.$this->myDOMNode->localName,$this->myDOMNode->nodeValue);
$this->myDOMNode=$parent->getAttributeNodeNS($uri,$this->myDOMNode->localName);
}
elseif ($this->myDOMNode->nodeType===XML_ELEMENT_NODE)
{
$NewNode=$this->myDOMNode->ownerDocument->createElementNS($uri,$nsprefix.':'.$this->myDOMNode->localName);
foreach ($this->myDOMNode->attributes as $n) $NewNode->appendChild($n->cloneNode(true));
foreach ($this->myDOMNode->childNodes as $n) $NewNode->appendChild($n->cloneNode(true));
$xpath=new DOMXPath($this->myDOMNode->ownerDocument);
$myDOMNodeList=$xpath->query('namespace::*[name()!="xml"]',$this->myDOMNode); //Add old namespaces
foreach ($myDOMNodeList as $n) $NewNode->setAttributeNS('http://www.w3.org/2000/xmlns/',$n->nodeName,$n->nodeValue);
$this->myDOMNode->parentNode->replaceChild($NewNode,$this->myDOMNode);
$this->myDOMNode=$NewNode;
}
}
function unlink_node()
{
if ($this->myDOMNode->parentNode!=null)
{
if ($this->myDOMNode->nodeType===XML_ATTRIBUTE_NODE) $this->myDOMNode->parentNode->removeAttributeNode($this->myDOMNode);
else $this->myDOMNode->parentNode->removeChild($this->myDOMNode);
}
}
protected function _importNode($newnode) {return $this->myOwnerDocument===$newnode->myOwnerDocument ? $newnode->myDOMNode : $this->myOwnerDocument->myDOMNode->importNode($newnode->myDOMNode,true);} //To import DOMNode from another DOMDocument
static function _newDOMElement($aDOMNode,$aOwnerDocument)
{//Check the PHP5 DOMNode before creating a new associated PHP4 DOMNode wrapper
if ($aDOMNode==null) return null;
switch ($aDOMNode->nodeType)
{
case XML_ELEMENT_NODE: return new php4DOMElement($aDOMNode,$aOwnerDocument);
case XML_TEXT_NODE: return new php4DOMText($aDOMNode,$aOwnerDocument);
case XML_ATTRIBUTE_NODE: return new php4DOMAttr($aDOMNode,$aOwnerDocument);
case XML_PI_NODE: return new php4DomProcessingInstruction($aDOMNode,$aOwnerDocument);
default: return new php4DOMNode($aDOMNode,$aOwnerDocument);
}
}
}
class php4DomProcessingInstruction extends php4DOMNode
{
function data() {return $this->myDOMNode->data;}
function target() {return $this->myDOMNode->target;}
}
class php4DOMText extends php4DOMNode
{
function __get($name)
{
if ($name==='tagname') return '#text';
else return parent::__get($name);
}
function tagname() {return '#text';}
function set_content($text) {$this->myDOMNode->nodeValue=$text; return true;}
}
if (!defined('XPATH_NODESET'))
{
define('XPATH_UNDEFINED',0);
define('XPATH_NODESET',1);
define('XPATH_BOOLEAN',2);
define('XPATH_NUMBER',3);
define('XPATH_STRING',4);
/*define('XPATH_POINT',5);
define('XPATH_RANGE',6);
define('XPATH_LOCATIONSET',7);
define('XPATH_USERS',8);
define('XPATH_XSLT_TREE',9);*/
}
class php4DOMNodelist
{
private $myDOMNodelist;
public $nodeset;
public $type=XPATH_UNDEFINED;
public $value;
function php4DOMNodelist($aDOMNodelist,$aOwnerDocument)
{
if (!isset($aDOMNodelist)) return;
elseif (is_object($aDOMNodelist)||is_array($aDOMNodelist))
{
if ($aDOMNodelist->length>0)
{
$this->myDOMNodelist=$aDOMNodelist;
$this->nodeset=array();
$this->type=XPATH_NODESET;
$i=0;
while ($node=$this->myDOMNodelist->item($i++)) $this->nodeset[]=php4DOMNode::_newDOMElement($node,$aOwnerDocument);
}
}
elseif (is_int($aDOMNodelist)||is_float($aDOMNodelist))
{
$this->type=XPATH_NUMBER;
$this->value=$aDOMNodelist;
}
elseif (is_bool($aDOMNodelist))
{
$this->type=XPATH_BOOLEAN;
$this->value=$aDOMNodelist;
}
elseif (is_string($aDOMNodelist))
{
$this->type=XPATH_STRING;
$this->value=$aDOMNodelist;
}
}
}
class php4DOMXPath
{
public $myDOMXPath;
private $myOwnerDocument;
function php4DOMXPath($dom_document)
{
//TODO: If $dom_document is a DomElement, make that default $contextnode and modify XPath. Ex: '/test'
$this->myOwnerDocument=$dom_document->myOwnerDocument;
$this->myDOMXPath=new DOMXPath($this->myOwnerDocument->myDOMNode);
}
function xpath_eval($eval_str,$contextnode=null)
{
if (method_exists($this->myDOMXPath,'evaluate')) $xp=isset($contextnode->myDOMNode) ? $this->myDOMXPath->evaluate($eval_str,$contextnode->myDOMNode) : $this->myDOMXPath->evaluate($eval_str);
else $xp=isset($contextnode->myDOMNode) ? $this->myDOMXPath->query($eval_str,$contextnode->myDOMNode) : $this->myDOMXPath->query($eval_str);
$xp=new php4DOMNodelist($xp,$this->myOwnerDocument);
return ($xp->type===XPATH_UNDEFINED) ? false : $xp;
}
function xpath_register_ns($prefix,$namespaceURI) {return $this->myDOMXPath->registerNamespace($prefix,$namespaceURI);}
}
if (extension_loaded('xsl'))
{//See also: http://alexandre.alapetite.fr/doc-alex/xslt-php4-php5/
function domxml_xslt_stylesheet($xslstring) {return new php4DomXsltStylesheet(DOMDocument::loadXML($xslstring));}
function domxml_xslt_stylesheet_doc($dom_document) {return new php4DomXsltStylesheet($dom_document);}
function domxml_xslt_stylesheet_file($xslfile) {return new php4DomXsltStylesheet(DOMDocument::load($xslfile));}
class php4DomXsltStylesheet
{
private $myxsltProcessor;
function php4DomXsltStylesheet($dom_document)
{
$this->myxsltProcessor=new xsltProcessor();
$this->myxsltProcessor->importStyleSheet($dom_document);
}
function process($dom_document,$xslt_parameters=array(),$param_is_xpath=false)
{
foreach ($xslt_parameters as $param=>$value) $this->myxsltProcessor->setParameter('',$param,$value);
$myphp4DOMDocument=new php4DOMDocument();
$myphp4DOMDocument->myDOMNode=$this->myxsltProcessor->transformToDoc($dom_document->myDOMNode);
return $myphp4DOMDocument;
}
function result_dump_file($dom_document,$filename)
{
$html=$dom_document->myDOMNode->saveHTML();
file_put_contents($filename,$html);
return $html;
}
function result_dump_mem($dom_document) {return $dom_document->myDOMNode->saveHTML();}
}
}
?>
|
dhamma-dev/SEA
|
web/auth/cas/CAS/CAS/domxml-php4-to-php5.php
|
PHP
|
gpl-3.0
| 22,868
|
CodeMirror.defineMode("clike", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords || {},
blockKeywords = parserConfig.blockKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "word";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return 0;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}"
};
});
(function() {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
"double static else struct entry switch extern typedef float union for unsigned " +
"goto while enum void const signed volatile";
function cppHook(stream, state) {
if (!state.startOfLine) return false;
stream.skipToEnd();
return "meta";
}
// C#-style strings where "" escapes a quote.
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
CodeMirror.defineMIME("text/x-csrc", {
name: "clike",
keywords: words(cKeywords),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null"),
hooks: {"#": cppHook}
});
CodeMirror.defineMIME("text/x-c++src", {
name: "clike",
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
"static_cast typeid catch operator template typename class friend private " +
"this using const_cast inline public throw virtual delete mutable protected " +
"wchar_t"),
blockKeywords: words("catch class do else finally for if struct switch try while"),
atoms: words("true false null"),
hooks: {"#": cppHook}
});
CodeMirror.defineMIME("text/x-java", {
name: "clike",
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
"do double else enum extends final finally float for goto if implements import " +
"instanceof int interface long native new package private protected public " +
"return short static strictfp super switch synchronized this throw throws transient " +
"try void volatile while"),
blockKeywords: words("catch class do else finally for if switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
CodeMirror.defineMIME("text/x-csharp", {
name: "clike",
keywords: words("abstract as base bool break byte case catch char checked class const continue decimal" +
" default delegate do double else enum event explicit extern finally fixed float for" +
" foreach goto if implicit in int interface internal is lock long namespace new object" +
" operator out override params private protected public readonly ref return sbyte sealed short" +
" sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked" +
" unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield"),
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
if (stream.eat('"')) {
state.tokenize = tokenAtString;
return tokenAtString(stream, state);
}
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
}());
|
kylesawatsky/sl-website
|
wp-content/uploads/wp-clone/wpclone_backup/wp-content/plugins/debug-bar-console/codemirror/mode/clike.js
|
JavaScript
|
gpl-2.0
| 8,404
|
/*
* Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2008 S3 Graphics, Inc. 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;
* 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 WARRANTIES OR REPRESENTATIONS; 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.
*/
#include <linux/via-core.h>
#include "global.h"
static struct pll_config cle266_pll_config[] = {
{19, 4, 0},
{26, 5, 0},
{28, 5, 0},
{31, 5, 0},
{33, 5, 0},
{55, 5, 0},
{102, 5, 0},
{53, 6, 0},
{92, 6, 0},
{98, 6, 0},
{112, 6, 0},
{41, 7, 0},
{60, 7, 0},
{99, 7, 0},
{100, 7, 0},
{83, 8, 0},
{86, 8, 0},
{108, 8, 0},
{87, 9, 0},
{118, 9, 0},
{95, 12, 0},
{115, 12, 0},
{108, 13, 0},
{83, 17, 0},
{67, 20, 0},
{86, 20, 0},
{98, 20, 0},
{121, 24, 0},
{99, 29, 0},
{33, 3, 1},
{15, 4, 1},
{23, 4, 1},
{37, 5, 1},
{83, 5, 1},
{85, 5, 1},
{94, 5, 1},
{103, 5, 1},
{109, 5, 1},
{113, 5, 1},
{121, 5, 1},
{82, 6, 1},
{31, 7, 1},
{55, 7, 1},
{84, 7, 1},
{83, 8, 1},
{76, 9, 1},
{127, 9, 1},
{33, 4, 2},
{75, 4, 2},
{119, 4, 2},
{121, 4, 2},
{91, 5, 2},
{118, 5, 2},
{83, 6, 2},
{109, 6, 2},
{90, 7, 2},
{93, 2, 3},
{53, 3, 3},
{73, 4, 3},
{89, 4, 3},
{105, 4, 3},
{117, 4, 3},
{101, 5, 3},
{121, 5, 3},
{127, 5, 3},
{99, 7, 3}
};
static struct pll_config k800_pll_config[] = {
{22, 2, 0},
{28, 3, 0},
{81, 3, 1},
{85, 3, 1},
{98, 3, 1},
{112, 3, 1},
{86, 4, 1},
{166, 4, 1},
{109, 5, 1},
{113, 5, 1},
{121, 5, 1},
{131, 5, 1},
{143, 5, 1},
{153, 5, 1},
{66, 3, 2},
{68, 3, 2},
{95, 3, 2},
{106, 3, 2},
{116, 3, 2},
{93, 4, 2},
{119, 4, 2},
{121, 4, 2},
{133, 4, 2},
{137, 4, 2},
{117, 5, 2},
{118, 5, 2},
{120, 5, 2},
{124, 5, 2},
{132, 5, 2},
{137, 5, 2},
{141, 5, 2},
{166, 5, 2},
{170, 5, 2},
{191, 5, 2},
{206, 5, 2},
{208, 5, 2},
{30, 2, 3},
{69, 3, 3},
{82, 3, 3},
{83, 3, 3},
{109, 3, 3},
{114, 3, 3},
{125, 3, 3},
{89, 4, 3},
{103, 4, 3},
{117, 4, 3},
{126, 4, 3},
{150, 4, 3},
{161, 4, 3},
{121, 5, 3},
{127, 5, 3},
{131, 5, 3},
{134, 5, 3},
{148, 5, 3},
{169, 5, 3},
{172, 5, 3},
{182, 5, 3},
{195, 5, 3},
{196, 5, 3},
{208, 5, 3},
{66, 2, 4},
{85, 3, 4},
{141, 4, 4},
{146, 4, 4},
{161, 4, 4},
{177, 5, 4}
};
static struct pll_config cx700_pll_config[] = {
{98, 3, 1},
{86, 4, 1},
{109, 5, 1},
{110, 5, 1},
{113, 5, 1},
{121, 5, 1},
{131, 5, 1},
{135, 5, 1},
{142, 5, 1},
{143, 5, 1},
{153, 5, 1},
{187, 5, 1},
{208, 5, 1},
{68, 2, 2},
{95, 3, 2},
{116, 3, 2},
{93, 4, 2},
{119, 4, 2},
{133, 4, 2},
{137, 4, 2},
{151, 4, 2},
{166, 4, 2},
{110, 5, 2},
{112, 5, 2},
{117, 5, 2},
{118, 5, 2},
{120, 5, 2},
{132, 5, 2},
{137, 5, 2},
{141, 5, 2},
{151, 5, 2},
{166, 5, 2},
{175, 5, 2},
{191, 5, 2},
{206, 5, 2},
{174, 7, 2},
{82, 3, 3},
{109, 3, 3},
{117, 4, 3},
{150, 4, 3},
{161, 4, 3},
{112, 5, 3},
{115, 5, 3},
{121, 5, 3},
{127, 5, 3},
{129, 5, 3},
{131, 5, 3},
{134, 5, 3},
{138, 5, 3},
{148, 5, 3},
{157, 5, 3},
{169, 5, 3},
{172, 5, 3},
{190, 5, 3},
{195, 5, 3},
{196, 5, 3},
{208, 5, 3},
{141, 5, 4},
{150, 5, 4},
{166, 5, 4},
{176, 5, 4},
{177, 5, 4},
{183, 5, 4},
{202, 5, 4}
};
static struct pll_config vx855_pll_config[] = {
{86, 4, 1},
{108, 5, 1},
{110, 5, 1},
{113, 5, 1},
{121, 5, 1},
{131, 5, 1},
{135, 5, 1},
{142, 5, 1},
{143, 5, 1},
{153, 5, 1},
{164, 5, 1},
{187, 5, 1},
{208, 5, 1},
{110, 5, 2},
{112, 5, 2},
{117, 5, 2},
{118, 5, 2},
{124, 5, 2},
{132, 5, 2},
{137, 5, 2},
{141, 5, 2},
{149, 5, 2},
{151, 5, 2},
{159, 5, 2},
{166, 5, 2},
{167, 5, 2},
{172, 5, 2},
{189, 5, 2},
{191, 5, 2},
{194, 5, 2},
{206, 5, 2},
{208, 5, 2},
{83, 3, 3},
{88, 3, 3},
{109, 3, 3},
{112, 3, 3},
{103, 4, 3},
{105, 4, 3},
{161, 4, 3},
{112, 5, 3},
{115, 5, 3},
{121, 5, 3},
{127, 5, 3},
{134, 5, 3},
{137, 5, 3},
{148, 5, 3},
{157, 5, 3},
{169, 5, 3},
{172, 5, 3},
{182, 5, 3},
{191, 5, 3},
{195, 5, 3},
{209, 5, 3},
{142, 4, 4},
{146, 4, 4},
{161, 4, 4},
{141, 5, 4},
{150, 5, 4},
{165, 5, 4},
{176, 5, 4}
};
/* according to VIA Technologies these values are based on experiment */
static struct io_reg scaling_parameters[] = {
{VIACR, CR7A, 0xFF, 0x01}, /* LCD Scaling Parameter 1 */
{VIACR, CR7B, 0xFF, 0x02}, /* LCD Scaling Parameter 2 */
{VIACR, CR7C, 0xFF, 0x03}, /* LCD Scaling Parameter 3 */
{VIACR, CR7D, 0xFF, 0x04}, /* LCD Scaling Parameter 4 */
{VIACR, CR7E, 0xFF, 0x07}, /* LCD Scaling Parameter 5 */
{VIACR, CR7F, 0xFF, 0x0A}, /* LCD Scaling Parameter 6 */
{VIACR, CR80, 0xFF, 0x0D}, /* LCD Scaling Parameter 7 */
{VIACR, CR81, 0xFF, 0x13}, /* LCD Scaling Parameter 8 */
{VIACR, CR82, 0xFF, 0x16}, /* LCD Scaling Parameter 9 */
{VIACR, CR83, 0xFF, 0x19}, /* LCD Scaling Parameter 10 */
{VIACR, CR84, 0xFF, 0x1C}, /* LCD Scaling Parameter 11 */
{VIACR, CR85, 0xFF, 0x1D}, /* LCD Scaling Parameter 12 */
{VIACR, CR86, 0xFF, 0x1E}, /* LCD Scaling Parameter 13 */
{VIACR, CR87, 0xFF, 0x1F}, /* LCD Scaling Parameter 14 */
};
static struct fifo_depth_select display_fifo_depth_reg = {
/* IGA1 FIFO Depth_Select */
{IGA1_FIFO_DEPTH_SELECT_REG_NUM, {{SR17, 0, 7} } },
/* IGA2 FIFO Depth_Select */
{IGA2_FIFO_DEPTH_SELECT_REG_NUM,
{{CR68, 4, 7}, {CR94, 7, 7}, {CR95, 7, 7} } }
};
static struct fifo_threshold_select fifo_threshold_select_reg = {
/* IGA1 FIFO Threshold Select */
{IGA1_FIFO_THRESHOLD_REG_NUM, {{SR16, 0, 5}, {SR16, 7, 7} } },
/* IGA2 FIFO Threshold Select */
{IGA2_FIFO_THRESHOLD_REG_NUM, {{CR68, 0, 3}, {CR95, 4, 6} } }
};
static struct fifo_high_threshold_select fifo_high_threshold_select_reg = {
/* IGA1 FIFO High Threshold Select */
{IGA1_FIFO_HIGH_THRESHOLD_REG_NUM, {{SR18, 0, 5}, {SR18, 7, 7} } },
/* IGA2 FIFO High Threshold Select */
{IGA2_FIFO_HIGH_THRESHOLD_REG_NUM, {{CR92, 0, 3}, {CR95, 0, 2} } }
};
static struct display_queue_expire_num display_queue_expire_num_reg = {
/* IGA1 Display Queue Expire Num */
{IGA1_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{SR22, 0, 4} } },
/* IGA2 Display Queue Expire Num */
{IGA2_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{CR94, 0, 6} } }
};
/* Definition Fetch Count Registers*/
static struct fetch_count fetch_count_reg = {
/* IGA1 Fetch Count Register */
{IGA1_FETCH_COUNT_REG_NUM, {{SR1C, 0, 7}, {SR1D, 0, 1} } },
/* IGA2 Fetch Count Register */
{IGA2_FETCH_COUNT_REG_NUM, {{CR65, 0, 7}, {CR67, 2, 3} } }
};
static struct iga1_crtc_timing iga1_crtc_reg = {
/* IGA1 Horizontal Total */
{IGA1_HOR_TOTAL_REG_NUM, {{CR00, 0, 7}, {CR36, 3, 3} } },
/* IGA1 Horizontal Addressable Video */
{IGA1_HOR_ADDR_REG_NUM, {{CR01, 0, 7} } },
/* IGA1 Horizontal Blank Start */
{IGA1_HOR_BLANK_START_REG_NUM, {{CR02, 0, 7} } },
/* IGA1 Horizontal Blank End */
{IGA1_HOR_BLANK_END_REG_NUM,
{{CR03, 0, 4}, {CR05, 7, 7}, {CR33, 5, 5} } },
/* IGA1 Horizontal Sync Start */
{IGA1_HOR_SYNC_START_REG_NUM, {{CR04, 0, 7}, {CR33, 4, 4} } },
/* IGA1 Horizontal Sync End */
{IGA1_HOR_SYNC_END_REG_NUM, {{CR05, 0, 4} } },
/* IGA1 Vertical Total */
{IGA1_VER_TOTAL_REG_NUM,
{{CR06, 0, 7}, {CR07, 0, 0}, {CR07, 5, 5}, {CR35, 0, 0} } },
/* IGA1 Vertical Addressable Video */
{IGA1_VER_ADDR_REG_NUM,
{{CR12, 0, 7}, {CR07, 1, 1}, {CR07, 6, 6}, {CR35, 2, 2} } },
/* IGA1 Vertical Blank Start */
{IGA1_VER_BLANK_START_REG_NUM,
{{CR15, 0, 7}, {CR07, 3, 3}, {CR09, 5, 5}, {CR35, 3, 3} } },
/* IGA1 Vertical Blank End */
{IGA1_VER_BLANK_END_REG_NUM, {{CR16, 0, 7} } },
/* IGA1 Vertical Sync Start */
{IGA1_VER_SYNC_START_REG_NUM,
{{CR10, 0, 7}, {CR07, 2, 2}, {CR07, 7, 7}, {CR35, 1, 1} } },
/* IGA1 Vertical Sync End */
{IGA1_VER_SYNC_END_REG_NUM, {{CR11, 0, 3} } }
};
static struct iga2_crtc_timing iga2_crtc_reg = {
/* IGA2 Horizontal Total */
{IGA2_HOR_TOTAL_REG_NUM, {{CR50, 0, 7}, {CR55, 0, 3} } },
/* IGA2 Horizontal Addressable Video */
{IGA2_HOR_ADDR_REG_NUM, {{CR51, 0, 7}, {CR55, 4, 6} } },
/* IGA2 Horizontal Blank Start */
{IGA2_HOR_BLANK_START_REG_NUM, {{CR52, 0, 7}, {CR54, 0, 2} } },
/* IGA2 Horizontal Blank End */
{IGA2_HOR_BLANK_END_REG_NUM,
{{CR53, 0, 7}, {CR54, 3, 5}, {CR5D, 6, 6} } },
/* IGA2 Horizontal Sync Start */
{IGA2_HOR_SYNC_START_REG_NUM,
{{CR56, 0, 7}, {CR54, 6, 7}, {CR5C, 7, 7}, {CR5D, 7, 7} } },
/* IGA2 Horizontal Sync End */
{IGA2_HOR_SYNC_END_REG_NUM, {{CR57, 0, 7}, {CR5C, 6, 6} } },
/* IGA2 Vertical Total */
{IGA2_VER_TOTAL_REG_NUM, {{CR58, 0, 7}, {CR5D, 0, 2} } },
/* IGA2 Vertical Addressable Video */
{IGA2_VER_ADDR_REG_NUM, {{CR59, 0, 7}, {CR5D, 3, 5} } },
/* IGA2 Vertical Blank Start */
{IGA2_VER_BLANK_START_REG_NUM, {{CR5A, 0, 7}, {CR5C, 0, 2} } },
/* IGA2 Vertical Blank End */
{IGA2_VER_BLANK_END_REG_NUM, {{CR5B, 0, 7}, {CR5C, 3, 5} } },
/* IGA2 Vertical Sync Start */
{IGA2_VER_SYNC_START_REG_NUM, {{CR5E, 0, 7}, {CR5F, 5, 7} } },
/* IGA2 Vertical Sync End */
{IGA2_VER_SYNC_END_REG_NUM, {{CR5F, 0, 4} } }
};
static struct rgbLUT palLUT_table[] = {
/* {R,G,B} */
/* Index 0x00~0x03 */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x2A}, {0x00, 0x2A, 0x00}, {0x00,
0x2A,
0x2A},
/* Index 0x04~0x07 */
{0x2A, 0x00, 0x00}, {0x2A, 0x00, 0x2A}, {0x2A, 0x15, 0x00}, {0x2A,
0x2A,
0x2A},
/* Index 0x08~0x0B */
{0x15, 0x15, 0x15}, {0x15, 0x15, 0x3F}, {0x15, 0x3F, 0x15}, {0x15,
0x3F,
0x3F},
/* Index 0x0C~0x0F */
{0x3F, 0x15, 0x15}, {0x3F, 0x15, 0x3F}, {0x3F, 0x3F, 0x15}, {0x3F,
0x3F,
0x3F},
/* Index 0x10~0x13 */
{0x00, 0x00, 0x00}, {0x05, 0x05, 0x05}, {0x08, 0x08, 0x08}, {0x0B,
0x0B,
0x0B},
/* Index 0x14~0x17 */
{0x0E, 0x0E, 0x0E}, {0x11, 0x11, 0x11}, {0x14, 0x14, 0x14}, {0x18,
0x18,
0x18},
/* Index 0x18~0x1B */
{0x1C, 0x1C, 0x1C}, {0x20, 0x20, 0x20}, {0x24, 0x24, 0x24}, {0x28,
0x28,
0x28},
/* Index 0x1C~0x1F */
{0x2D, 0x2D, 0x2D}, {0x32, 0x32, 0x32}, {0x38, 0x38, 0x38}, {0x3F,
0x3F,
0x3F},
/* Index 0x20~0x23 */
{0x00, 0x00, 0x3F}, {0x10, 0x00, 0x3F}, {0x1F, 0x00, 0x3F}, {0x2F,
0x00,
0x3F},
/* Index 0x24~0x27 */
{0x3F, 0x00, 0x3F}, {0x3F, 0x00, 0x2F}, {0x3F, 0x00, 0x1F}, {0x3F,
0x00,
0x10},
/* Index 0x28~0x2B */
{0x3F, 0x00, 0x00}, {0x3F, 0x10, 0x00}, {0x3F, 0x1F, 0x00}, {0x3F,
0x2F,
0x00},
/* Index 0x2C~0x2F */
{0x3F, 0x3F, 0x00}, {0x2F, 0x3F, 0x00}, {0x1F, 0x3F, 0x00}, {0x10,
0x3F,
0x00},
/* Index 0x30~0x33 */
{0x00, 0x3F, 0x00}, {0x00, 0x3F, 0x10}, {0x00, 0x3F, 0x1F}, {0x00,
0x3F,
0x2F},
/* Index 0x34~0x37 */
{0x00, 0x3F, 0x3F}, {0x00, 0x2F, 0x3F}, {0x00, 0x1F, 0x3F}, {0x00,
0x10,
0x3F},
/* Index 0x38~0x3B */
{0x1F, 0x1F, 0x3F}, {0x27, 0x1F, 0x3F}, {0x2F, 0x1F, 0x3F}, {0x37,
0x1F,
0x3F},
/* Index 0x3C~0x3F */
{0x3F, 0x1F, 0x3F}, {0x3F, 0x1F, 0x37}, {0x3F, 0x1F, 0x2F}, {0x3F,
0x1F,
0x27},
/* Index 0x40~0x43 */
{0x3F, 0x1F, 0x1F}, {0x3F, 0x27, 0x1F}, {0x3F, 0x2F, 0x1F}, {0x3F,
0x3F,
0x1F},
/* Index 0x44~0x47 */
{0x3F, 0x3F, 0x1F}, {0x37, 0x3F, 0x1F}, {0x2F, 0x3F, 0x1F}, {0x27,
0x3F,
0x1F},
/* Index 0x48~0x4B */
{0x1F, 0x3F, 0x1F}, {0x1F, 0x3F, 0x27}, {0x1F, 0x3F, 0x2F}, {0x1F,
0x3F,
0x37},
/* Index 0x4C~0x4F */
{0x1F, 0x3F, 0x3F}, {0x1F, 0x37, 0x3F}, {0x1F, 0x2F, 0x3F}, {0x1F,
0x27,
0x3F},
/* Index 0x50~0x53 */
{0x2D, 0x2D, 0x3F}, {0x31, 0x2D, 0x3F}, {0x36, 0x2D, 0x3F}, {0x3A,
0x2D,
0x3F},
/* Index 0x54~0x57 */
{0x3F, 0x2D, 0x3F}, {0x3F, 0x2D, 0x3A}, {0x3F, 0x2D, 0x36}, {0x3F,
0x2D,
0x31},
/* Index 0x58~0x5B */
{0x3F, 0x2D, 0x2D}, {0x3F, 0x31, 0x2D}, {0x3F, 0x36, 0x2D}, {0x3F,
0x3A,
0x2D},
/* Index 0x5C~0x5F */
{0x3F, 0x3F, 0x2D}, {0x3A, 0x3F, 0x2D}, {0x36, 0x3F, 0x2D}, {0x31,
0x3F,
0x2D},
/* Index 0x60~0x63 */
{0x2D, 0x3F, 0x2D}, {0x2D, 0x3F, 0x31}, {0x2D, 0x3F, 0x36}, {0x2D,
0x3F,
0x3A},
/* Index 0x64~0x67 */
{0x2D, 0x3F, 0x3F}, {0x2D, 0x3A, 0x3F}, {0x2D, 0x36, 0x3F}, {0x2D,
0x31,
0x3F},
/* Index 0x68~0x6B */
{0x00, 0x00, 0x1C}, {0x07, 0x00, 0x1C}, {0x0E, 0x00, 0x1C}, {0x15,
0x00,
0x1C},
/* Index 0x6C~0x6F */
{0x1C, 0x00, 0x1C}, {0x1C, 0x00, 0x15}, {0x1C, 0x00, 0x0E}, {0x1C,
0x00,
0x07},
/* Index 0x70~0x73 */
{0x1C, 0x00, 0x00}, {0x1C, 0x07, 0x00}, {0x1C, 0x0E, 0x00}, {0x1C,
0x15,
0x00},
/* Index 0x74~0x77 */
{0x1C, 0x1C, 0x00}, {0x15, 0x1C, 0x00}, {0x0E, 0x1C, 0x00}, {0x07,
0x1C,
0x00},
/* Index 0x78~0x7B */
{0x00, 0x1C, 0x00}, {0x00, 0x1C, 0x07}, {0x00, 0x1C, 0x0E}, {0x00,
0x1C,
0x15},
/* Index 0x7C~0x7F */
{0x00, 0x1C, 0x1C}, {0x00, 0x15, 0x1C}, {0x00, 0x0E, 0x1C}, {0x00,
0x07,
0x1C},
/* Index 0x80~0x83 */
{0x0E, 0x0E, 0x1C}, {0x11, 0x0E, 0x1C}, {0x15, 0x0E, 0x1C}, {0x18,
0x0E,
0x1C},
/* Index 0x84~0x87 */
{0x1C, 0x0E, 0x1C}, {0x1C, 0x0E, 0x18}, {0x1C, 0x0E, 0x15}, {0x1C,
0x0E,
0x11},
/* Index 0x88~0x8B */
{0x1C, 0x0E, 0x0E}, {0x1C, 0x11, 0x0E}, {0x1C, 0x15, 0x0E}, {0x1C,
0x18,
0x0E},
/* Index 0x8C~0x8F */
{0x1C, 0x1C, 0x0E}, {0x18, 0x1C, 0x0E}, {0x15, 0x1C, 0x0E}, {0x11,
0x1C,
0x0E},
/* Index 0x90~0x93 */
{0x0E, 0x1C, 0x0E}, {0x0E, 0x1C, 0x11}, {0x0E, 0x1C, 0x15}, {0x0E,
0x1C,
0x18},
/* Index 0x94~0x97 */
{0x0E, 0x1C, 0x1C}, {0x0E, 0x18, 0x1C}, {0x0E, 0x15, 0x1C}, {0x0E,
0x11,
0x1C},
/* Index 0x98~0x9B */
{0x14, 0x14, 0x1C}, {0x16, 0x14, 0x1C}, {0x18, 0x14, 0x1C}, {0x1A,
0x14,
0x1C},
/* Index 0x9C~0x9F */
{0x1C, 0x14, 0x1C}, {0x1C, 0x14, 0x1A}, {0x1C, 0x14, 0x18}, {0x1C,
0x14,
0x16},
/* Index 0xA0~0xA3 */
{0x1C, 0x14, 0x14}, {0x1C, 0x16, 0x14}, {0x1C, 0x18, 0x14}, {0x1C,
0x1A,
0x14},
/* Index 0xA4~0xA7 */
{0x1C, 0x1C, 0x14}, {0x1A, 0x1C, 0x14}, {0x18, 0x1C, 0x14}, {0x16,
0x1C,
0x14},
/* Index 0xA8~0xAB */
{0x14, 0x1C, 0x14}, {0x14, 0x1C, 0x16}, {0x14, 0x1C, 0x18}, {0x14,
0x1C,
0x1A},
/* Index 0xAC~0xAF */
{0x14, 0x1C, 0x1C}, {0x14, 0x1A, 0x1C}, {0x14, 0x18, 0x1C}, {0x14,
0x16,
0x1C},
/* Index 0xB0~0xB3 */
{0x00, 0x00, 0x10}, {0x04, 0x00, 0x10}, {0x08, 0x00, 0x10}, {0x0C,
0x00,
0x10},
/* Index 0xB4~0xB7 */
{0x10, 0x00, 0x10}, {0x10, 0x00, 0x0C}, {0x10, 0x00, 0x08}, {0x10,
0x00,
0x04},
/* Index 0xB8~0xBB */
{0x10, 0x00, 0x00}, {0x10, 0x04, 0x00}, {0x10, 0x08, 0x00}, {0x10,
0x0C,
0x00},
/* Index 0xBC~0xBF */
{0x10, 0x10, 0x00}, {0x0C, 0x10, 0x00}, {0x08, 0x10, 0x00}, {0x04,
0x10,
0x00},
/* Index 0xC0~0xC3 */
{0x00, 0x10, 0x00}, {0x00, 0x10, 0x04}, {0x00, 0x10, 0x08}, {0x00,
0x10,
0x0C},
/* Index 0xC4~0xC7 */
{0x00, 0x10, 0x10}, {0x00, 0x0C, 0x10}, {0x00, 0x08, 0x10}, {0x00,
0x04,
0x10},
/* Index 0xC8~0xCB */
{0x08, 0x08, 0x10}, {0x0A, 0x08, 0x10}, {0x0C, 0x08, 0x10}, {0x0E,
0x08,
0x10},
/* Index 0xCC~0xCF */
{0x10, 0x08, 0x10}, {0x10, 0x08, 0x0E}, {0x10, 0x08, 0x0C}, {0x10,
0x08,
0x0A},
/* Index 0xD0~0xD3 */
{0x10, 0x08, 0x08}, {0x10, 0x0A, 0x08}, {0x10, 0x0C, 0x08}, {0x10,
0x0E,
0x08},
/* Index 0xD4~0xD7 */
{0x10, 0x10, 0x08}, {0x0E, 0x10, 0x08}, {0x0C, 0x10, 0x08}, {0x0A,
0x10,
0x08},
/* Index 0xD8~0xDB */
{0x08, 0x10, 0x08}, {0x08, 0x10, 0x0A}, {0x08, 0x10, 0x0C}, {0x08,
0x10,
0x0E},
/* Index 0xDC~0xDF */
{0x08, 0x10, 0x10}, {0x08, 0x0E, 0x10}, {0x08, 0x0C, 0x10}, {0x08,
0x0A,
0x10},
/* Index 0xE0~0xE3 */
{0x0B, 0x0B, 0x10}, {0x0C, 0x0B, 0x10}, {0x0D, 0x0B, 0x10}, {0x0F,
0x0B,
0x10},
/* Index 0xE4~0xE7 */
{0x10, 0x0B, 0x10}, {0x10, 0x0B, 0x0F}, {0x10, 0x0B, 0x0D}, {0x10,
0x0B,
0x0C},
/* Index 0xE8~0xEB */
{0x10, 0x0B, 0x0B}, {0x10, 0x0C, 0x0B}, {0x10, 0x0D, 0x0B}, {0x10,
0x0F,
0x0B},
/* Index 0xEC~0xEF */
{0x10, 0x10, 0x0B}, {0x0F, 0x10, 0x0B}, {0x0D, 0x10, 0x0B}, {0x0C,
0x10,
0x0B},
/* Index 0xF0~0xF3 */
{0x0B, 0x10, 0x0B}, {0x0B, 0x10, 0x0C}, {0x0B, 0x10, 0x0D}, {0x0B,
0x10,
0x0F},
/* Index 0xF4~0xF7 */
{0x0B, 0x10, 0x10}, {0x0B, 0x0F, 0x10}, {0x0B, 0x0D, 0x10}, {0x0B,
0x0C,
0x10},
/* Index 0xF8~0xFB */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00,
0x00,
0x00},
/* Index 0xFC~0xFF */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00,
0x00,
0x00}
};
static struct via_device_mapping device_mapping[] = {
{VIA_LDVP0, "LDVP0"},
{VIA_LDVP1, "LDVP1"},
{VIA_DVP0, "DVP0"},
{VIA_CRT, "CRT"},
{VIA_DVP1, "DVP1"},
{VIA_LVDS1, "LVDS1"},
{VIA_LVDS2, "LVDS2"}
};
static void load_fix_bit_crtc_reg(void);
static void __devinit init_gfx_chip_info(int chip_type);
static void __devinit init_tmds_chip_info(void);
static void __devinit init_lvds_chip_info(void);
static void device_screen_off(void);
static void device_screen_on(void);
static void set_display_channel(void);
static void device_off(void);
static void device_on(void);
static void enable_second_display_channel(void);
static void disable_second_display_channel(void);
void viafb_lock_crt(void)
{
viafb_write_reg_mask(CR11, VIACR, BIT7, BIT7);
}
void viafb_unlock_crt(void)
{
viafb_write_reg_mask(CR11, VIACR, 0, BIT7);
viafb_write_reg_mask(CR47, VIACR, 0, BIT0);
}
static void write_dac_reg(u8 index, u8 r, u8 g, u8 b)
{
outb(index, LUT_INDEX_WRITE);
outb(r, LUT_DATA);
outb(g, LUT_DATA);
outb(b, LUT_DATA);
}
static u32 get_dvi_devices(int output_interface)
{
switch (output_interface) {
case INTERFACE_DVP0:
return VIA_DVP0 | VIA_LDVP0;
case INTERFACE_DVP1:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return VIA_LDVP1;
else
return VIA_DVP1;
case INTERFACE_DFP_HIGH:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return 0;
else
return VIA_LVDS2 | VIA_DVP0;
case INTERFACE_DFP_LOW:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return 0;
else
return VIA_DVP1 | VIA_LVDS1;
case INTERFACE_TMDS:
return VIA_LVDS1;
}
return 0;
}
static u32 get_lcd_devices(int output_interface)
{
switch (output_interface) {
case INTERFACE_DVP0:
return VIA_DVP0;
case INTERFACE_DVP1:
return VIA_DVP1;
case INTERFACE_DFP_HIGH:
return VIA_LVDS2 | VIA_DVP0;
case INTERFACE_DFP_LOW:
return VIA_LVDS1 | VIA_DVP1;
case INTERFACE_DFP:
return VIA_LVDS1 | VIA_LVDS2;
case INTERFACE_LVDS0:
case INTERFACE_LVDS0LVDS1:
return VIA_LVDS1;
case INTERFACE_LVDS1:
return VIA_LVDS2;
}
return 0;
}
/*Set IGA path for each device*/
void viafb_set_iga_path(void)
{
if (viafb_SAMM_ON == 1) {
if (viafb_CRT_ON) {
if (viafb_primary_dev == CRT_Device)
viaparinfo->crt_setting_info->iga_path = IGA1;
else
viaparinfo->crt_setting_info->iga_path = IGA2;
}
if (viafb_DVI_ON) {
if (viafb_primary_dev == DVI_Device)
viaparinfo->tmds_setting_info->iga_path = IGA1;
else
viaparinfo->tmds_setting_info->iga_path = IGA2;
}
if (viafb_LCD_ON) {
if (viafb_primary_dev == LCD_Device) {
if (viafb_dual_fb &&
(viaparinfo->chip_info->gfx_chip_name ==
UNICHROME_CLE266)) {
viaparinfo->
lvds_setting_info->iga_path = IGA2;
viaparinfo->
crt_setting_info->iga_path = IGA1;
viaparinfo->
tmds_setting_info->iga_path = IGA1;
} else
viaparinfo->
lvds_setting_info->iga_path = IGA1;
} else {
viaparinfo->lvds_setting_info->iga_path = IGA2;
}
}
if (viafb_LCD2_ON) {
if (LCD2_Device == viafb_primary_dev)
viaparinfo->lvds_setting_info2->iga_path = IGA1;
else
viaparinfo->lvds_setting_info2->iga_path = IGA2;
}
} else {
viafb_SAMM_ON = 0;
if (viafb_CRT_ON && viafb_LCD_ON) {
viaparinfo->crt_setting_info->iga_path = IGA1;
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_CRT_ON && viafb_DVI_ON) {
viaparinfo->crt_setting_info->iga_path = IGA1;
viaparinfo->tmds_setting_info->iga_path = IGA2;
} else if (viafb_LCD_ON && viafb_DVI_ON) {
viaparinfo->tmds_setting_info->iga_path = IGA1;
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_LCD_ON && viafb_LCD2_ON) {
viaparinfo->lvds_setting_info->iga_path = IGA2;
viaparinfo->lvds_setting_info2->iga_path = IGA2;
} else if (viafb_CRT_ON) {
viaparinfo->crt_setting_info->iga_path = IGA1;
} else if (viafb_LCD_ON) {
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_DVI_ON) {
viaparinfo->tmds_setting_info->iga_path = IGA1;
}
}
viaparinfo->shared->iga1_devices = 0;
viaparinfo->shared->iga2_devices = 0;
if (viafb_CRT_ON) {
if (viaparinfo->crt_setting_info->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= VIA_CRT;
else
viaparinfo->shared->iga2_devices |= VIA_CRT;
}
if (viafb_DVI_ON) {
if (viaparinfo->tmds_setting_info->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_dvi_devices(
viaparinfo->chip_info->
tmds_chip_info.output_interface);
else
viaparinfo->shared->iga2_devices |= get_dvi_devices(
viaparinfo->chip_info->
tmds_chip_info.output_interface);
}
if (viafb_LCD_ON) {
if (viaparinfo->lvds_setting_info->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info.output_interface);
else
viaparinfo->shared->iga2_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info.output_interface);
}
if (viafb_LCD2_ON) {
if (viaparinfo->lvds_setting_info2->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info2.output_interface);
else
viaparinfo->shared->iga2_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info2.output_interface);
}
}
static void set_color_register(u8 index, u8 red, u8 green, u8 blue)
{
outb(0xFF, 0x3C6); /* bit mask of palette */
outb(index, 0x3C8);
outb(red, 0x3C9);
outb(green, 0x3C9);
outb(blue, 0x3C9);
}
void viafb_set_primary_color_register(u8 index, u8 red, u8 green, u8 blue)
{
viafb_write_reg_mask(0x1A, VIASR, 0x00, 0x01);
set_color_register(index, red, green, blue);
}
void viafb_set_secondary_color_register(u8 index, u8 red, u8 green, u8 blue)
{
viafb_write_reg_mask(0x1A, VIASR, 0x01, 0x01);
set_color_register(index, red, green, blue);
}
static void set_source_common(u8 index, u8 offset, u8 iga)
{
u8 value, mask = 1 << offset;
switch (iga) {
case IGA1:
value = 0x00;
break;
case IGA2:
value = mask;
break;
default:
printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga);
return;
}
via_write_reg_mask(VIACR, index, value, mask);
}
static void set_crt_source(u8 iga)
{
u8 value;
switch (iga) {
case IGA1:
value = 0x00;
break;
case IGA2:
value = 0x40;
break;
default:
printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga);
return;
}
via_write_reg_mask(VIASR, 0x16, value, 0x40);
}
static inline void set_ldvp0_source(u8 iga)
{
set_source_common(0x6C, 7, iga);
}
static inline void set_ldvp1_source(u8 iga)
{
set_source_common(0x93, 7, iga);
}
static inline void set_dvp0_source(u8 iga)
{
set_source_common(0x96, 4, iga);
}
static inline void set_dvp1_source(u8 iga)
{
set_source_common(0x9B, 4, iga);
}
static inline void set_lvds1_source(u8 iga)
{
set_source_common(0x99, 4, iga);
}
static inline void set_lvds2_source(u8 iga)
{
set_source_common(0x97, 4, iga);
}
void via_set_source(u32 devices, u8 iga)
{
if (devices & VIA_LDVP0)
set_ldvp0_source(iga);
if (devices & VIA_LDVP1)
set_ldvp1_source(iga);
if (devices & VIA_DVP0)
set_dvp0_source(iga);
if (devices & VIA_CRT)
set_crt_source(iga);
if (devices & VIA_DVP1)
set_dvp1_source(iga);
if (devices & VIA_LVDS1)
set_lvds1_source(iga);
if (devices & VIA_LVDS2)
set_lvds2_source(iga);
}
static void set_crt_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x00;
break;
case VIA_STATE_STANDBY:
value = 0x10;
break;
case VIA_STATE_SUSPEND:
value = 0x20;
break;
case VIA_STATE_OFF:
value = 0x30;
break;
default:
return;
}
via_write_reg_mask(VIACR, 0x36, value, 0x30);
}
static void set_dvp0_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0xC0;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x1E, value, 0xC0);
}
static void set_dvp1_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x30;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x1E, value, 0x30);
}
static void set_lvds1_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x03;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x2A, value, 0x03);
}
static void set_lvds2_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x0C;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x2A, value, 0x0C);
}
void via_set_state(u32 devices, u8 state)
{
/*
TODO: Can we enable/disable these devices? How?
if (devices & VIA_LDVP0)
if (devices & VIA_LDVP1)
*/
if (devices & VIA_DVP0)
set_dvp0_state(state);
if (devices & VIA_CRT)
set_crt_state(state);
if (devices & VIA_DVP1)
set_dvp1_state(state);
if (devices & VIA_LVDS1)
set_lvds1_state(state);
if (devices & VIA_LVDS2)
set_lvds2_state(state);
}
void via_set_sync_polarity(u32 devices, u8 polarity)
{
if (polarity & ~(VIA_HSYNC_NEGATIVE | VIA_VSYNC_NEGATIVE)) {
printk(KERN_WARNING "viafb: Unsupported polarity: %d\n",
polarity);
return;
}
if (devices & VIA_CRT)
via_write_misc_reg_mask(polarity << 6, 0xC0);
if (devices & VIA_DVP1)
via_write_reg_mask(VIACR, 0x9B, polarity << 5, 0x60);
if (devices & VIA_LVDS1)
via_write_reg_mask(VIACR, 0x99, polarity << 5, 0x60);
if (devices & VIA_LVDS2)
via_write_reg_mask(VIACR, 0x97, polarity << 5, 0x60);
}
u32 via_parse_odev(char *input, char **end)
{
char *ptr = input;
u32 odev = 0;
bool next = true;
int i, len;
while (next) {
next = false;
for (i = 0; i < ARRAY_SIZE(device_mapping); i++) {
len = strlen(device_mapping[i].name);
if (!strncmp(ptr, device_mapping[i].name, len)) {
odev |= device_mapping[i].device;
ptr += len;
if (*ptr == ',') {
ptr++;
next = true;
}
}
}
}
*end = ptr;
return odev;
}
void via_odev_to_seq(struct seq_file *m, u32 odev)
{
int i, count = 0;
for (i = 0; i < ARRAY_SIZE(device_mapping); i++) {
if (odev & device_mapping[i].device) {
if (count > 0)
seq_putc(m, ',');
seq_puts(m, device_mapping[i].name);
count++;
}
}
seq_putc(m, '\n');
}
static void load_fix_bit_crtc_reg(void)
{
/* always set to 1 */
viafb_write_reg_mask(CR03, VIACR, 0x80, BIT7);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg(CR18, VIACR, 0xff);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR07, VIACR, 0x10, BIT4);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR09, VIACR, 0x40, BIT6);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR35, VIACR, 0x10, BIT4);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR33, VIACR, 0x06, BIT0 + BIT1 + BIT2);
/*viafb_write_reg_mask(CR32, VIACR, 0x01, BIT0); */
/* extend mode always set to e3h */
viafb_write_reg(CR17, VIACR, 0xe3);
/* extend mode always set to 0h */
viafb_write_reg(CR08, VIACR, 0x00);
/* extend mode always set to 0h */
viafb_write_reg(CR14, VIACR, 0x00);
/* If K8M800, enable Prefetch Mode. */
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800)
|| (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890))
viafb_write_reg_mask(CR33, VIACR, 0x08, BIT3);
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
&& (viaparinfo->chip_info->gfx_chip_revision == CLE266_REVISION_AX))
viafb_write_reg_mask(SR1A, VIASR, 0x02, BIT1);
}
void viafb_load_reg(int timing_value, int viafb_load_reg_num,
struct io_register *reg,
int io_type)
{
int reg_mask;
int bit_num = 0;
int data;
int i, j;
int shift_next_reg;
int start_index, end_index, cr_index;
u16 get_bit;
for (i = 0; i < viafb_load_reg_num; i++) {
reg_mask = 0;
data = 0;
start_index = reg[i].start_bit;
end_index = reg[i].end_bit;
cr_index = reg[i].io_addr;
shift_next_reg = bit_num;
for (j = start_index; j <= end_index; j++) {
/*if (bit_num==8) timing_value = timing_value >>8; */
reg_mask = reg_mask | (BIT0 << j);
get_bit = (timing_value & (BIT0 << bit_num));
data =
data | ((get_bit >> shift_next_reg) << start_index);
bit_num++;
}
if (io_type == VIACR)
viafb_write_reg_mask(cr_index, VIACR, data, reg_mask);
else
viafb_write_reg_mask(cr_index, VIASR, data, reg_mask);
}
}
/* Write Registers */
void viafb_write_regx(struct io_reg RegTable[], int ItemNum)
{
int i;
/*DEBUG_MSG(KERN_INFO "Table Size : %x!!\n",ItemNum ); */
for (i = 0; i < ItemNum; i++)
via_write_reg_mask(RegTable[i].port, RegTable[i].index,
RegTable[i].value, RegTable[i].mask);
}
void viafb_load_fetch_count_reg(int h_addr, int bpp_byte, int set_iga)
{
int reg_value;
int viafb_load_reg_num;
struct io_register *reg = NULL;
switch (set_iga) {
case IGA1:
reg_value = IGA1_FETCH_COUNT_FORMULA(h_addr, bpp_byte);
viafb_load_reg_num = fetch_count_reg.
iga1_fetch_count_reg.reg_num;
reg = fetch_count_reg.iga1_fetch_count_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
break;
case IGA2:
reg_value = IGA2_FETCH_COUNT_FORMULA(h_addr, bpp_byte);
viafb_load_reg_num = fetch_count_reg.
iga2_fetch_count_reg.reg_num;
reg = fetch_count_reg.iga2_fetch_count_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
break;
}
}
void viafb_load_FIFO_reg(int set_iga, int hor_active, int ver_active)
{
int reg_value;
int viafb_load_reg_num;
struct io_register *reg = NULL;
int iga1_fifo_max_depth = 0, iga1_fifo_threshold =
0, iga1_fifo_high_threshold = 0, iga1_display_queue_expire_num = 0;
int iga2_fifo_max_depth = 0, iga2_fifo_threshold =
0, iga2_fifo_high_threshold = 0, iga2_display_queue_expire_num = 0;
if (set_iga == IGA1) {
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
iga1_fifo_max_depth = K800_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = K800_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
K800_IGA1_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64, else
expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
K800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) {
iga1_fifo_max_depth = P880_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P880_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P880_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
/* If resolution > 1280x1024, expire length = 64, else
expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) {
iga1_fifo_max_depth = CN700_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = CN700_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
CN700_IGA1_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
CN700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
iga1_fifo_max_depth = CX700_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = CX700_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
CX700_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
CX700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) {
iga1_fifo_max_depth = K8M890_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = K8M890_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
K8M890_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
K8M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) {
iga1_fifo_max_depth = P4M890_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P4M890_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P4M890_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P4M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) {
iga1_fifo_max_depth = P4M900_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P4M900_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P4M900_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P4M900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) {
iga1_fifo_max_depth = VX800_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX800_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX800_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) {
iga1_fifo_max_depth = VX855_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX855_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX855_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX855_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) {
iga1_fifo_max_depth = VX900_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX900_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX900_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
/* Set Display FIFO Depath Select */
reg_value = IGA1_FIFO_DEPTH_SELECT_FORMULA(iga1_fifo_max_depth);
viafb_load_reg_num =
display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg_num;
reg = display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set Display FIFO Threshold Select */
reg_value = IGA1_FIFO_THRESHOLD_FORMULA(iga1_fifo_threshold);
viafb_load_reg_num =
fifo_threshold_select_reg.
iga1_fifo_threshold_select_reg.reg_num;
reg =
fifo_threshold_select_reg.
iga1_fifo_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set FIFO High Threshold Select */
reg_value =
IGA1_FIFO_HIGH_THRESHOLD_FORMULA(iga1_fifo_high_threshold);
viafb_load_reg_num =
fifo_high_threshold_select_reg.
iga1_fifo_high_threshold_select_reg.reg_num;
reg =
fifo_high_threshold_select_reg.
iga1_fifo_high_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set Display Queue Expire Num */
reg_value =
IGA1_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA
(iga1_display_queue_expire_num);
viafb_load_reg_num =
display_queue_expire_num_reg.
iga1_display_queue_expire_num_reg.reg_num;
reg =
display_queue_expire_num_reg.
iga1_display_queue_expire_num_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
} else {
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
iga2_fifo_max_depth = K800_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = K800_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
K800_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
K800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) {
iga2_fifo_max_depth = P880_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P880_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P880_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
P880_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) {
iga2_fifo_max_depth = CN700_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = CN700_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
CN700_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
CN700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
iga2_fifo_max_depth = CX700_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = CX700_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
CX700_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
CX700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) {
iga2_fifo_max_depth = K8M890_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = K8M890_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
K8M890_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
K8M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) {
iga2_fifo_max_depth = P4M890_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P4M890_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P4M890_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
P4M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) {
iga2_fifo_max_depth = P4M900_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P4M900_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P4M900_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
P4M900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) {
iga2_fifo_max_depth = VX800_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX800_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX800_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) {
iga2_fifo_max_depth = VX855_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX855_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX855_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX855_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) {
iga2_fifo_max_depth = VX900_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX900_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX900_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
/* Set Display FIFO Depath Select */
reg_value =
IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth)
- 1;
/* Patch LCD in IGA2 case */
viafb_load_reg_num =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg_num;
reg =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
} else {
/* Set Display FIFO Depath Select */
reg_value =
IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth);
viafb_load_reg_num =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg_num;
reg =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
}
/* Set Display FIFO Threshold Select */
reg_value = IGA2_FIFO_THRESHOLD_FORMULA(iga2_fifo_threshold);
viafb_load_reg_num =
fifo_threshold_select_reg.
iga2_fifo_threshold_select_reg.reg_num;
reg =
fifo_threshold_select_reg.
iga2_fifo_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
/* Set FIFO High Threshold Select */
reg_value =
IGA2_FIFO_HIGH_THRESHOLD_FORMULA(iga2_fifo_high_threshold);
viafb_load_reg_num =
fifo_high_threshold_select_reg.
iga2_fifo_high_threshold_select_reg.reg_num;
reg =
fifo_high_threshold_select_reg.
iga2_fifo_high_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
/* Set Display Queue Expire Num */
reg_value =
IGA2_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA
(iga2_display_queue_expire_num);
viafb_load_reg_num =
display_queue_expire_num_reg.
iga2_display_queue_expire_num_reg.reg_num;
reg =
display_queue_expire_num_reg.
iga2_display_queue_expire_num_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
}
}
static u32 cle266_encode_pll(struct pll_config pll)
{
return (pll.multiplier << 8)
| (pll.rshift << 6)
| pll.divisor;
}
static u32 k800_encode_pll(struct pll_config pll)
{
return ((pll.divisor - 2) << 16)
| (pll.rshift << 10)
| (pll.multiplier - 2);
}
static u32 vx855_encode_pll(struct pll_config pll)
{
return (pll.divisor << 16)
| (pll.rshift << 10)
| pll.multiplier;
}
static inline u32 get_pll_internal_frequency(u32 ref_freq,
struct pll_config pll)
{
return ref_freq / pll.divisor * pll.multiplier;
}
static inline u32 get_pll_output_frequency(u32 ref_freq, struct pll_config pll)
{
return get_pll_internal_frequency(ref_freq, pll)>>pll.rshift;
}
static struct pll_config get_pll_config(struct pll_config *config, int size,
int clk)
{
struct pll_config best = config[0];
const u32 f0 = 14318180; /* X1 frequency */
int i;
for (i = 1; i < size; i++) {
if (abs(get_pll_output_frequency(f0, config[i]) - clk)
< abs(get_pll_output_frequency(f0, best) - clk))
best = config[i];
}
return best;
}
u32 viafb_get_clk_value(int clk)
{
u32 value = 0;
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
value = cle266_encode_pll(get_pll_config(cle266_pll_config,
ARRAY_SIZE(cle266_pll_config), clk));
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
value = k800_encode_pll(get_pll_config(k800_pll_config,
ARRAY_SIZE(k800_pll_config), clk));
break;
case UNICHROME_CX700:
case UNICHROME_CN750:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_VX800:
value = k800_encode_pll(get_pll_config(cx700_pll_config,
ARRAY_SIZE(cx700_pll_config), clk));
break;
case UNICHROME_VX855:
case UNICHROME_VX900:
value = vx855_encode_pll(get_pll_config(vx855_pll_config,
ARRAY_SIZE(vx855_pll_config), clk));
break;
}
return value;
}
/* Set VCLK*/
void viafb_set_vclock(u32 clk, int set_iga)
{
/* H.W. Reset : ON */
viafb_write_reg_mask(CR17, VIACR, 0x00, BIT7);
if (set_iga == IGA1) {
/* Change D,N FOR VCLK */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
via_write_reg(VIASR, SR46, (clk & 0x00FF));
via_write_reg(VIASR, SR47, (clk & 0xFF00) >> 8);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_CN750:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
via_write_reg(VIASR, SR44, (clk & 0x0000FF));
via_write_reg(VIASR, SR45, (clk & 0x00FF00) >> 8);
via_write_reg(VIASR, SR46, (clk & 0xFF0000) >> 16);
break;
}
}
if (set_iga == IGA2) {
/* Change D,N FOR LCK */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
via_write_reg(VIASR, SR44, (clk & 0x00FF));
via_write_reg(VIASR, SR45, (clk & 0xFF00) >> 8);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_CN750:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
via_write_reg(VIASR, SR4A, (clk & 0x0000FF));
via_write_reg(VIASR, SR4B, (clk & 0x00FF00) >> 8);
via_write_reg(VIASR, SR4C, (clk & 0xFF0000) >> 16);
break;
}
}
/* H.W. Reset : OFF */
viafb_write_reg_mask(CR17, VIACR, 0x80, BIT7);
/* Reset PLL */
if (set_iga == IGA1) {
viafb_write_reg_mask(SR40, VIASR, 0x02, BIT1);
viafb_write_reg_mask(SR40, VIASR, 0x00, BIT1);
}
if (set_iga == IGA2) {
viafb_write_reg_mask(SR40, VIASR, 0x04, BIT2);
viafb_write_reg_mask(SR40, VIASR, 0x00, BIT2);
}
/* Fire! */
via_write_misc_reg_mask(0x0C, 0x0C); /* select external clock */
}
void viafb_load_crtc_timing(struct display_timing device_timing,
int set_iga)
{
int i;
int viafb_load_reg_num = 0;
int reg_value = 0;
struct io_register *reg = NULL;
viafb_unlock_crt();
for (i = 0; i < 12; i++) {
if (set_iga == IGA1) {
switch (i) {
case H_TOTAL_INDEX:
reg_value =
IGA1_HOR_TOTAL_FORMULA(device_timing.
hor_total);
viafb_load_reg_num =
iga1_crtc_reg.hor_total.reg_num;
reg = iga1_crtc_reg.hor_total.reg;
break;
case H_ADDR_INDEX:
reg_value =
IGA1_HOR_ADDR_FORMULA(device_timing.
hor_addr);
viafb_load_reg_num =
iga1_crtc_reg.hor_addr.reg_num;
reg = iga1_crtc_reg.hor_addr.reg;
break;
case H_BLANK_START_INDEX:
reg_value =
IGA1_HOR_BLANK_START_FORMULA
(device_timing.hor_blank_start);
viafb_load_reg_num =
iga1_crtc_reg.hor_blank_start.reg_num;
reg = iga1_crtc_reg.hor_blank_start.reg;
break;
case H_BLANK_END_INDEX:
reg_value =
IGA1_HOR_BLANK_END_FORMULA
(device_timing.hor_blank_start,
device_timing.hor_blank_end);
viafb_load_reg_num =
iga1_crtc_reg.hor_blank_end.reg_num;
reg = iga1_crtc_reg.hor_blank_end.reg;
break;
case H_SYNC_START_INDEX:
reg_value =
IGA1_HOR_SYNC_START_FORMULA
(device_timing.hor_sync_start);
viafb_load_reg_num =
iga1_crtc_reg.hor_sync_start.reg_num;
reg = iga1_crtc_reg.hor_sync_start.reg;
break;
case H_SYNC_END_INDEX:
reg_value =
IGA1_HOR_SYNC_END_FORMULA
(device_timing.hor_sync_start,
device_timing.hor_sync_end);
viafb_load_reg_num =
iga1_crtc_reg.hor_sync_end.reg_num;
reg = iga1_crtc_reg.hor_sync_end.reg;
break;
case V_TOTAL_INDEX:
reg_value =
IGA1_VER_TOTAL_FORMULA(device_timing.
ver_total);
viafb_load_reg_num =
iga1_crtc_reg.ver_total.reg_num;
reg = iga1_crtc_reg.ver_total.reg;
break;
case V_ADDR_INDEX:
reg_value =
IGA1_VER_ADDR_FORMULA(device_timing.
ver_addr);
viafb_load_reg_num =
iga1_crtc_reg.ver_addr.reg_num;
reg = iga1_crtc_reg.ver_addr.reg;
break;
case V_BLANK_START_INDEX:
reg_value =
IGA1_VER_BLANK_START_FORMULA
(device_timing.ver_blank_start);
viafb_load_reg_num =
iga1_crtc_reg.ver_blank_start.reg_num;
reg = iga1_crtc_reg.ver_blank_start.reg;
break;
case V_BLANK_END_INDEX:
reg_value =
IGA1_VER_BLANK_END_FORMULA
(device_timing.ver_blank_start,
device_timing.ver_blank_end);
viafb_load_reg_num =
iga1_crtc_reg.ver_blank_end.reg_num;
reg = iga1_crtc_reg.ver_blank_end.reg;
break;
case V_SYNC_START_INDEX:
reg_value =
IGA1_VER_SYNC_START_FORMULA
(device_timing.ver_sync_start);
viafb_load_reg_num =
iga1_crtc_reg.ver_sync_start.reg_num;
reg = iga1_crtc_reg.ver_sync_start.reg;
break;
case V_SYNC_END_INDEX:
reg_value =
IGA1_VER_SYNC_END_FORMULA
(device_timing.ver_sync_start,
device_timing.ver_sync_end);
viafb_load_reg_num =
iga1_crtc_reg.ver_sync_end.reg_num;
reg = iga1_crtc_reg.ver_sync_end.reg;
break;
}
}
if (set_iga == IGA2) {
switch (i) {
case H_TOTAL_INDEX:
reg_value =
IGA2_HOR_TOTAL_FORMULA(device_timing.
hor_total);
viafb_load_reg_num =
iga2_crtc_reg.hor_total.reg_num;
reg = iga2_crtc_reg.hor_total.reg;
break;
case H_ADDR_INDEX:
reg_value =
IGA2_HOR_ADDR_FORMULA(device_timing.
hor_addr);
viafb_load_reg_num =
iga2_crtc_reg.hor_addr.reg_num;
reg = iga2_crtc_reg.hor_addr.reg;
break;
case H_BLANK_START_INDEX:
reg_value =
IGA2_HOR_BLANK_START_FORMULA
(device_timing.hor_blank_start);
viafb_load_reg_num =
iga2_crtc_reg.hor_blank_start.reg_num;
reg = iga2_crtc_reg.hor_blank_start.reg;
break;
case H_BLANK_END_INDEX:
reg_value =
IGA2_HOR_BLANK_END_FORMULA
(device_timing.hor_blank_start,
device_timing.hor_blank_end);
viafb_load_reg_num =
iga2_crtc_reg.hor_blank_end.reg_num;
reg = iga2_crtc_reg.hor_blank_end.reg;
break;
case H_SYNC_START_INDEX:
reg_value =
IGA2_HOR_SYNC_START_FORMULA
(device_timing.hor_sync_start);
if (UNICHROME_CN700 <=
viaparinfo->chip_info->gfx_chip_name)
viafb_load_reg_num =
iga2_crtc_reg.hor_sync_start.
reg_num;
else
viafb_load_reg_num = 3;
reg = iga2_crtc_reg.hor_sync_start.reg;
break;
case H_SYNC_END_INDEX:
reg_value =
IGA2_HOR_SYNC_END_FORMULA
(device_timing.hor_sync_start,
device_timing.hor_sync_end);
viafb_load_reg_num =
iga2_crtc_reg.hor_sync_end.reg_num;
reg = iga2_crtc_reg.hor_sync_end.reg;
break;
case V_TOTAL_INDEX:
reg_value =
IGA2_VER_TOTAL_FORMULA(device_timing.
ver_total);
viafb_load_reg_num =
iga2_crtc_reg.ver_total.reg_num;
reg = iga2_crtc_reg.ver_total.reg;
break;
case V_ADDR_INDEX:
reg_value =
IGA2_VER_ADDR_FORMULA(device_timing.
ver_addr);
viafb_load_reg_num =
iga2_crtc_reg.ver_addr.reg_num;
reg = iga2_crtc_reg.ver_addr.reg;
break;
case V_BLANK_START_INDEX:
reg_value =
IGA2_VER_BLANK_START_FORMULA
(device_timing.ver_blank_start);
viafb_load_reg_num =
iga2_crtc_reg.ver_blank_start.reg_num;
reg = iga2_crtc_reg.ver_blank_start.reg;
break;
case V_BLANK_END_INDEX:
reg_value =
IGA2_VER_BLANK_END_FORMULA
(device_timing.ver_blank_start,
device_timing.ver_blank_end);
viafb_load_reg_num =
iga2_crtc_reg.ver_blank_end.reg_num;
reg = iga2_crtc_reg.ver_blank_end.reg;
break;
case V_SYNC_START_INDEX:
reg_value =
IGA2_VER_SYNC_START_FORMULA
(device_timing.ver_sync_start);
viafb_load_reg_num =
iga2_crtc_reg.ver_sync_start.reg_num;
reg = iga2_crtc_reg.ver_sync_start.reg;
break;
case V_SYNC_END_INDEX:
reg_value =
IGA2_VER_SYNC_END_FORMULA
(device_timing.ver_sync_start,
device_timing.ver_sync_end);
viafb_load_reg_num =
iga2_crtc_reg.ver_sync_end.reg_num;
reg = iga2_crtc_reg.ver_sync_end.reg;
break;
}
}
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
}
viafb_lock_crt();
}
void viafb_fill_crtc_timing(struct crt_mode_table *crt_table,
struct VideoModeTable *video_mode, int bpp_byte, int set_iga)
{
struct display_timing crt_reg;
int i;
int index = 0;
int h_addr, v_addr;
u32 pll_D_N, clock, refresh = viafb_refresh;
if (viafb_SAMM_ON && set_iga == IGA2)
refresh = viafb_refresh1;
for (i = 0; i < video_mode->mode_array; i++) {
index = i;
if (crt_table[i].refresh_rate == refresh)
break;
}
crt_reg = crt_table[index].crtc;
/* Mode 640x480 has border, but LCD/DFP didn't have border. */
/* So we would delete border. */
if ((viafb_LCD_ON | viafb_DVI_ON)
&& video_mode->crtc[0].crtc.hor_addr == 640
&& video_mode->crtc[0].crtc.ver_addr == 480
&& refresh == 60) {
/* The border is 8 pixels. */
crt_reg.hor_blank_start = crt_reg.hor_blank_start - 8;
/* Blanking time should add left and right borders. */
crt_reg.hor_blank_end = crt_reg.hor_blank_end + 16;
}
h_addr = crt_reg.hor_addr;
v_addr = crt_reg.ver_addr;
if (set_iga == IGA1) {
viafb_unlock_crt();
viafb_write_reg(CR09, VIACR, 0x00); /*initial CR09=0 */
viafb_write_reg_mask(CR11, VIACR, 0x00, BIT4 + BIT5 + BIT6);
viafb_write_reg_mask(CR17, VIACR, 0x00, BIT7);
}
switch (set_iga) {
case IGA1:
viafb_load_crtc_timing(crt_reg, IGA1);
break;
case IGA2:
viafb_load_crtc_timing(crt_reg, IGA2);
break;
}
load_fix_bit_crtc_reg();
viafb_lock_crt();
viafb_write_reg_mask(CR17, VIACR, 0x80, BIT7);
viafb_load_fetch_count_reg(h_addr, bpp_byte, set_iga);
/* load FIFO */
if ((viaparinfo->chip_info->gfx_chip_name != UNICHROME_CLE266)
&& (viaparinfo->chip_info->gfx_chip_name != UNICHROME_K400))
viafb_load_FIFO_reg(set_iga, h_addr, v_addr);
clock = crt_reg.hor_total * crt_reg.ver_total
* crt_table[index].refresh_rate;
pll_D_N = viafb_get_clk_value(clock);
DEBUG_MSG(KERN_INFO "PLL=%x", pll_D_N);
viafb_set_vclock(pll_D_N, set_iga);
}
void __devinit viafb_init_chip_info(int chip_type)
{
init_gfx_chip_info(chip_type);
init_tmds_chip_info();
init_lvds_chip_info();
viaparinfo->crt_setting_info->iga_path = IGA1;
/*Set IGA path for each device */
viafb_set_iga_path();
viaparinfo->lvds_setting_info->display_method = viafb_lcd_dsp_method;
viaparinfo->lvds_setting_info->lcd_mode = viafb_lcd_mode;
viaparinfo->lvds_setting_info2->display_method =
viaparinfo->lvds_setting_info->display_method;
viaparinfo->lvds_setting_info2->lcd_mode =
viaparinfo->lvds_setting_info->lcd_mode;
}
void viafb_update_device_setting(int hres, int vres, int bpp, int flag)
{
if (flag == 0) {
viaparinfo->tmds_setting_info->h_active = hres;
viaparinfo->tmds_setting_info->v_active = vres;
viaparinfo->lvds_setting_info->h_active = hres;
viaparinfo->lvds_setting_info->v_active = vres;
viaparinfo->lvds_setting_info->bpp = bpp;
viaparinfo->lvds_setting_info2->h_active = hres;
viaparinfo->lvds_setting_info2->v_active = vres;
viaparinfo->lvds_setting_info2->bpp = bpp;
} else {
if (viaparinfo->tmds_setting_info->iga_path == IGA2) {
viaparinfo->tmds_setting_info->h_active = hres;
viaparinfo->tmds_setting_info->v_active = vres;
}
if (viaparinfo->lvds_setting_info->iga_path == IGA2) {
viaparinfo->lvds_setting_info->h_active = hres;
viaparinfo->lvds_setting_info->v_active = vres;
viaparinfo->lvds_setting_info->bpp = bpp;
}
if (IGA2 == viaparinfo->lvds_setting_info2->iga_path) {
viaparinfo->lvds_setting_info2->h_active = hres;
viaparinfo->lvds_setting_info2->v_active = vres;
viaparinfo->lvds_setting_info2->bpp = bpp;
}
}
}
static void __devinit init_gfx_chip_info(int chip_type)
{
u8 tmp;
viaparinfo->chip_info->gfx_chip_name = chip_type;
/* Check revision of CLE266 Chip */
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
/* CR4F only define in CLE266.CX chip */
tmp = viafb_read_reg(VIACR, CR4F);
viafb_write_reg(CR4F, VIACR, 0x55);
if (viafb_read_reg(VIACR, CR4F) != 0x55)
viaparinfo->chip_info->gfx_chip_revision =
CLE266_REVISION_AX;
else
viaparinfo->chip_info->gfx_chip_revision =
CLE266_REVISION_CX;
/* restore orignal CR4F value */
viafb_write_reg(CR4F, VIACR, tmp);
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
tmp = viafb_read_reg(VIASR, SR43);
DEBUG_MSG(KERN_INFO "SR43:%X\n", tmp);
if (tmp & 0x02) {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700M2;
} else if (tmp & 0x40) {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700M;
} else {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700;
}
}
/* Determine which 2D engine we have */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_M1;
break;
case UNICHROME_K8M890:
case UNICHROME_P4M900:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H5;
break;
default:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H2;
break;
}
}
static void __devinit init_tmds_chip_info(void)
{
viafb_tmds_trasmitter_identify();
if (INTERFACE_NONE == viaparinfo->chip_info->tmds_chip_info.
output_interface) {
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CX700:
{
/* we should check support by hardware layout.*/
if ((viafb_display_hardware_layout ==
HW_LAYOUT_DVI_ONLY)
|| (viafb_display_hardware_layout ==
HW_LAYOUT_LCD_DVI)) {
viaparinfo->chip_info->tmds_chip_info.
output_interface = INTERFACE_TMDS;
} else {
viaparinfo->chip_info->tmds_chip_info.
output_interface =
INTERFACE_NONE;
}
break;
}
case UNICHROME_K8M890:
case UNICHROME_P4M900:
case UNICHROME_P4M890:
/* TMDS on PCIE, we set DFPLOW as default. */
viaparinfo->chip_info->tmds_chip_info.output_interface =
INTERFACE_DFP_LOW;
break;
default:
{
/* set DVP1 default for DVI */
viaparinfo->chip_info->tmds_chip_info
.output_interface = INTERFACE_DVP1;
}
}
}
DEBUG_MSG(KERN_INFO "TMDS Chip = %d\n",
viaparinfo->chip_info->tmds_chip_info.tmds_chip_name);
viafb_init_dvi_size(&viaparinfo->shared->chip_info.tmds_chip_info,
&viaparinfo->shared->tmds_setting_info);
}
static void __devinit init_lvds_chip_info(void)
{
viafb_lvds_trasmitter_identify();
viafb_init_lcd_size();
viafb_init_lvds_output_interface(&viaparinfo->chip_info->lvds_chip_info,
viaparinfo->lvds_setting_info);
if (viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name) {
viafb_init_lvds_output_interface(&viaparinfo->chip_info->
lvds_chip_info2, viaparinfo->lvds_setting_info2);
}
/*If CX700,two singel LCD, we need to reassign
LCD interface to different LVDS port */
if ((UNICHROME_CX700 == viaparinfo->chip_info->gfx_chip_name)
&& (HW_LAYOUT_LCD1_LCD2 == viafb_display_hardware_layout)) {
if ((INTEGRATED_LVDS == viaparinfo->chip_info->lvds_chip_info.
lvds_chip_name) && (INTEGRATED_LVDS ==
viaparinfo->chip_info->
lvds_chip_info2.lvds_chip_name)) {
viaparinfo->chip_info->lvds_chip_info.output_interface =
INTERFACE_LVDS0;
viaparinfo->chip_info->lvds_chip_info2.
output_interface =
INTERFACE_LVDS1;
}
}
DEBUG_MSG(KERN_INFO "LVDS Chip = %d\n",
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name);
DEBUG_MSG(KERN_INFO "LVDS1 output_interface = %d\n",
viaparinfo->chip_info->lvds_chip_info.output_interface);
DEBUG_MSG(KERN_INFO "LVDS2 output_interface = %d\n",
viaparinfo->chip_info->lvds_chip_info.output_interface);
}
void __devinit viafb_init_dac(int set_iga)
{
int i;
u8 tmp;
if (set_iga == IGA1) {
/* access Primary Display's LUT */
viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0);
/* turn off LCK */
viafb_write_reg_mask(SR1B, VIASR, 0x00, BIT7 + BIT6);
for (i = 0; i < 256; i++) {
write_dac_reg(i, palLUT_table[i].red,
palLUT_table[i].green,
palLUT_table[i].blue);
}
/* turn on LCK */
viafb_write_reg_mask(SR1B, VIASR, 0xC0, BIT7 + BIT6);
} else {
tmp = viafb_read_reg(VIACR, CR6A);
/* access Secondary Display's LUT */
viafb_write_reg_mask(CR6A, VIACR, 0x40, BIT6);
viafb_write_reg_mask(SR1A, VIASR, 0x01, BIT0);
for (i = 0; i < 256; i++) {
write_dac_reg(i, palLUT_table[i].red,
palLUT_table[i].green,
palLUT_table[i].blue);
}
/* set IGA1 DAC for default */
viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0);
viafb_write_reg(CR6A, VIACR, tmp);
}
}
static void device_screen_off(void)
{
/* turn off CRT screen (IGA1) */
viafb_write_reg_mask(SR01, VIASR, 0x20, BIT5);
}
static void device_screen_on(void)
{
/* turn on CRT screen (IGA1) */
viafb_write_reg_mask(SR01, VIASR, 0x00, BIT5);
}
static void set_display_channel(void)
{
/*If viafb_LCD2_ON, on cx700, internal lvds's information
is keeped on lvds_setting_info2 */
if (viafb_LCD2_ON &&
viaparinfo->lvds_setting_info2->device_lcd_dualedge) {
/* For dual channel LCD: */
/* Set to Dual LVDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5);
} else if (viafb_LCD_ON && viafb_DVI_ON) {
/* For LCD+DFP: */
/* Set to LVDS1 + TMDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x10, BIT4 + BIT5);
} else if (viafb_DVI_ON) {
/* Set to single TMDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x30, BIT4 + BIT5);
} else if (viafb_LCD_ON) {
if (viaparinfo->lvds_setting_info->device_lcd_dualedge) {
/* For dual channel LCD: */
/* Set to Dual LVDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5);
} else {
/* Set to LVDS0 + LVDS1 channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x00, BIT4 + BIT5);
}
}
}
static u8 get_sync(struct fb_info *info)
{
u8 polarity = 0;
if (!(info->var.sync & FB_SYNC_HOR_HIGH_ACT))
polarity |= VIA_HSYNC_NEGATIVE;
if (!(info->var.sync & FB_SYNC_VERT_HIGH_ACT))
polarity |= VIA_VSYNC_NEGATIVE;
return polarity;
}
int viafb_setmode(struct VideoModeTable *vmode_tbl, int video_bpp,
struct VideoModeTable *vmode_tbl1, int video_bpp1)
{
int i, j;
int port;
u32 devices = viaparinfo->shared->iga1_devices
| viaparinfo->shared->iga2_devices;
u8 value, index, mask;
struct crt_mode_table *crt_timing;
struct crt_mode_table *crt_timing1 = NULL;
device_screen_off();
crt_timing = vmode_tbl->crtc;
if (viafb_SAMM_ON == 1) {
crt_timing1 = vmode_tbl1->crtc;
}
inb(VIAStatus);
outb(0x00, VIAAR);
/* Write Common Setting for Video Mode */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
viafb_write_regx(CLE266_ModeXregs, NUM_TOTAL_CLE266_ModeXregs);
break;
case UNICHROME_K400:
viafb_write_regx(KM400_ModeXregs, NUM_TOTAL_KM400_ModeXregs);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
viafb_write_regx(CN400_ModeXregs, NUM_TOTAL_CN400_ModeXregs);
break;
case UNICHROME_CN700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
viafb_write_regx(CN700_ModeXregs, NUM_TOTAL_CN700_ModeXregs);
break;
case UNICHROME_CX700:
case UNICHROME_VX800:
viafb_write_regx(CX700_ModeXregs, NUM_TOTAL_CX700_ModeXregs);
break;
case UNICHROME_VX855:
case UNICHROME_VX900:
viafb_write_regx(VX855_ModeXregs, NUM_TOTAL_VX855_ModeXregs);
break;
}
viafb_write_regx(scaling_parameters, ARRAY_SIZE(scaling_parameters));
device_off();
via_set_state(devices, VIA_STATE_OFF);
/* Fill VPIT Parameters */
/* Write Misc Register */
outb(VPIT.Misc, VIA_MISC_REG_WRITE);
/* Write Sequencer */
for (i = 1; i <= StdSR; i++)
via_write_reg(VIASR, i, VPIT.SR[i - 1]);
viafb_write_reg_mask(0x15, VIASR, 0xA2, 0xA2);
/* Write CRTC */
viafb_fill_crtc_timing(crt_timing, vmode_tbl, video_bpp / 8, IGA1);
/* Write Graphic Controller */
for (i = 0; i < StdGR; i++)
via_write_reg(VIAGR, i, VPIT.GR[i]);
/* Write Attribute Controller */
for (i = 0; i < StdAR; i++) {
inb(VIAStatus);
outb(i, VIAAR);
outb(VPIT.AR[i], VIAAR);
}
inb(VIAStatus);
outb(0x20, VIAAR);
/* Update Patch Register */
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266
|| viaparinfo->chip_info->gfx_chip_name == UNICHROME_K400)
&& vmode_tbl->crtc[0].crtc.hor_addr == 1024
&& vmode_tbl->crtc[0].crtc.ver_addr == 768) {
for (j = 0; j < res_patch_table[0].table_length; j++) {
index = res_patch_table[0].io_reg_table[j].index;
port = res_patch_table[0].io_reg_table[j].port;
value = res_patch_table[0].io_reg_table[j].value;
mask = res_patch_table[0].io_reg_table[j].mask;
viafb_write_reg_mask(index, port, value, mask);
}
}
via_set_primary_pitch(viafbinfo->fix.line_length);
via_set_secondary_pitch(viafb_dual_fb ? viafbinfo1->fix.line_length
: viafbinfo->fix.line_length);
via_set_primary_color_depth(viaparinfo->depth);
via_set_secondary_color_depth(viafb_dual_fb ? viaparinfo1->depth
: viaparinfo->depth);
via_set_source(viaparinfo->shared->iga1_devices, IGA1);
via_set_source(viaparinfo->shared->iga2_devices, IGA2);
if (viaparinfo->shared->iga2_devices)
enable_second_display_channel();
else
disable_second_display_channel();
/* Update Refresh Rate Setting */
/* Clear On Screen */
/* CRT set mode */
if (viafb_CRT_ON) {
if (viafb_SAMM_ON && (viaparinfo->crt_setting_info->iga_path ==
IGA2)) {
viafb_fill_crtc_timing(crt_timing1, vmode_tbl1,
video_bpp1 / 8,
viaparinfo->crt_setting_info->iga_path);
} else {
viafb_fill_crtc_timing(crt_timing, vmode_tbl,
video_bpp / 8,
viaparinfo->crt_setting_info->iga_path);
}
/* Patch if set_hres is not 8 alignment (1366) to viafb_setmode
to 8 alignment (1368),there is several pixels (2 pixels)
on right side of screen. */
if (vmode_tbl->crtc[0].crtc.hor_addr % 8) {
viafb_unlock_crt();
viafb_write_reg(CR02, VIACR,
viafb_read_reg(VIACR, CR02) - 1);
viafb_lock_crt();
}
}
if (viafb_DVI_ON) {
if (viafb_SAMM_ON &&
(viaparinfo->tmds_setting_info->iga_path == IGA2)) {
viafb_dvi_set_mode(viafb_get_mode
(viaparinfo->tmds_setting_info->h_active,
viaparinfo->tmds_setting_info->
v_active),
video_bpp1, viaparinfo->
tmds_setting_info->iga_path);
} else {
viafb_dvi_set_mode(viafb_get_mode
(viaparinfo->tmds_setting_info->h_active,
viaparinfo->
tmds_setting_info->v_active),
video_bpp, viaparinfo->
tmds_setting_info->iga_path);
}
}
if (viafb_LCD_ON) {
if (viafb_SAMM_ON &&
(viaparinfo->lvds_setting_info->iga_path == IGA2)) {
viaparinfo->lvds_setting_info->bpp = video_bpp1;
viafb_lcd_set_mode(crt_timing1, viaparinfo->
lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
} else {
/* IGA1 doesn't have LCD scaling, so set it center. */
if (viaparinfo->lvds_setting_info->iga_path == IGA1) {
viaparinfo->lvds_setting_info->display_method =
LCD_CENTERING;
}
viaparinfo->lvds_setting_info->bpp = video_bpp;
viafb_lcd_set_mode(crt_timing, viaparinfo->
lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
}
}
if (viafb_LCD2_ON) {
if (viafb_SAMM_ON &&
(viaparinfo->lvds_setting_info2->iga_path == IGA2)) {
viaparinfo->lvds_setting_info2->bpp = video_bpp1;
viafb_lcd_set_mode(crt_timing1, viaparinfo->
lvds_setting_info2,
&viaparinfo->chip_info->lvds_chip_info2);
} else {
/* IGA1 doesn't have LCD scaling, so set it center. */
if (viaparinfo->lvds_setting_info2->iga_path == IGA1) {
viaparinfo->lvds_setting_info2->display_method =
LCD_CENTERING;
}
viaparinfo->lvds_setting_info2->bpp = video_bpp;
viafb_lcd_set_mode(crt_timing, viaparinfo->
lvds_setting_info2,
&viaparinfo->chip_info->lvds_chip_info2);
}
}
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700)
&& (viafb_LCD_ON || viafb_DVI_ON))
set_display_channel();
/* If set mode normally, save resolution information for hot-plug . */
if (!viafb_hotplug) {
viafb_hotplug_Xres = vmode_tbl->crtc[0].crtc.hor_addr;
viafb_hotplug_Yres = vmode_tbl->crtc[0].crtc.ver_addr;
viafb_hotplug_bpp = video_bpp;
viafb_hotplug_refresh = viafb_refresh;
if (viafb_DVI_ON)
viafb_DeviceStatus = DVI_Device;
else
viafb_DeviceStatus = CRT_Device;
}
device_on();
if (!viafb_dual_fb)
via_set_sync_polarity(devices, get_sync(viafbinfo));
else {
via_set_sync_polarity(viaparinfo->shared->iga1_devices,
get_sync(viafbinfo));
via_set_sync_polarity(viaparinfo->shared->iga2_devices,
get_sync(viafbinfo1));
}
via_set_state(devices, VIA_STATE_ON);
device_screen_on();
return 1;
}
int viafb_get_pixclock(int hres, int vres, int vmode_refresh)
{
int i;
struct crt_mode_table *best;
struct VideoModeTable *vmode = viafb_get_mode(hres, vres);
if (!vmode)
return RES_640X480_60HZ_PIXCLOCK;
best = &vmode->crtc[0];
for (i = 1; i < vmode->mode_array; i++) {
if (abs(vmode->crtc[i].refresh_rate - vmode_refresh)
< abs(best->refresh_rate - vmode_refresh))
best = &vmode->crtc[i];
}
return 1000000000 / (best->crtc.hor_total * best->crtc.ver_total)
* 1000 / best->refresh_rate;
}
int viafb_get_refresh(int hres, int vres, u32 long_refresh)
{
int i;
struct crt_mode_table *best;
struct VideoModeTable *vmode = viafb_get_mode(hres, vres);
if (!vmode)
return 60;
best = &vmode->crtc[0];
for (i = 1; i < vmode->mode_array; i++) {
if (abs(vmode->crtc[i].refresh_rate - long_refresh)
< abs(best->refresh_rate - long_refresh))
best = &vmode->crtc[i];
}
if (abs(best->refresh_rate - long_refresh) > 3)
return 60;
return best->refresh_rate;
}
static void device_off(void)
{
viafb_dvi_disable();
viafb_lcd_disable();
}
static void device_on(void)
{
if (viafb_DVI_ON == 1)
viafb_dvi_enable();
if (viafb_LCD_ON == 1)
viafb_lcd_enable();
}
static void enable_second_display_channel(void)
{
/* to enable second display channel. */
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6);
viafb_write_reg_mask(CR6A, VIACR, BIT7, BIT7);
viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6);
}
static void disable_second_display_channel(void)
{
/* to disable second display channel. */
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6);
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT7);
viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6);
}
void viafb_set_dpa_gfx(int output_interface, struct GFX_DPA_SETTING\
*p_gfx_dpa_setting)
{
switch (output_interface) {
case INTERFACE_DVP0:
{
/* DVP0 Clock Polarity and Adjust: */
viafb_write_reg_mask(CR96, VIACR,
p_gfx_dpa_setting->DVP0, 0x0F);
/* DVP0 Clock and Data Pads Driving: */
viafb_write_reg_mask(SR1E, VIASR,
p_gfx_dpa_setting->DVP0ClockDri_S, BIT2);
viafb_write_reg_mask(SR2A, VIASR,
p_gfx_dpa_setting->DVP0ClockDri_S1,
BIT4);
viafb_write_reg_mask(SR1B, VIASR,
p_gfx_dpa_setting->DVP0DataDri_S, BIT1);
viafb_write_reg_mask(SR2A, VIASR,
p_gfx_dpa_setting->DVP0DataDri_S1, BIT5);
break;
}
case INTERFACE_DVP1:
{
/* DVP1 Clock Polarity and Adjust: */
viafb_write_reg_mask(CR9B, VIACR,
p_gfx_dpa_setting->DVP1, 0x0F);
/* DVP1 Clock and Data Pads Driving: */
viafb_write_reg_mask(SR65, VIASR,
p_gfx_dpa_setting->DVP1Driving, 0x0F);
break;
}
case INTERFACE_DFP_HIGH:
{
viafb_write_reg_mask(CR97, VIACR,
p_gfx_dpa_setting->DFPHigh, 0x0F);
break;
}
case INTERFACE_DFP_LOW:
{
viafb_write_reg_mask(CR99, VIACR,
p_gfx_dpa_setting->DFPLow, 0x0F);
break;
}
case INTERFACE_DFP:
{
viafb_write_reg_mask(CR97, VIACR,
p_gfx_dpa_setting->DFPHigh, 0x0F);
viafb_write_reg_mask(CR99, VIACR,
p_gfx_dpa_setting->DFPLow, 0x0F);
break;
}
}
}
/*According var's xres, yres fill var's other timing information*/
void viafb_fill_var_timing_info(struct fb_var_screeninfo *var, int refresh,
struct VideoModeTable *vmode_tbl)
{
struct crt_mode_table *crt_timing = NULL;
struct display_timing crt_reg;
int i = 0, index = 0;
crt_timing = vmode_tbl->crtc;
for (i = 0; i < vmode_tbl->mode_array; i++) {
index = i;
if (crt_timing[i].refresh_rate == refresh)
break;
}
crt_reg = crt_timing[index].crtc;
var->pixclock = viafb_get_pixclock(var->xres, var->yres, refresh);
var->left_margin =
crt_reg.hor_total - (crt_reg.hor_sync_start + crt_reg.hor_sync_end);
var->right_margin = crt_reg.hor_sync_start - crt_reg.hor_addr;
var->hsync_len = crt_reg.hor_sync_end;
var->upper_margin =
crt_reg.ver_total - (crt_reg.ver_sync_start + crt_reg.ver_sync_end);
var->lower_margin = crt_reg.ver_sync_start - crt_reg.ver_addr;
var->vsync_len = crt_reg.ver_sync_end;
var->sync = 0;
if (crt_timing[index].h_sync_polarity == POSITIVE)
var->sync |= FB_SYNC_HOR_HIGH_ACT;
if (crt_timing[index].v_sync_polarity == POSITIVE)
var->sync |= FB_SYNC_VERT_HIGH_ACT;
}
|
chaoling/test123
|
linux-2.6.39/drivers/video/via/hw.c
|
C
|
gpl-2.0
| 73,941
|
/*==================================================
Copyright (c) 2013-2015 司徒正美 and other contributors
http://www.cnblogs.com/rubylouvre/
https://github.com/RubyLouvre
http://weibo.com/jslouvre/
Released under the MIT license
avalon.modern.shim.js(无加载器版本) 1.44 built in 2015.6.17
support IE10+ and other browsers
==================================================*/
(function(global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get avalon.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var avalon = require("avalon")(window);
module.exports = global.document ? factory(global, true) : function(w) {
if (!w.document) {
throw new Error("Avalon requires a window with a document")
}
return factory(w)
}
} else {
factory(global)
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function(window, noGlobal){
/*********************************************************************
* 全局变量及方法 *
**********************************************************************/
var expose = Date.now()
//http://stackoverflow.com/questions/7290086/javascript-use-strict-and-nicks-find-global-function
var DOC = window.document
var head = DOC.head //HEAD元素
head.insertAdjacentHTML("afterBegin", '<avalon ms-skip class="avalonHide"><style id="avalonStyle">.avalonHide{ display: none!important }</style></avalon>')
var ifGroup = head.firstChild
function log() {
if (avalon.config.debug) {
// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
console.log.apply(console, arguments)
}
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*/
function createMap() {
return Object.create(null)
}
var subscribers = "$" + expose
var otherRequire = window.require
var otherDefine = window.define
var innerRequire
var stopRepeatAssign = false
var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
var rcomplexType = /^(?:object|array)$/
var rsvg = /^\[object SVG\w*Element\]$/
var rwindow = /^\[object (?:Window|DOMWindow|global)\]$/
var oproto = Object.prototype
var ohasOwn = oproto.hasOwnProperty
var serialize = oproto.toString
var ap = Array.prototype
var aslice = ap.slice
var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
var W3C = window.dispatchEvent
var root = DOC.documentElement
var avalonFragment = DOC.createDocumentFragment()
var cinerator = DOC.createElement("div")
var class2type = {}
"Boolean Number String Function Array Date RegExp Object Error".replace(rword, function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
function noop() {
}
function oneObject(array, val) {
if (typeof array === "string") {
array = array.match(rword) || []
}
var result = {},
value = val !== void 0 ? val : 1
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value
}
return result
}
//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
var generateID = function(prefix) {
prefix = prefix || "avalon"
return String(Math.random() + Math.random()).replace(/\d\.\d{4}/, prefix)
}
function IE() {
if (window.VBArray) {
var mode = document.documentMode
return mode ? mode : window.XMLHttpRequest ? 7 : 6
} else {
return 0
}
}
var IEVersion = IE()
avalon = function(el) { //创建jQuery式的无new 实例化结构
return new avalon.init(el)
}
/*视浏览器情况采用最快的异步回调*/
avalon.nextTick = new function() {// jshint ignore:line
var tickImmediate = window.setImmediate
var tickObserver = window.MutationObserver
var tickPost = W3C && window.postMessage
if (tickImmediate) {
return tickImmediate.bind(window)
}
var queue = []
function callback() {
var n = queue.length
for (var i = 0; i < n; i++) {
queue[i]()
}
queue = queue.slice(n)
}
if (tickObserver) {
var node = document.createTextNode("avalon")
new tickObserver(callback).observe(node, {characterData: true})// jshint ignore:line
return function(fn) {
queue.push(fn)
node.data = Math.random()
}
}
if (tickPost) {
window.addEventListener("message", function(e) {
var source = e.source
if ((source === window || source === null) && e.data === "process-tick") {
e.stopPropagation()
callback()
}
})
return function(fn) {
queue.push(fn)
window.postMessage('process-tick', '*')
}
}
return function(fn) {
setTimeout(fn, 0)
}
}// jshint ignore:line
/*********************************************************************
* avalon的静态方法定义区 *
**********************************************************************/
avalon.init = function(el) {
this[0] = this.element = el
}
avalon.fn = avalon.prototype = avalon.init.prototype
avalon.type = function(obj) { //取得目标的类型
if (obj == null) {
return String(obj)
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === "object" || typeof obj === "function" ?
class2type[serialize.call(obj)] || "object" :
typeof obj
}
var isFunction = function(fn) {
return serialize.call(fn) === "[object Function]"
}
avalon.isFunction = isFunction
avalon.isWindow = function(obj) {
return rwindow.test(serialize.call(obj))
}
/*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
avalon.isPlainObject = function(obj) {
// 简单的 typeof obj === "object"检测,会致使用isPlainObject(window)在opera下通不过
return serialize.call(obj) === "[object Object]" && Object.getPrototypeOf(obj) === oproto
}
//与jQuery.extend方法,可用于浅拷贝,深拷贝
avalon.mix = avalon.fn.mix = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false
// 如果第一个参数为布尔,判定是否深拷贝
if (typeof target === "boolean") {
deep = target
target = arguments[1] || {}
i++
}
//确保接受方为一个复杂的数据类型
if (typeof target !== "object" && !isFunction(target)) {
target = {}
}
//如果只有一个参数,那么新成员添加于mix所在的对象上
if (i === length) {
target = this
i--
}
for (; i < length; i++) {
//只处理非空参数
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name]
copy = options[name]
// 防止环引用
if (target === copy) {
continue
}
if (deep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && Array.isArray(src) ? src : []
} else {
clone = src && avalon.isPlainObject(src) ? src : {}
}
target[name] = avalon.mix(deep, clone, copy)
} else if (copy !== void 0) {
target[name] = copy
}
}
}
}
return target
}
function _number(a, len) { //用于模拟slice, splice的效果
a = Math.floor(a) || 0
return a < 0 ? Math.max(len + a, 0) : Math.min(a, len);
}
avalon.mix({
rword: rword,
subscribers: subscribers,
version: 1.44,
ui: {},
log: log,
slice: function(nodes, start, end) {
return aslice.call(nodes, start, end)
},
noop: noop,
/*如果不用Error对象封装一下,str在控制台下可能会乱码*/
error: function(str, e) {
throw new (e || Error)(str)// jshint ignore:line
},
/*将一个以空格或逗号隔开的字符串或数组,转换成一个键值都为1的对象*/
oneObject: oneObject,
/* avalon.range(10)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
avalon.range(1, 11)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
avalon.range(0, 30, 5)
=> [0, 5, 10, 15, 20, 25]
avalon.range(0, -10, -1)
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
avalon.range(0)
=> []*/
range: function(start, end, step) { // 用于生成整数数组
step || (step = 1)
if (end == null) {
end = start || 0
start = 0
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = new Array(length)
while (++index < length) {
result[index] = start
start += step
}
return result
},
eventHooks: {},
/*绑定事件*/
bind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, type, fn, phase)
}
}
if (!fn.unbind)
el.addEventListener(type, fn, !!phase)
return fn
},
/*卸载事件*/
unbind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
var callback = fn || noop
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, type, fn, false)
}
}
el.removeEventListener(type, callback, !!phase)
},
/*读写删除元素节点的样式*/
css: function(node, name, value) {
if (node instanceof avalon) {
node = node[0]
}
var prop = /[_-]/.test(name) ? camelize(name) : name, fn
name = avalon.cssName(prop) || prop
if (value === void 0 || typeof value === "boolean") { //获取样式
fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
if (name === "background") {
name = "backgroundColor"
}
var val = fn(node, name)
return value === true ? parseFloat(val) || 0 : val
} else if (value === "") { //请除样式
node.style[name] = ""
} else { //设置样式
if (value == null || value !== value) {
return
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += "px"
}
fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
fn(node, name, value)
}
},
/*遍历数组与对象,回调的第一个参数为索引或键名,第二个或元素或键值*/
each: function(obj, fn) {
if (obj) { //排除null, undefined
var i = 0
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
if (fn(i, obj[i]) === false)
break
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i) && fn(i, obj[i]) === false) {
break
}
}
}
}
},
//收集元素的data-{{prefix}}-*属性,并转换为对象
getWidgetData: function(elem, prefix) {
var raw = avalon(elem).data()
var result = {}
for (var i in raw) {
if (i.indexOf(prefix) === 0) {
result[i.replace(prefix, "").replace(/\w/, function(a) {
return a.toLowerCase()
})] = raw[i]
}
}
return result
},
Array: {
/*只有当前数组不存在此元素时只添加它*/
ensure: function(target, item) {
if (target.indexOf(item) === -1) {
return target.push(item)
}
},
/*移除数组中指定位置的元素,返回布尔表示成功与否*/
removeAt: function(target, index) {
return !!target.splice(index, 1).length
},
/*移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否*/
remove: function(target, item) {
var index = target.indexOf(item)
if (~index)
return avalon.Array.removeAt(target, index)
return false
}
}
})
var bindingHandlers = avalon.bindingHandlers = {}
var bindingExecutors = avalon.bindingExecutors = {}
/*判定是否类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
function isArrayLike(obj) {
if (obj && typeof obj === "object") {
var n = obj.length,
str = serialize.call(obj)
if (/(Array|List|Collection|Map|Arguments)\]$/.test(str)) {
return true
} else if (str === "[object Object]" && n === (n >>> 0)) {
return true //由于ecma262v5能修改对象属性的enumerable,因此不能用propertyIsEnumerable来判定了
}
}
return false
}
// https://github.com/rsms/js-lru
var Cache = new function() {// jshint ignore:line
function LRU(maxLength) {
this.size = 0
this.limit = maxLength
this.head = this.tail = void 0
this._keymap = {}
}
var p = LRU.prototype
p.put = function(key, value) {
var entry = {
key: key,
value: value
}
this._keymap[key] = entry
if (this.tail) {
this.tail.newer = entry
entry.older = this.tail
} else {
this.head = entry
}
this.tail = entry
if (this.size === this.limit) {
this.shift()
} else {
this.size++
}
return value
}
p.shift = function() {
var entry = this.head
if (entry) {
this.head = this.head.newer
this.head.older =
entry.newer =
entry.older =
this._keymap[entry.key] = void 0
}
}
p.get = function(key) {
var entry = this._keymap[key]
if (entry === void 0)
return
if (entry === this.tail) {
return entry.value
}
// HEAD--------------TAIL
// <.older .newer>
// <--- add direction --
// A B C <D> E
if (entry.newer) {
if (entry === this.head) {
this.head = entry.newer
}
entry.newer.older = entry.older // C <-- E.
}
if (entry.older) {
entry.older.newer = entry.newer // C. --> E
}
entry.newer = void 0 // D --x
entry.older = this.tail // D. --> E
if (this.tail) {
this.tail.newer = entry // E. <-- D
}
this.tail = entry
return entry.value
}
return LRU
}// jshint ignore:line
/*********************************************************************
* DOM 底层补丁 *
**********************************************************************/
//safari5+是把contains方法放在Element.prototype上而不是Node.prototype
if (!DOC.contains) {
Node.prototype.contains = function (arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
avalon.contains = function (root, el) {
try {
while ((el = el.parentNode))
if (el === root)
return true
return false
} catch (e) {
return false
}
}
if (window.SVGElement) {
var svgns = "http://www.w3.org/2000/svg"
var svg = DOC.createElementNS(svgns, "svg")
svg.innerHTML = '<circle cx="50" cy="50" r="40" fill="red" />'
if (!rsvg.test(svg.firstChild)) {// #409
/* jshint ignore:start */
function enumerateNode(node, targetNode) {
if (node && node.childNodes) {
var nodes = node.childNodes
for (var i = 0, el; el = nodes[i++]; ) {
if (el.tagName) {
var svg = DOC.createElementNS(svgns,
el.tagName.toLowerCase())
// copy attrs
ap.forEach.call(el.attributes, function (attr) {
svg.setAttribute(attr.name, attr.value)
})
// 递归处理子节点
enumerateNode(el, svg)
targetNode.appendChild(svg)
}
}
}
}
/* jshint ignore:end */
Object.defineProperties(SVGElement.prototype, {
"outerHTML": {//IE9-11,firefox不支持SVG元素的innerHTML,outerHTML属性
enumerable: true,
configurable: true,
get: function () {
return new XMLSerializer().serializeToString(this)
},
set: function (html) {
var tagName = this.tagName.toLowerCase(),
par = this.parentNode,
frag = avalon.parseHTML(html)
// 操作的svg,直接插入
if (tagName === "svg") {
par.insertBefore(frag, this)
// svg节点的子节点类似
} else {
var newFrag = DOC.createDocumentFragment()
enumerateNode(frag, newFrag)
par.insertBefore(newFrag, this)
}
par.removeChild(this)
}
},
"innerHTML": {
enumerable: true,
configurable: true,
get: function () {
var s = this.outerHTML
var ropen = new RegExp("<" + this.nodeName + '\\b(?:(["\'])[^"]*?(\\1)|[^>])*>', "i")
var rclose = new RegExp("<\/" + this.nodeName + ">$", "i")
return s.replace(ropen, "").replace(rclose, "")
},
set: function (html) {
if (avalon.clearHTML) {
avalon.clearHTML(this)
var frag = avalon.parseHTML(html)
enumerateNode(frag, this)
}
}
}
})
}
}
//========================= event binding ====================
var eventHooks = avalon.eventHooks
//针对firefox, chrome修正mouseenter, mouseleave(chrome30+)
if (!("onmouseenter" in root)) {
avalon.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function (origType, fixType) {
eventHooks[origType] = {
type: fixType,
deel: function (elem, _, fn) {
return function (e) {
var t = e.relatedTarget
if (!t || (t !== elem && !(elem.compareDocumentPosition(t) & 16))) {
delete e.type
e.type = origType
return fn.call(elem, e)
}
}
}
}
})
}
//针对IE9+, w3c修正animationend
avalon.each({
AnimationEvent: "animationend",
WebKitAnimationEvent: "webkitAnimationEnd"
}, function (construct, fixType) {
if (window[construct] && !eventHooks.animationend) {
eventHooks.animationend = {
type: fixType
}
}
})
if (DOC.onmousewheel === void 0) {
/* IE6-11 chrome mousewheel wheelDetla 下 -120 上 120
firefox DOMMouseScroll detail 下3 上-3
firefox wheel detlaY 下3 上-3
IE9-11 wheel deltaY 下40 上-40
chrome wheel deltaY 下100 上-100 */
eventHooks.mousewheel = {
type: "wheel",
deel: function (elem, _, fn) {
return function (e) {
e.wheelDeltaY = e.wheelDelta = e.deltaY > 0 ? -120 : 120
e.wheelDeltaX = 0
Object.defineProperty(e, "type", {
value: "mousewheel"
})
fn.call(elem, e)
}
}
}
}
/*********************************************************************
* 配置系统 *
**********************************************************************/
function kernel(settings) {
for (var p in settings) {
if (!ohasOwn.call(settings, p))
continue
var val = settings[p]
if (typeof kernel.plugins[p] === "function") {
kernel.plugins[p](val)
} else if (typeof kernel[p] === "object") {
avalon.mix(kernel[p], val)
} else {
kernel[p] = val
}
}
return this
}
var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
function escapeRegExp(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return (target + "").replace(rregexp, "\\$&")
}
var plugins = {
loader: function (builtin) {
var flag = innerRequire && builtin
window.require = flag ? innerRequire : otherRequire
window.define = flag ? innerRequire.define : otherDefine
},
interpolate: function (array) {
openTag = array[0]
closeTag = array[1]
if (openTag === closeTag) {
throw new SyntaxError("openTag!==closeTag")
} else if (array + "" === "<!--,-->") {
kernel.commentInterpolate = true
} else {
var test = openTag + "test" + closeTag
cinerator.innerHTML = test
if (cinerator.innerHTML !== test && cinerator.innerHTML.indexOf("<") > -1) {
throw new SyntaxError("此定界符不合法")
}
cinerator.innerHTML = ""
}
var o = escapeRegExp(openTag),
c = escapeRegExp(closeTag)
rexpr = new RegExp(o + "(.*?)" + c)
rexprg = new RegExp(o + "(.*?)" + c, "g")
rbind = new RegExp(o + ".*?" + c + "|\\sms-")
}
}
kernel.debug = true
kernel.plugins = plugins
kernel.plugins['interpolate'](["{{", "}}"])
kernel.paths = {}
kernel.shim = {}
kernel.maxRepeatSize = 100
avalon.config = kernel
var ravalon = /(\w+)\[(avalonctrl)="(\S+)"\]/
var findNodes = function(str) {
return DOC.querySelectorAll(str)
}
/*********************************************************************
* 事件总线 *
**********************************************************************/
var EventBus = {
$watch: function (type, callback) {
if (typeof callback === "function") {
var callbacks = this.$events[type]
if (callbacks) {
callbacks.push(callback)
} else {
this.$events[type] = [callback]
}
} else { //重新开始监听此VM的第一重简单属性的变动
this.$events = this.$watch.backup
}
return this
},
$unwatch: function (type, callback) {
var n = arguments.length
if (n === 0) { //让此VM的所有$watch回调无效化
this.$watch.backup = this.$events
this.$events = {}
} else if (n === 1) {
this.$events[type] = []
} else {
var callbacks = this.$events[type] || []
var i = callbacks.length
while (~--i < 0) {
if (callbacks[i] === callback) {
return callbacks.splice(i, 1)
}
}
}
return this
},
$fire: function (type) {
var special, i, v, callback
if (/^(\w+)!(\S+)$/.test(type)) {
special = RegExp.$1
type = RegExp.$2
}
var events = this.$events
if (!events)
return
var args = aslice.call(arguments, 1)
var detail = [type].concat(args)
if (special === "all") {
for (i in avalon.vmodels) {
v = avalon.vmodels[i]
if (v !== this) {
v.$fire.apply(v, detail)
}
}
} else if (special === "up" || special === "down") {
var elements = events.expr ? findNodes(events.expr) : []
if (elements.length === 0)
return
for (i in avalon.vmodels) {
v = avalon.vmodels[i]
if (v !== this) {
if (v.$events.expr) {
var eventNodes = findNodes(v.$events.expr)
if (eventNodes.length === 0) {
continue
}
//循环两个vmodel中的节点,查找匹配(向上匹配或者向下匹配)的节点并设置标识
/* jshint ignore:start */
ap.forEach.call(eventNodes, function (node) {
ap.forEach.call(elements, function (element) {
var ok = special === "down" ? element.contains(node) : //向下捕获
node.contains(element) //向上冒泡
if (ok) {
node._avalon = v //符合条件的加一个标识
}
});
})
/* jshint ignore:end */
}
}
}
var nodes = DOC.getElementsByTagName("*") //实现节点排序
var alls = []
ap.forEach.call(nodes, function (el) {
if (el._avalon) {
alls.push(el._avalon)
el._avalon = ""
el.removeAttribute("_avalon")
}
})
if (special === "up") {
alls.reverse()
}
for (i = 0; callback = alls[i++]; ) {
if (callback.$fire.apply(callback, detail) === false) {
break
}
}
} else {
var callbacks = events[type] || []
var all = events.$all || []
for (i = 0; callback = callbacks[i++]; ) {
if (isFunction(callback))
callback.apply(this, args)
}
for (i = 0; callback = all[i++]; ) {
if (isFunction(callback))
callback.apply(this, arguments)
}
}
}
}
/*********************************************************************
* modelFactory *
**********************************************************************/
//avalon最核心的方法的两个方法之一(另一个是avalon.scan),返回一个ViewModel(VM)
var VMODELS = avalon.vmodels = {} //所有vmodel都储存在这里
avalon.define = function (id, factory) {
var $id = id.$id || id
if (!$id) {
log("warning: vm必须指定$id")
}
if (VMODELS[$id]) {
log("warning: " + $id + " 已经存在于avalon.vmodels中")
}
if (typeof id === "object") {
var model = modelFactory(id)
} else {
var scope = {
$watch: noop
}
factory(scope) //得到所有定义
model = modelFactory(scope) //偷天换日,将scope换为model
stopRepeatAssign = true
factory(model)
stopRepeatAssign = false
}
model.$id = $id
return VMODELS[$id] = model
}
//一些不需要被监听的属性
var $$skipArray = String("$id,$watch,$unwatch,$fire,$events,$model,$skipArray,$proxy").match(rword)
function modelFactory(source, $special, $model) {
if (Array.isArray(source)) {
var arr = source.concat()
source.length = 0
var collection = arrayFactory(source)// jshint ignore:line
collection.pushArray(arr)
return collection
}
//0 null undefined || Node || VModel(fix IE6-8 createWithProxy $val: val引发的BUG)
if (!source || source.nodeType > 0 || (source.$id && source.$events)) {
return source
}
var $skipArray = Array.isArray(source.$skipArray) ? source.$skipArray : []
$skipArray.$special = $special || createMap() //强制要监听的属性
var $vmodel = {} //要返回的对象, 它在IE6-8下可能被偷龙转凤
$model = $model || {} //vmodels.$model属性
var $events = createMap() //vmodel.$events属性
var accessors = createMap() //监控属性
var computed = []
$$skipArray.forEach(function (name) {
delete source[name]
})
for (var i in source) {
(function (name, val, accessor) {
$model[name] = val
if (!isObservable(name, val, $skipArray)) {
return //过滤所有非监控属性
}
//总共产生三种accessor
$events[name] = []
var valueType = avalon.type(val)
//总共产生三种accessor
if (valueType === "object" && isFunction(val.get) && Object.keys(val).length <= 2) {
accessor = makeComputedAccessor(name, val)
computed.push(accessor)
} else if (rcomplexType.test(valueType)) {
accessor = makeComplexAccessor(name, val, valueType, $events[name])
} else {
accessor = makeSimpleAccessor(name, val)
}
accessors[name] = accessor
})(i, source[i])// jshint ignore:line
}
$vmodel = Object.defineProperties($vmodel, descriptorFactory(accessors)) //生成一个空的ViewModel
for (var name in source) {
if (!accessors[name]) {
$vmodel[name] = source[name]
}
}
//添加$id, $model, $events, $watch, $unwatch, $fire
$vmodel.$id = generateID()
$vmodel.$model = $model
$vmodel.$events = $events
for (i in EventBus) {
$vmodel[i] = EventBus[i]
}
Object.defineProperty($vmodel, "hasOwnProperty", {
value: function (name) {
return name in this.$model
},
writable: false,
enumerable: false,
configurable: true
})
$vmodel.$compute = function () {
computed.forEach(function (accessor) {
dependencyDetection.begin({
callback: function (vm, dependency) {//dependency为一个accessor
var name = dependency._name
if (dependency !== accessor) {
var list = vm.$events[name]
accessor.vm = $vmodel
injectDependency(list, accessor.digest)
}
}
})
try {
accessor.get.call($vmodel)
} finally {
dependencyDetection.end()
}
})
}
$vmodel.$compute()
return $vmodel
}
//创建一个简单访问器
function makeSimpleAccessor(name, value) {
function accessor(value) {
var oldValue = accessor._value
if (arguments.length > 0) {
if (!stopRepeatAssign && !isEqual(value, oldValue)) {
accessor.updateValue(this, value)
accessor.notify(this, value, oldValue)
}
return this
} else {
dependencyDetection.collectDependency(this, accessor)
return oldValue
}
}
accessorFactory(accessor, name)
accessor._value = value
return accessor;
}
///创建一个计算访问器
function makeComputedAccessor(name, options) {
options.set = options.set || noop
function accessor(value) {//计算属性
var oldValue = accessor._value
var init = "_value" in accessor
if (arguments.length > 0) {
if (stopRepeatAssign) {
return this
}
accessor.set.call(this, value)
return this
} else {
//将依赖于自己的高层访问器或视图刷新函数(以绑定对象形式)放到自己的订阅数组中
value = accessor.get.call(this)
if (oldValue !== value) {
accessor.updateValue(this, value)
init && accessor.notify(this, value, oldValue) //触发$watch回调
}
//将自己注入到低层访问器的订阅数组中
return value
}
}
accessor.set = options.set || noop
accessor.get = options.get
accessorFactory(accessor, name)
var id
accessor.digest = function () {
accessor.updateValue = globalUpdateModelValue
accessor.notify = noop
accessor.call(accessor.vm)
clearTimeout(id)//如果计算属性存在多个依赖项,那么等它们都更新了才更新视图
id = setTimeout(function () {
accessorFactory(accessor, accessor._name)
accessor.call(accessor.vm)
})
}
return accessor
}
//创建一个复杂访问器
function makeComplexAccessor(name, initValue, valueType, list) {
function accessor(value) {
var oldValue = accessor._value
var son = accessor._vmodel
if (arguments.length > 0) {
if (stopRepeatAssign) {
return this
}
if (valueType === "array") {
var old = son._
son._ = []
son.clear()
son._ = old
son.pushArray(value)
} else if (valueType === "object") {
var $proxy = son.$proxy
var observes = this.$events[name] || []
son = accessor._vmodel = modelFactory(value)
son.$proxy = $proxy
if (observes.length) {
observes.forEach(function (data) {
if (data.rollback) {
data.rollback() //还原 ms-with ms-on
}
bindingHandlers[data.type](data, data.vmodels)
})
son.$events[name] = observes
}
}
accessor.updateValue(this, son.$model)
accessor.notify(this, this._value, oldValue)
return this
} else {
dependencyDetection.collectDependency(this, accessor)
return son
}
}
accessorFactory(accessor, name)
var son = accessor._vmodel = modelFactory(initValue)
son.$events[subscribers] = list
return accessor
}
function globalUpdateValue(vmodel, value) {
vmodel.$model[this._name] = this._value = value
}
function globalUpdateModelValue(vmodel, value) {
vmodel.$model[this._name] = value
}
function globalNotify(vmodel, value, oldValue) {
var name = this._name
var array = vmodel.$events[name] //刷新值
if (array) {
fireDependencies(array) //同步视图
EventBus.$fire.call(vmodel, name, value, oldValue) //触发$watch回调
}
}
function accessorFactory(accessor, name) {
accessor._name = name
//同时更新_value与model
accessor.updateValue = globalUpdateValue
accessor.notify = globalNotify
}
//比较两个值是否相等
var isEqual = Object.is || function (v1, v2) {
if (v1 === 0 && v2 === 0) {
return 1 / v1 === 1 / v2
} else if (v1 !== v1) {
return v2 !== v2
} else {
return v1 === v2
}
}
function isObservable(name, value, $skipArray) {
if (isFunction(value) || value && value.nodeType) {
return false
}
if ($skipArray.indexOf(name) !== -1) {
return false
}
var $special = $skipArray.$special
if (name && name.charAt(0) === "$" && !$special[name]) {
return false
}
return true
}
var descriptorFactory = function (obj) {
var descriptors = {}
for (var i in obj) {
descriptors[i] = {
get: obj[i],
set: obj[i],
enumerable: true,
configurable: true
}
}
return descriptors
}
/*********************************************************************
* 监控数组(与ms-each, ms-repeat配合使用) *
**********************************************************************/
function arrayFactory(model) {
var array = []
array.$id = generateID()
array.$model = model //数据模型
array.$events = {}
array.$events[subscribers] = []
array._ = modelFactory({
length: model.length
})
array._.$watch("length", function (a, b) {
array.$fire("length", a, b)
})
for (var i in EventBus) {
array[i] = EventBus[i]
}
array.$map = {
el: 1
}
array.$proxy = []
avalon.mix(array, arrayPrototype)
return array
}
function mutateArray(method, pos, n, index, method2, pos2, n2) {
var oldLen = this.length, loop = 2
while (--loop) {
switch (method) {
case "add":
/* jshint ignore:start */
var m = pos + n
var array = this.$model.slice(pos, m).map(function (el) {
if (rcomplexType.test(avalon.type(el))) {//转换为VM
return el.$id ? el : modelFactory(el, 0, el)
} else {
return el
}
})
_splice.apply(this, [pos, 0].concat(array))
/* jshint ignore:end */
for (var i = pos; i < m; i++) {//生成代理VM
var proxy = eachProxyAgent(i, this)
this.$proxy.splice(i, 0, proxy)
}
this._fire("add", pos, n)
break
case "del":
var ret = this._splice(pos, n)
var removed = this.$proxy.splice(pos, n) //回收代理VM
eachProxyRecycler(removed, "each")
this._fire("del", pos, n)
break
}
if (method2) {
method = method2
pos = pos2
n = n2
loop = 2
method2 = 0
}
}
resetIndex(this.$proxy, index)
if (this.length !== oldLen) {
this._.length = this.length
}
return ret
}
var _splice = ap.splice
var arrayPrototype = {
_splice: _splice,
_fire: function (method, a, b) {
fireDependencies(this.$events[subscribers], method, a, b)
},
size: function () { //取得数组长度,这个函数可以同步视图,length不能
return this._.length
},
pushArray: function (array) {
var m = array.length, n = this.length
if (m) {
ap.push.apply(this.$model, array)
mutateArray.call(this, "add", n, m, Math.max(0, n - 1))
}
return m + n
},
push: function () {
//http://jsperf.com/closure-with-arguments
var array = []
var i, n = arguments.length
for (i = 0; i < n; i++) {
array[i] = arguments[i]
}
return this.pushArray(array)
},
unshift: function () {
var m = arguments.length, n = this.length
if (m) {
ap.unshift.apply(this.$model, arguments)
mutateArray.call(this, "add", 0, m, 0)
}
return m + n //IE67的unshift不会返回长度
},
shift: function () {
if (this.length) {
var el = this.$model.shift()
mutateArray.call(this, "del", 0, 1, 0)
return el //返回被移除的元素
}
},
pop: function () {
var n = this.length
if (n) {
var el = this.$model.pop()
mutateArray.call(this, "del", n - 1, 1, Math.max(0, n - 2))
return el //返回被移除的元素
}
},
splice: function (start) {
var m = arguments.length, args = [], change
var removed = _splice.apply(this.$model, arguments)
if (removed.length) { //如果用户删掉了元素
args.push("del", start, removed.length, 0)
change = true
}
if (m > 2) { //如果用户添加了元素
if (change) {
args.splice(3, 1, 0, "add", start, m - 2)
} else {
args.push("add", start, m - 2, 0)
}
change = true
}
if (change) { //返回被移除的元素
return mutateArray.apply(this, args)
} else {
return []
}
},
contains: function (el) { //判定是否包含
return this.indexOf(el) !== -1
},
remove: function (el) { //移除第一个等于给定值的元素
return this.removeAt(this.indexOf(el))
},
removeAt: function (index) { //移除指定索引上的元素
if (index >= 0) {
this.$model.splice(index, 1)
return mutateArray.call(this, "del", index, 1, 0)
}
return []
},
clear: function () {
eachProxyRecycler(this.$proxy, "each")
this.$model.length = this.$proxy.length = this.length = this._.length = 0 //清空数组
this._fire("clear", 0)
return this
},
removeAll: function (all) { //移除N个元素
if (Array.isArray(all)) {
for (var i = this.length - 1; i >= 0; i--) {
if (all.indexOf(this[i]) !== -1) {
this.removeAt(i)
}
}
} else if (typeof all === "function") {
for (i = this.length - 1; i >= 0; i--) {
if (all(this[i], i)) {
this.removeAt(i)
}
}
} else {
this.clear()
}
},
ensure: function (el) {
if (!this.contains(el)) { //只有不存在才push
this.push(el)
}
return this
},
set: function (index, val) {
if (index >= 0) {
var valueType = avalon.type(val)
if (val && val.$model) {
val = val.$model
}
var target = this[index]
if (valueType === "object") {
for (var i in val) {
if (target.hasOwnProperty(i)) {
target[i] = val[i]
}
}
} else if (valueType === "array") {
target.clear().push.apply(target, val)
} else if (target !== val) {
this[index] = val
this.$model[index] = val
var proxy = this.$proxy[index]
if (proxy) {
fireDependencies(proxy.$events.$index)
}
}
}
return this
}
}
//相当于原来bindingExecutors.repeat 的index分支
function resetIndex(array, pos) {
var last = array.length - 1
for (var el; el = array[pos]; pos++) {
el.$index = pos
el.$first = pos === 0
el.$last = pos === last
}
}
function sortByIndex(array, indexes) {
var map = {};
for (var i = 0, n = indexes.length; i < n; i++) {
map[i] = array[i] // preserve
var j = indexes[i]
if (j in map) {
array[i] = map[j]
delete map[j]
} else {
array[i] = array[j]
}
}
}
"sort,reverse".replace(rword, function (method) {
arrayPrototype[method] = function () {
var newArray = this.$model//这是要排序的新数组
var oldArray = newArray.concat() //保持原来状态的旧数组
var mask = Math.random()
var indexes = []
var hasSort
ap[method].apply(newArray, arguments) //排序
for (var i = 0, n = oldArray.length; i < n; i++) {
var neo = newArray[i]
var old = oldArray[i]
if (isEqual(neo, old)) {
indexes.push(i)
} else {
var index = oldArray.indexOf(neo)
indexes.push(index)//得到新数组的每个元素在旧数组对应的位置
oldArray[index] = mask //屏蔽已经找过的元素
hasSort = true
}
}
if (hasSort) {
sortByIndex(this, indexes)
sortByIndex(this.$proxy, indexes)
this._fire("move", indexes)
resetIndex(this.$proxy, 0)
}
return this
}
})
var eachProxyPool = []
function eachProxyFactory() {
var source = {
$index: NaN,
$first: NaN,
$last: NaN,
$map: {},
$host: {},
$outer: {},
$remove: avalon.noop,
el: {
get: function () {
//avalon1.4.4中,计算属性的订阅数组不再添加绑定对象
return this.$host[this.$index]
},
set: function (val) {
this.$host.set(this.$index, val)
}
}
}
var second = {
$last: 1,
$first: 1,
$index: 1
}
var proxy = modelFactory(source, second)
proxy.$id = generateID("$proxy$each")
return proxy
}
function eachProxyAgent(index, host) {
var proxy = eachProxyPool.shift()
if (!proxy) {
proxy = eachProxyFactory( )
}else{
proxy.$compute()
}
var last = host.length - 1
proxy.$host = host
proxy.$index = index
proxy.$first = index === 0
proxy.$last = index === last
proxy.$map = host.$map
proxy.$remove = function () {
return host.removeAt(proxy.$index)
}
return proxy
}
/*********************************************************************
* 依赖调度系统 *
**********************************************************************/
//检测两个对象间的依赖关系
var dependencyDetection = (function () {
var outerFrames = []
var currentFrame
return {
begin: function (accessorObject) {
//accessorObject为一个拥有callback的对象
outerFrames.push(currentFrame)
currentFrame = accessorObject
},
end: function () {
currentFrame = outerFrames.pop()
},
collectDependency: function (vmodel, accessor) {
if (currentFrame) {
//被dependencyDetection.begin调用
currentFrame.callback(vmodel, accessor);
}
}
};
})()
//将绑定对象注入到其依赖项的订阅数组中
var ronduplex = /^(duplex|on)$/
avalon.injectBinding = function (data) {
var fn = data.evaluator
if (fn) { //如果是求值函数
dependencyDetection.begin({
callback: function (vmodel, dependency) {
injectDependency(vmodel.$events[dependency._name], data)
}
})
try {
var c = ronduplex.test(data.type) ? data : fn.apply(0, data.args)
data.handler(c, data.element, data)
} catch (e) {
//log("warning:exception throwed in [avalon.injectBinding] " + e)
delete data.evaluator
var node = data.element
if (node.nodeType === 3) {
var parent = node.parentNode
if (kernel.commentInterpolate) {
parent.replaceChild(DOC.createComment(data.value), node)
} else {
node.data = openTag + data.value + closeTag
}
}
} finally {
dependencyDetection.end()
}
}
}
//将依赖项(比它高层的访问器或构建视图刷新函数的绑定对象)注入到订阅者数组
function injectDependency(list, data) {
data = data || Registry[expose]
if (list && data && avalon.Array.ensure(list, data) && data.element) {
injectDisposeQueue(data, list)
}
}
//通知依赖于这个访问器的订阅者更新自身
function fireDependencies(list) {
if (list && list.length) {
if (new Date() - beginTime > 444 && typeof list[0] === "object") {
rejectDisposeQueue()
}
var args = aslice.call(arguments, 1)
for (var i = list.length, fn; fn = list[--i]; ) {
var el = fn.element
if (el && el.parentNode) {
if (fn.$repeat) {
fn.handler.apply(fn, args) //处理监控数组的方法
} else if (fn.type !== "on") { //事件绑定只能由用户触发,不能由程序触发
var fun = fn.evaluator || noop
fn.handler(fun.apply(0, fn.args || []), el, fn)
}
}
}
}
}
/*********************************************************************
* 定时GC回收机制 *
**********************************************************************/
var disposeCount = 0
var disposeQueue = avalon.$$subscribers = []
var beginTime = new Date()
var oldInfo = {}
function getUid(obj) { //IE9+,标准浏览器
return obj.uniqueNumber || (obj.uniqueNumber = ++disposeCount)
}
//添加到回收列队中
function injectDisposeQueue(data, list) {
var elem = data.element
if (!data.uuid) {
if (elem.nodeType !== 1) {
data.uuid = data.type + (data.pos || 0) + "-" + getUid(elem.parentNode)
} else {
data.uuid = data.name + "-" + getUid(elem)
}
}
var lists = data.lists || (data.lists = [])
avalon.Array.ensure(lists, list)
list.$uuid = list.$uuid || generateID()
if (!disposeQueue[data.uuid]) {
disposeQueue[data.uuid] = 1
disposeQueue.push(data)
}
}
function rejectDisposeQueue(data) {
var i = disposeQueue.length
var n = i
var allTypes = []
var iffishTypes = {}
var newInfo = {}
//对页面上所有绑定对象进行分门别类, 只检测个数发生变化的类型
while (data = disposeQueue[--i]) {
var type = data.type
if (newInfo[type]) {
newInfo[type]++
} else {
newInfo[type] = 1
allTypes.push(type)
}
}
var diff = false
allTypes.forEach(function (type) {
if (oldInfo[type] !== newInfo[type]) {
iffishTypes[type] = 1
diff = true
}
})
i = n
if (diff) {
while (data = disposeQueue[--i]) {
if (!data.element)
continue
if (iffishTypes[data.type] && shouldDispose(data.element)) { //如果它没有在DOM树
disposeQueue.splice(i, 1)
delete disposeQueue[data.uuid]
var lists = data.lists
for (var k = 0, list; list = lists[k++]; ) {
avalon.Array.remove(lists, list)
avalon.Array.remove(list, data)
}
disposeData(data)
}
}
}
oldInfo = newInfo
beginTime = new Date()
}
function disposeData(data) {
data.element = null
data.rollback && data.rollback()
for (var key in data) {
data[key] = null
}
}
function shouldDispose(el) {
try {//IE下,如果文本节点脱离DOM树,访问parentNode会报错
if (!el.parentNode) {
return true
}
} catch (e) {
return true
}
return el.msRetain ? 0 : (el.nodeType === 1 ? !root.contains(el) : !avalon.contains(root, el))
}
/************************************************************************
* HTML处理(parseHTML, innerHTML, clearHTML) *
**************************************************************************/
//parseHTML的辅助变量
var tagHooks = new function() {// jshint ignore:line
avalon.mix(this, {
option: DOC.createElement("select"),
thead: DOC.createElement("table"),
td: DOC.createElement("tr"),
area: DOC.createElement("map"),
tr: DOC.createElement("tbody"),
col: DOC.createElement("colgroup"),
legend: DOC.createElement("fieldset"),
_default: DOC.createElement("div"),
"g": DOC.createElementNS("http://www.w3.org/2000/svg", "svg")
})
this.optgroup = this.option
this.tbody = this.tfoot = this.colgroup = this.caption = this.thead
this.th = this.td
}// jshint ignore:line
String("circle,defs,ellipse,image,line,path,polygon,polyline,rect,symbol,text,use").replace(rword, function(tag) {
tagHooks[tag] = tagHooks.g //处理SVG
})
var rtagName = /<([\w:]+)/
var rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig
var scriptTypes = oneObject(["", "text/javascript", "text/ecmascript", "application/ecmascript", "application/javascript"])
var script = DOC.createElement("script")
var rhtml = /<|&#?\w+;/
avalon.parseHTML = function(html) {
var fragment = avalonFragment.cloneNode(false)
if (typeof html !== "string" ) {
return fragment
}
if (!rhtml.test(html)) {
fragment.appendChild(DOC.createTextNode(html))
return fragment
}
html = html.replace(rxhtml, "<$1></$2>").trim()
var tag = (rtagName.exec(html) || ["", ""])[1].toLowerCase(),
//取得其标签名
wrapper = tagHooks[tag] || tagHooks._default,
firstChild
wrapper.innerHTML = html
var els = wrapper.getElementsByTagName("script")
if (els.length) { //使用innerHTML生成的script节点不会发出请求与执行text属性
for (var i = 0, el; el = els[i++]; ) {
if (scriptTypes[el.type]) {
var neo = script.cloneNode(false) //FF不能省略参数
ap.forEach.call(el.attributes, function(attr) {
neo.setAttribute(attr.name, attr.value)
})// jshint ignore:line
neo.text = el.text
el.parentNode.replaceChild(neo, el)
}
}
}
while (firstChild = wrapper.firstChild) { // 将wrapper上的节点转移到文档碎片上!
fragment.appendChild(firstChild)
}
return fragment
}
avalon.innerHTML = function(node, html) {
var a = this.parseHTML(html)
this.clearHTML(node).appendChild(a)
}
avalon.clearHTML = function(node) {
node.textContent = ""
while (node.firstChild) {
node.removeChild(node.firstChild)
}
return node
}
/*********************************************************************
* avalon的原型方法定义区 *
**********************************************************************/
function hyphen(target) {
//转换为连字符线风格
return target.replace(/([a-z\d])([A-Z]+)/g, "$1-$2").toLowerCase()
}
function camelize(target) {
//转换为驼峰风格
if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
return target //提前判断,提高getStyle等的效率
}
return target.replace(/[-_][^-_]/g, function(match) {
return match.charAt(1).toUpperCase()
})
}
"add,remove".replace(rword, function(method) {
avalon.fn[method + "Class"] = function(cls) {
var el = this[0]
//https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
if (cls && typeof cls === "string" && el && el.nodeType === 1) {
cls.replace(/\S+/g, function(c) {
el.classList[method](c)
})
}
return this
}
})
avalon.fn.mix({
hasClass: function(cls) {
var el = this[0] || {} //IE10+, chrome8+, firefox3.6+, safari5.1+,opera11.5+支持classList,chrome24+,firefox26+支持classList2.0
return el.nodeType === 1 && el.classList.contains(cls)
},
toggleClass: function(value, stateVal) {
var className, i = 0
var classNames = String(value).split(/\s+/)
var isBool = typeof stateVal === "boolean"
while ((className = classNames[i++])) {
var state = isBool ? stateVal : !this.hasClass(className)
this[state ? "addClass" : "removeClass"](className)
}
return this
},
attr: function(name, value) {
if (arguments.length === 2) {
this[0].setAttribute(name, value)
return this
} else {
return this[0].getAttribute(name)
}
},
data: function(name, value) {
name = "data-" + hyphen(name || "")
switch (arguments.length) {
case 2:
this.attr(name, value)
return this
case 1:
var val = this.attr(name)
return parseData(val)
case 0:
var ret = {}
ap.forEach.call(this[0].attributes, function(attr) {
if (attr) {
name = attr.name
if (!name.indexOf("data-")) {
name = camelize(name.slice(5))
ret[name] = parseData(attr.value)
}
}
})
return ret
}
},
removeData: function(name) {
name = "data-" + hyphen(name)
this[0].removeAttribute(name)
return this
},
css: function(name, value) {
if (avalon.isPlainObject(name)) {
for (var i in name) {
avalon.css(this, i, name[i])
}
} else {
var ret = avalon.css(this, name, value)
}
return ret !== void 0 ? ret : this
},
position: function() {
var offsetParent, offset,
elem = this[0],
parentOffset = {
top: 0,
left: 0
};
if (!elem) {
return
}
if (this.css("position") === "fixed") {
offset = elem.getBoundingClientRect()
} else {
offsetParent = this.offsetParent() //得到真正的offsetParent
offset = this.offset() // 得到正确的offsetParent
if (offsetParent[0].tagName !== "HTML") {
parentOffset = offsetParent.offset()
}
parentOffset.top += avalon.css(offsetParent[0], "borderTopWidth", true)
parentOffset.left += avalon.css(offsetParent[0], "borderLeftWidth", true)
// Subtract offsetParent scroll positions
parentOffset.top -= offsetParent.scrollTop()
parentOffset.left -= offsetParent.scrollLeft()
}
return {
top: offset.top - parentOffset.top - avalon.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - avalon.css(elem, "marginLeft", true)
}
},
offsetParent: function() {
var offsetParent = this[0].offsetParent
while (offsetParent && avalon.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent;
}
return avalon(offsetParent || root)
},
bind: function(type, fn, phase) {
if (this[0]) { //此方法不会链
return avalon.bind(this[0], type, fn, phase)
}
},
unbind: function(type, fn, phase) {
if (this[0]) {
avalon.unbind(this[0], type, fn, phase)
}
return this
},
val: function(value) {
var node = this[0]
if (node && node.nodeType === 1) {
var get = arguments.length === 0
var access = get ? ":get" : ":set"
var fn = valHooks[getValType(node) + access]
if (fn) {
var val = fn(node, value)
} else if (get) {
return (node.value || "").replace(/\r/g, "")
} else {
node.value = value
}
}
return get ? val : this
}
})
if (root.dataset) {
avalon.fn.data = function(name, val) {
name = name && camelize(name)
var dataset = this[0].dataset
switch (arguments.length) {
case 2:
dataset[name] = val
return this
case 1:
val = dataset[name]
return parseData(val)
case 0:
var ret = createMap()
for (name in dataset) {
ret[name] = parseData(dataset[name])
}
return ret
}
}
}
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/
avalon.parseJSON = JSON.parse
function parseData(data) {
try {
if (typeof data === "object")
return data
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null : +data + "" === data ? +data : rbrace.test(data) ? JSON.parse(data) : data
} catch (e) {}
return data
}
avalon.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(method, prop) {
avalon.fn[method] = function(val) {
var node = this[0] || {}, win = getWindow(node),
top = method === "scrollTop"
if (!arguments.length) {
return win ? win[prop] : node[method]
} else {
if (win) {
win.scrollTo(!top ? val : win[prop], top ? val : win[prop])
} else {
node[method] = val
}
}
}
})
function getWindow(node) {
return node.window && node.document ? node : node.nodeType === 9 ? node.defaultView : false
}
//=============================css相关==================================
var cssHooks = avalon.cssHooks = createMap()
var prefixes = ["", "-webkit-", "-moz-", "-ms-"] //去掉opera-15的支持
var cssMap = {
"float": "cssFloat"
}
avalon.cssNumber = oneObject("columnCount,order,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom")
avalon.cssName = function(name, host, camelCase) {
if (cssMap[name]) {
return cssMap[name]
}
host = host || root.style
for (var i = 0, n = prefixes.length; i < n; i++) {
camelCase = camelize(prefixes[i] + name)
if (camelCase in host) {
return (cssMap[name] = camelCase)
}
}
return null
}
cssHooks["@:set"] = function(node, name, value) {
node.style[name] = value
}
cssHooks["@:get"] = function(node, name) {
if (!node || !node.style) {
throw new Error("getComputedStyle要求传入一个节点 " + node)
}
var ret, computed = getComputedStyle(node)
if (computed) {
ret = name === "filter" ? computed.getPropertyValue(name) : computed[name]
if (ret === "") {
ret = node.style[name] //其他浏览器需要我们手动取内联样式
}
}
return ret
}
cssHooks["opacity:get"] = function(node) {
var ret = cssHooks["@:get"](node, "opacity")
return ret === "" ? "1" : ret
}
"top,left".replace(rword, function(name) {
cssHooks[name + ":get"] = function(node) {
var computed = cssHooks["@:get"](node, name)
return /px$/.test(computed) ? computed :
avalon(node).position()[name] + "px"
}
})
var cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}
var rdisplayswap = /^(none|table(?!-c[ea]).+)/
function showHidden(node, array) {
//http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
if (node.offsetWidth <= 0) { //opera.offsetWidth可能小于0
var styles = getComputedStyle(node, null)
if (rdisplayswap.test(styles["display"])) {
var obj = {
node: node
}
for (var name in cssShow) {
obj[name] = styles[name]
node.style[name] = cssShow[name]
}
array.push(obj)
}
var parent = node.parentNode
if (parent && parent.nodeType === 1) {
showHidden(parent, array)
}
}
}
"Width,Height".replace(rword, function(name) { //fix 481
var method = name.toLowerCase(),
clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name
cssHooks[method + ":get"] = function(node, which, override) {
var boxSizing = -4
if (typeof override === "number") {
boxSizing = override
}
which = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"]
var ret = node[offsetProp] // border-box 0
if (boxSizing === 2) { // margin-box 2
return ret + avalon.css(node, "margin" + which[0], true) + avalon.css(node, "margin" + which[1], true)
}
if (boxSizing < 0) { // padding-box -2
ret = ret - avalon.css(node, "border" + which[0] + "Width", true) - avalon.css(node, "border" + which[1] + "Width", true)
}
if (boxSizing === -4) { // content-box -4
ret = ret - avalon.css(node, "padding" + which[0], true) - avalon.css(node, "padding" + which[1], true)
}
return ret
}
cssHooks[method + "&get"] = function(node) {
var hidden = [];
showHidden(node, hidden);
var val = cssHooks[method + ":get"](node)
for (var i = 0, obj; obj = hidden[i++];) {
node = obj.node
for (var n in obj) {
if (typeof obj[n] === "string") {
node.style[n] = obj[n]
}
}
}
return val;
}
avalon.fn[method] = function(value) { //会忽视其display
var node = this[0]
if (arguments.length === 0) {
if (node.setTimeout) { //取得窗口尺寸,IE9后可以用node.innerWidth /innerHeight代替
return node["inner" + name]
}
if (node.nodeType === 9) { //取得页面尺寸
var doc = node.documentElement
//FF chrome html.scrollHeight< body.scrollHeight
//IE 标准模式 : html.scrollHeight> body.scrollHeight
//IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp])
}
return cssHooks[method + "&get"](node)
} else {
return this.css(method, value)
}
}
avalon.fn["inner" + name] = function() {
return cssHooks[method + ":get"](this[0], void 0, -2)
}
avalon.fn["outer" + name] = function(includeMargin) {
return cssHooks[method + ":get"](this[0], void 0, includeMargin === true ? 2 : 0)
}
})
avalon.fn.offset = function() { //取得距离页面左右角的坐标
var node = this[0]
try {
var rect = node.getBoundingClientRect()
// Make sure element is not hidden (display: none) or disconnected
// https://github.com/jquery/jquery/pull/2043/files#r23981494
if (rect.width || rect.height || node.getClientRects().length) {
var doc = node.ownerDocument
var root = doc.documentElement
var win = doc.defaultView
return {
top: rect.top + win.pageYOffset - root.clientTop,
left: rect.left + win.pageXOffset - root.clientLeft
}
}
} catch (e) {
return {
left: 0,
top: 0
}
}
}
//=============================val相关=======================
function getValType(elem) {
var ret = elem.tagName.toLowerCase()
return ret === "input" && /checkbox|radio/.test(elem.type) ? "checked" : ret
}
var valHooks = {
"select:get": function(node, value) {
var option, options = node.options,
index = node.selectedIndex,
one = node.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ? max : one ? index : 0
for (; i < max; i++) {
option = options[i]
//旧式IE在reset后不会改变selected,需要改用i === index判定
//我们过滤所有disabled的option元素,但在safari5下,如果设置select为disable,那么其所有孩子都disable
//因此当一个元素为disable,需要检测其是否显式设置了disable及其父节点的disable情况
if ((option.selected || i === index) && !option.disabled) {
value = option.value
if (one) {
return value
}
//收集所有selected值组成数组返回
values.push(value)
}
}
return values
},
"select:set": function(node, values, optionSet) {
values = [].concat(values) //强制转换为数组
for (var i = 0, el; el = node.options[i++];) {
if ((el.selected = values.indexOf(el.value) > -1)) {
optionSet = true
}
}
if (!optionSet) {
node.selectedIndex = -1
}
}
}
/*********************************************************************
* 编译系统 *
**********************************************************************/
var quote = JSON.stringify
var keywords = [
"break,case,catch,continue,debugger,default,delete,do,else,false",
"finally,for,function,if,in,instanceof,new,null,return,switch,this",
"throw,true,try,typeof,var,void,while,with", /* 关键字*/
"abstract,boolean,byte,char,class,const,double,enum,export,extends",
"final,float,goto,implements,import,int,interface,long,native",
"package,private,protected,public,short,static,super,synchronized",
"throws,transient,volatile", /*保留字*/
"arguments,let,yield,undefined" /* ECMA 5 - use strict*/].join(",")
var rrexpstr = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g
var rsplit = /[^\w$]+/g
var rkeywords = new RegExp(["\\b" + keywords.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g')
var rnumber = /\b\d[^,]*/g
var rcomma = /^,+|,+$/g
var variablePool = new Cache(512)
var getVariables = function (code) {
var key = "," + code.trim()
var ret = variablePool.get(key)
if (ret) {
return ret
}
var match = code
.replace(rrexpstr, "")
.replace(rsplit, ",")
.replace(rkeywords, "")
.replace(rnumber, "")
.replace(rcomma, "")
.split(/^$|,+/)
return variablePool.put(key, uniqSet(match))
}
/*添加赋值语句*/
function addAssign(vars, scope, name, data) {
var ret = [],
prefix = " = " + name + "."
var isProxy = /\$proxy\$each/.test(scope.$id)
for (var i = vars.length, prop; prop = vars[--i]; ) {
var el = isProxy && scope.$map[prop] ? "el" : prop
if (scope.hasOwnProperty(el)) {
ret.push(prop + prefix + el)
data.vars.push(prop)
if (data.type === "duplex") {
vars.get = name + "." + el
}
vars.splice(i, 1)
}
}
return ret
}
function uniqSet(array) {
var ret = [],
unique = {}
for (var i = 0; i < array.length; i++) {
var el = array[i]
var id = el && typeof el.$id === "string" ? el.$id : el
if (!unique[id]) {
unique[id] = ret.push(el)
}
}
return ret
}
//缓存求值函数,以便多次利用
var evaluatorPool = new Cache(128)
//取得求值函数及其传参
var rduplex = /\w\[.*\]|\w\.\w/
var rproxy = /(\$proxy\$[a-z]+)\d+$/
var rthimRightParentheses = /\)\s*$/
var rthimOtherParentheses = /\)\s*\|/g
var rquoteFilterName = /\|\s*([$\w]+)/g
var rpatchBracket = /"\s*\["/g
var rthimLeftParentheses = /"\s*\(/g
function parseFilter(val, filters) {
filters = filters
.replace(rthimRightParentheses, "")//处理最后的小括号
.replace(rthimOtherParentheses, function () {//处理其他小括号
return "],|"
})
.replace(rquoteFilterName, function (a, b) { //处理|及它后面的过滤器的名字
return "[" + quote(b)
})
.replace(rpatchBracket, function () {
return '"],["'
})
.replace(rthimLeftParentheses, function () {
return '",'
}) + "]"
return "return avalon.filters.$filter(" + val + ", " + filters + ")"
}
function parseExpr(code, scopes, data) {
var dataType = data.type
var filters = data.filters || ""
var exprId = scopes.map(function (el) {
return String(el.$id).replace(rproxy, "$1")
}) + code + dataType + filters
var vars = getVariables(code).concat(),
assigns = [],
names = [],
args = [],
prefix = ""
//args 是一个对象数组, names 是将要生成的求值函数的参数
scopes = uniqSet(scopes)
data.vars = []
for (var i = 0, sn = scopes.length; i < sn; i++) {
if (vars.length) {
var name = "vm" + expose + "_" + i
names.push(name)
args.push(scopes[i])
assigns.push.apply(assigns, addAssign(vars, scopes[i], name, data))
}
}
if (!assigns.length && dataType === "duplex") {
return
}
if (dataType !== "duplex" && (code.indexOf("||") > -1 || code.indexOf("&&") > -1)) {
//https://github.com/RubyLouvre/avalon/issues/583
data.vars.forEach(function (v) {
var reg = new RegExp("\\b" + v + "(?:\\.\\w+|\\[\\w+\\])+", "ig")
code = code.replace(reg, function (_) {
var c = _.charAt(v.length)
var r = IEVersion ? code.slice(arguments[1] + _.length) : RegExp.rightContext
var method = /^\s*\(/.test(r)
if (c === "." || c === "[" || method) {//比如v为aa,我们只匹配aa.bb,aa[cc],不匹配aaa.xxx
var name = "var" + String(Math.random()).replace(/^0\./, "")
if (method) {//array.size()
var array = _.split(".")
if (array.length > 2) {
var last = array.pop()
assigns.push(name + " = " + array.join("."))
return name + "." + last
} else {
return _
}
}
assigns.push(name + " = " + _)
return name
} else {
return _
}
})
})
}
//---------------args----------------
data.args = args
//---------------cache----------------
delete data.vars
var fn = evaluatorPool.get(exprId) //直接从缓存,免得重复生成
if (fn) {
data.evaluator = fn
return
}
prefix = assigns.join(", ")
if (prefix) {
prefix = "var " + prefix
}
if (/\S/.test(filters)) { //文本绑定,双工绑定才有过滤器
if (!/text|html/.test(data.type)) {
throw Error("ms-" + data.type + "不支持过滤器")
}
code = "\nvar ret" + expose + " = " + code + ";\r\n"
code += parseFilter("ret" + expose, filters)
} else if (dataType === "duplex") { //双工绑定
var _body = "'use strict';\nreturn function(vvv){\n\t" +
prefix +
";\n\tif(!arguments.length){\n\t\treturn " +
code +
"\n\t}\n\t" + (!rduplex.test(code) ? vars.get : code) +
"= vvv;\n} "
try {
fn = Function.apply(noop, names.concat(_body))
data.evaluator = evaluatorPool.put(exprId, fn)
} catch (e) {
log("debug: parse error," + e.message)
}
return
} else if (dataType === "on") { //事件绑定
if (code.indexOf("(") === -1) {
code += ".call(this, $event)"
} else {
code = code.replace("(", ".call(this,")
}
names.push("$event")
code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
var lastIndex = code.lastIndexOf("\nreturn")
var header = code.slice(0, lastIndex)
var footer = code.slice(lastIndex)
code = header + "\n" + footer
} else { //其他绑定
code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
}
try {
fn = Function.apply(noop, names.concat("'use strict';\n" + prefix + code))
data.evaluator = evaluatorPool.put(exprId, fn)
} catch (e) {
log("debug: parse error," + e.message)
} finally {
vars = assigns = names = null //释放内存
}
}
//parseExpr的智能引用代理
function parseExprProxy(code, scopes, data, tokens, noRegister) {
if (Array.isArray(tokens)) {
code = tokens.map(function (el) {
return el.expr ? "(" + el.value + ")" : quote(el.value)
}).join(" + ")
}
parseExpr(code, scopes, data)
if (data.evaluator && !noRegister) {
data.handler = bindingExecutors[data.handlerName || data.type]
//方便调试
//这里非常重要,我们通过判定视图刷新函数的element是否在DOM树决定
//将它移出订阅者列表
avalon.injectBinding(data)
}
}
avalon.parseExprProxy = parseExprProxy
/*********************************************************************
* 扫描系统 *
**********************************************************************/
avalon.scan = function(elem, vmodel) {
elem = elem || root
var vmodels = vmodel ? [].concat(vmodel) : []
scanTag(elem, vmodels)
}
//http://www.w3.org/TR/html5/syntax.html#void-elements
var stopScan = oneObject("area,base,basefont,br,col,command,embed,hr,img,input,link,meta,param,source,track,wbr,noscript,script,style,textarea".toUpperCase())
function checkScan(elem, callback, innerHTML) {
var id = setTimeout(function() {
var currHTML = elem.innerHTML
clearTimeout(id)
if (currHTML === innerHTML) {
callback()
} else {
checkScan(elem, callback, currHTML)
}
})
}
function createSignalTower(elem, vmodel) {
var id = elem.getAttribute("avalonctrl") || vmodel.$id
elem.setAttribute("avalonctrl", id)
vmodel.$events.expr = elem.tagName + '[avalonctrl="' + id + '"]'
}
var getBindingCallback = function(elem, name, vmodels) {
var callback = elem.getAttribute(name)
if (callback) {
for (var i = 0, vm; vm = vmodels[i++]; ) {
if (vm.hasOwnProperty(callback) && typeof vm[callback] === "function") {
return vm[callback]
}
}
}
}
function executeBindings(bindings, vmodels) {
for (var i = 0, data; data = bindings[i++]; ) {
data.vmodels = vmodels
bindingHandlers[data.type](data, vmodels)
if (data.evaluator && data.element && data.element.nodeType === 1) { //移除数据绑定,防止被二次解析
//chrome使用removeAttributeNode移除不存在的特性节点时会报错 https://github.com/RubyLouvre/avalon/issues/99
data.element.removeAttribute(data.name)
}
}
bindings.length = 0
}
//https://github.com/RubyLouvre/avalon/issues/636
var mergeTextNodes = IEVersion && window.MutationObserver ? function (elem) {
var node = elem.firstChild, text
while (node) {
var aaa = node.nextSibling
if (node.nodeType === 3) {
if (text) {
text.nodeValue += node.nodeValue
elem.removeChild(node)
} else {
text = node
}
} else {
text = null
}
node = aaa
}
} : 0
var rmsAttr = /ms-(\w+)-?(.*)/
var priorityMap = {
"if": 10,
"repeat": 90,
"data": 100,
"widget": 110,
"each": 1400,
"with": 1500,
"duplex": 2000,
"on": 3000
}
var events = oneObject("animationend,blur,change,input,click,dblclick,focus,keydown,keypress,keyup,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,scan,scroll,submit")
var obsoleteAttrs = oneObject("value,title,alt,checked,selected,disabled,readonly,enabled")
function bindingSorter(a, b) {
return a.priority - b.priority
}
function scanAttr(elem, vmodels, match) {
var scanNode = true
if (vmodels.length) {
var attributes = elem.attributes
var bindings = []
var fixAttrs = []
var msData = createMap()
for (var i = 0, attr; attr = attributes[i++]; ) {
if (attr.specified) {
if (match = attr.name.match(rmsAttr)) {
//如果是以指定前缀命名的
var type = match[1]
var param = match[2] || ""
var value = attr.value
var name = attr.name
if (events[type]) {
param = type
type = "on"
} else if (obsoleteAttrs[type]) {
if (type === "enabled") {//吃掉ms-enabled绑定,用ms-disabled代替
log("warning!ms-enabled或ms-attr-enabled已经被废弃")
type = "disabled"
value = "!(" + value + ")"
}
param = type
type = "attr"
name = "ms-" + type +"-" +param
fixAttrs.push([attr.name, name, value])
}
msData[name] = value
if (typeof bindingHandlers[type] === "function") {
var binding = {
type: type,
param: param,
element: elem,
name: name,
value: value,
priority: (priorityMap[type] || type.charCodeAt(0) * 10 )+ (Number(param.replace(/\D/g, "")) || 0)
}
if (type === "html" || type === "text") {
var token = getToken(value)
avalon.mix(binding, token)
binding.filters = binding.filters.replace(rhasHtml, function () {
binding.type = "html"
binding.group = 1
return ""
})// jshint ignore:line
} else if (type === "duplex") {
var hasDuplex = name
} else if (name === "ms-if-loop") {
binding.priority += 100
}
bindings.push(binding)
if (type === "widget") {
elem.msData = elem.msData || msData
}
}
}
}
}
if (bindings.length) {
bindings.sort(bindingSorter)
fixAttrs.forEach(function (arr) {
log("warning!请改用" + arr[1] + "代替" + arr[0] + "!")
elem.removeAttribute(arr[0])
elem.setAttribute(arr[1], arr[2])
})
var control = elem.type
if (control && hasDuplex) {
if (msData["ms-attr-checked"]) {
log("warning!" + control + "控件不能同时定义ms-attr-checked与" + hasDuplex)
}
if (msData["ms-attr-value"]) {
log("warning!" + control + "控件不能同时定义ms-attr-value与" + hasDuplex)
}
}
for (i = 0; binding = bindings[i]; i++) {
type = binding.type
if (rnoscanAttrBinding.test(type)) {
return executeBindings(bindings.slice(0, i + 1), vmodels)
} else if (scanNode) {
scanNode = !rnoscanNodeBinding.test(type)
}
}
executeBindings(bindings, vmodels)
}
}
if (scanNode && !stopScan[elem.tagName] && rbind.test(elem.innerHTML + elem.textContent)) {
mergeTextNodes && mergeTextNodes(elem)
scanNodeList(elem, vmodels) //扫描子孙元素
}
}
var rnoscanAttrBinding = /^if|widget|repeat$/
var rnoscanNodeBinding = /^each|with|html|include$/
//function scanNodeList(parent, vmodels) {
// var node = parent.firstChild
// while (node) {
// var nextNode = node.nextSibling
// scanNode(node, node.nodeType, vmodels)
// node = nextNode
// }
//}
function scanNodeList(parent, vmodels) {
var nodes = avalon.slice(parent.childNodes)
scanNodeArray(nodes, vmodels)
}
function scanNodeArray(nodes, vmodels) {
for (var i = 0, node; node = nodes[i++]; ) {
scanNode(node, node.nodeType, vmodels)
}
}
function scanNode(node, nodeType, vmodels) {
if (nodeType === 1) {
scanTag(node, vmodels) //扫描元素节点
if( node.msCallback){
node.msCallback()
node.msCallback = void 0
}
} else if (nodeType === 3 && rexpr.test(node.data)){
scanText(node, vmodels) //扫描文本节点
} else if (kernel.commentInterpolate && nodeType === 8 && !rexpr.test(node.nodeValue)) {
scanText(node, vmodels) //扫描注释节点
}
}
function scanTag(elem, vmodels, node) {
//扫描顺序 ms-skip(0) --> ms-important(1) --> ms-controller(2) --> ms-if(10) --> ms-repeat(100)
//--> ms-if-loop(110) --> ms-attr(970) ...--> ms-each(1400)-->ms-with(1500)--〉ms-duplex(2000)垫后
var a = elem.getAttribute("ms-skip")
var b = elem.getAttributeNode("ms-important")
var c = elem.getAttributeNode("ms-controller")
if (typeof a === "string") {
return
} else if (node = b || c) {
var newVmodel = avalon.vmodels[node.value]
if (!newVmodel) {
return
}
//ms-important不包含父VM,ms-controller相反
vmodels = node === b ? [newVmodel] : [newVmodel].concat(vmodels)
elem.removeAttribute(node.name) //removeAttributeNode不会刷新[ms-controller]样式规则
elem.classList.remove(node.name)
createSignalTower(elem, newVmodel)
}
scanAttr(elem, vmodels) //扫描特性节点
}
var rhasHtml = /\|\s*html\s*/,
r11a = /\|\|/g,
rlt = /</g,
rgt = />/g,
rstringLiteral = /(['"])(\\\1|.)+?\1/g
function getToken(value, pos) {
if (value.indexOf("|") > 0) {
var scapegoat = value.replace( rstringLiteral, function(_){
return Array(_.length+1).join("1")// jshint ignore:line
})
var index = scapegoat.replace(r11a, "\u1122\u3344").indexOf("|") //干掉所有短路或
if (index > -1) {
return {
filters: value.slice(index),
value: value.slice(0, index),
pos: pos || 0,
expr: true
}
}
}
return {
value: value,
filters: "",
expr: true
}
}
function scanExpr(str) {
var tokens = [],
value, start = 0,
stop
do {
stop = str.indexOf(openTag, start)
if (stop === -1) {
break
}
value = str.slice(start, stop)
if (value) { // {{ 左边的文本
tokens.push({
value: value,
filters: "",
expr: false
})
}
start = stop + openTag.length
stop = str.indexOf(closeTag, start)
if (stop === -1) {
break
}
value = str.slice(start, stop)
if (value) { //处理{{ }}插值表达式
tokens.push(getToken(value, start))
}
start = stop + closeTag.length
} while (1)
value = str.slice(start)
if (value) { //}} 右边的文本
tokens.push({
value: value,
expr: false,
filters: ""
})
}
return tokens
}
function scanText(textNode, vmodels) {
var bindings = []
if (textNode.nodeType === 8) {
var token = getToken(textNode.nodeValue)
var tokens = [token]
} else {
tokens = scanExpr(textNode.data)
}
if (tokens.length) {
for (var i = 0; token = tokens[i++]; ) {
var node = DOC.createTextNode(token.value) //将文本转换为文本节点,并替换原来的文本节点
if (token.expr) {
token.type = "text"
token.element = node
token.filters = token.filters.replace(rhasHtml, function() {
token.type = "html"
return ""
})// jshint ignore:line
bindings.push(token) //收集带有插值表达式的文本
}
avalonFragment.appendChild(node)
}
textNode.parentNode.replaceChild(avalonFragment, textNode)
if (bindings.length)
executeBindings(bindings, vmodels)
}
}
var bools = ["autofocus,autoplay,async,allowTransparency,checked,controls",
"declare,disabled,defer,defaultChecked,defaultSelected",
"contentEditable,isMap,loop,multiple,noHref,noResize,noShade",
"open,readOnly,selected"
].join(",")
var boolMap = {}
bools.replace(rword, function(name) {
boolMap[name.toLowerCase()] = name
})
var propMap = { //属性名映射
"accept-charset": "acceptCharset",
"char": "ch",
"charoff": "chOff",
"class": "className",
"for": "htmlFor",
"http-equiv": "httpEquiv"
}
var anomaly = ["accessKey,bgColor,cellPadding,cellSpacing,codeBase,codeType,colSpan",
"dateTime,defaultValue,frameBorder,longDesc,maxLength,marginWidth,marginHeight",
"rowSpan,tabIndex,useMap,vSpace,valueType,vAlign"
].join(",")
anomaly.replace(rword, function(name) {
propMap[name.toLowerCase()] = name
})
var rnoscripts = /<noscript.*?>(?:[\s\S]+?)<\/noscript>/img
var rnoscriptText = /<noscript.*?>([\s\S]+?)<\/noscript>/im
var getXHR = function() {
return new(window.XMLHttpRequest || ActiveXObject)("Microsoft.XMLHTTP") // jshint ignore:line
}
var templatePool = avalon.templateCache = {}
bindingHandlers.attr = function(data, vmodels) {
var text = data.value.trim(),
simple = true
if (text.indexOf(openTag) > -1 && text.indexOf(closeTag) > 2) {
simple = false
if (rexpr.test(text) && RegExp.rightContext === "" && RegExp.leftContext === "") {
simple = true
text = RegExp.$1
}
}
if (data.type === "include") {
var elem = data.element
data.includeRendered = getBindingCallback(elem, "data-include-rendered", vmodels)
data.includeLoaded = getBindingCallback(elem, "data-include-loaded", vmodels)
var outer = data.includeReplace = !! avalon(elem).data("includeReplace")
if (avalon(elem).data("includeCache")) {
data.templateCache = {}
}
data.startInclude = DOC.createComment("ms-include")
data.endInclude = DOC.createComment("ms-include-end")
if (outer) {
data.element = data.startInclude
elem.parentNode.insertBefore(data.startInclude, elem)
elem.parentNode.insertBefore(data.endInclude, elem.nextSibling)
} else {
elem.insertBefore(data.startInclude, elem.firstChild)
elem.appendChild(data.endInclude)
}
}
data.handlerName = "attr" //handleName用于处理多种绑定共用同一种bindingExecutor的情况
parseExprProxy(text, vmodels, data, (simple ? 0 : scanExpr(data.value)))
}
bindingExecutors.attr = function(val, elem, data) {
var method = data.type,
attrName = data.param
if (method === "css") {
avalon(elem).css(attrName, val)
} else if (method === "attr") {
// ms-attr-class="xxx" vm.xxx="aaa bbb ccc"将元素的className设置为aaa bbb ccc
// ms-attr-class="xxx" vm.xxx=false 清空元素的所有类名
// ms-attr-name="yyy" vm.yyy="ooo" 为元素设置name属性
var toRemove = (val === false) || (val === null) || (val === void 0)
if (!W3C && propMap[attrName]) { //旧式IE下需要进行名字映射
attrName = propMap[attrName]
}
var bool = boolMap[attrName]
if (typeof elem[bool] === "boolean") {
elem[bool] = !! val //布尔属性必须使用el.xxx = true|false方式设值
if (!val) { //如果为false, IE全系列下相当于setAttribute(xxx,''),会影响到样式,需要进一步处理
toRemove = true
}
}
if (toRemove) {
return elem.removeAttribute(attrName)
}
//SVG只能使用setAttribute(xxx, yyy), VML只能使用elem.xxx = yyy ,HTML的固有属性必须elem.xxx = yyy
var isInnate = rsvg.test(elem) ? false : (DOC.namespaces && isVML(elem)) ? true : attrName in elem.cloneNode(false)
if (isInnate) {
elem[attrName] = val
} else {
elem.setAttribute(attrName, val)
}
} else if (method === "include" && val) {
var vmodels = data.vmodels
var rendered = data.includeRendered
var loaded = data.includeLoaded
var replace = data.includeReplace
var target = replace ? elem.parentNode : elem
var scanTemplate = function(text) {
if (loaded) {
var newText = loaded.apply(target, [text].concat(vmodels))
if (typeof newText === "string")
text = newText
}
if (rendered) {
checkScan(target, function() {
rendered.call(target)
}, NaN)
}
var lastID = data.includeLastID
if (data.templateCache && lastID && lastID !== val) {
var lastTemplate = data.templateCache[lastID]
if (!lastTemplate) {
lastTemplate = data.templateCache[lastID] = DOC.createElement("div")
ifGroup.appendChild(lastTemplate)
}
}
data.includeLastID = val
while (true) {
var node = data.startInclude.nextSibling
if (node && node !== data.endInclude) {
target.removeChild(node)
if (lastTemplate)
lastTemplate.appendChild(node)
} else {
break
}
}
var dom = getTemplateNodes(data, val, text)
var nodes = avalon.slice(dom.childNodes)
target.insertBefore(dom, data.endInclude)
scanNodeArray(nodes, vmodels)
}
if (data.param === "src") {
if (typeof templatePool[val] === "string") {
avalon.nextTick(function() {
scanTemplate(templatePool[val])
})
} else if (Array.isArray(templatePool[val])) { //#805 防止在循环绑定中发出许多相同的请求
templatePool[val].push(scanTemplate)
} else {
var xhr = getXHR()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var s = xhr.status
if (s >= 200 && s < 300 || s === 304 || s === 1223) {
var text = xhr.responseText
for (var f = 0, fn; fn = templatePool[val][f++];) {
fn(text)
}
templatePool[val] = text
}
}
}
templatePool[val] = [scanTemplate]
xhr.open("GET", val, true)
if ("withCredentials" in xhr) {
xhr.withCredentials = true
}
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.send(null)
}
} else {
//IE系列与够新的标准浏览器支持通过ID取得元素(firefox14+)
//http://tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/
var el = val && val.nodeType === 1 ? val : DOC.getElementById(val)
if (el) {
if (el.tagName === "NOSCRIPT" && !(el.innerHTML || el.fixIE78)) { //IE7-8 innerText,innerHTML都无法取得其内容,IE6能取得其innerHTML
xhr = getXHR() //IE9-11与chrome的innerHTML会得到转义的内容,它们的innerText可以
xhr.open("GET", location, false) //谢谢Nodejs 乱炖群 深圳-纯属虚构
xhr.send(null)
//http://bbs.csdn.net/topics/390349046?page=1#post-393492653
var noscripts = DOC.getElementsByTagName("noscript")
var array = (xhr.responseText || "").match(rnoscripts) || []
var n = array.length
for (var i = 0; i < n; i++) {
var tag = noscripts[i]
if (tag) { //IE6-8中noscript标签的innerHTML,innerText是只读的
tag.style.display = "none" //http://haslayout.net/css/noscript-Ghost-Bug
tag.fixIE78 = (array[i].match(rnoscriptText) || ["", " "])[1]
}
}
}
avalon.nextTick(function() {
scanTemplate(el.fixIE78 || el.value || el.innerText || el.innerHTML)
})
}
}
} else {
if (!root.hasAttribute && typeof val === "string" && (method === "src" || method === "href")) {
val = val.replace(/&/g, "&") //处理IE67自动转义的问题
}
elem[method] = val
if (window.chrome && elem.tagName === "EMBED") {
var parent = elem.parentNode //#525 chrome1-37下embed标签动态设置src不能发生请求
var comment = document.createComment("ms-src")
parent.replaceChild(comment, elem)
parent.replaceChild(elem, comment)
}
}
}
function getTemplateNodes(data, id, text) {
var div = data.templateCache && data.templateCache[id]
if (div) {
var dom = DOC.createDocumentFragment(),
firstChild
while (firstChild = div.firstChild) {
dom.appendChild(firstChild)
}
return dom
}
return avalon.parseHTML(text)
}
//这几个指令都可以使用插值表达式,如ms-src="aaa/{{b}}/{{c}}.html"
"title,alt,src,value,css,include,href".replace(rword, function(name) {
bindingHandlers[name] = bindingHandlers.attr
})
//根据VM的属性值或表达式的值切换类名,ms-class="xxx yyy zzz:flag"
//http://www.cnblogs.com/rubylouvre/archive/2012/12/17/2818540.html
bindingHandlers["class"] = function(data, vmodels) {
var oldStyle = data.param,
text = data.value,
rightExpr
data.handlerName = "class"
if (!oldStyle || isFinite(oldStyle)) {
data.param = "" //去掉数字
var noExpr = text.replace(rexprg, function(a) {
return a.replace(/./g, "0")
//return Math.pow(10, a.length - 1) //将插值表达式插入10的N-1次方来占位
})
var colonIndex = noExpr.indexOf(":") //取得第一个冒号的位置
if (colonIndex === -1) { // 比如 ms-class="aaa bbb ccc" 的情况
var className = text
} else { // 比如 ms-class-1="ui-state-active:checked" 的情况
className = text.slice(0, colonIndex)
rightExpr = text.slice(colonIndex + 1)
parseExpr(rightExpr, vmodels, data) //决定是添加还是删除
if (!data.evaluator) {
log("debug: ms-class '" + (rightExpr || "").trim() + "' 不存在于VM中")
return false
} else {
data._evaluator = data.evaluator
data._args = data.args
}
}
var hasExpr = rexpr.test(className) //比如ms-class="width{{w}}"的情况
if (!hasExpr) {
data.immobileClass = className
}
parseExprProxy("", vmodels, data, (hasExpr ? scanExpr(className) : 0))
} else {
data.immobileClass = data.oldStyle = data.param
parseExprProxy(text, vmodels, data)
}
}
bindingExecutors["class"] = function(val, elem, data) {
var $elem = avalon(elem),
method = data.type
if (method === "class" && data.oldStyle) { //如果是旧风格
$elem.toggleClass(data.oldStyle, !! val)
} else {
//如果存在冒号就有求值函数
data.toggleClass = data._evaluator ? !! data._evaluator.apply(elem, data._args) : true
data.newClass = data.immobileClass || val
if (data.oldClass && data.newClass !== data.oldClass) {
$elem.removeClass(data.oldClass)
}
data.oldClass = data.newClass
switch (method) {
case "class":
$elem.toggleClass(data.newClass, data.toggleClass)
break
case "hover":
case "active":
if (!data.hasBindEvent) { //确保只绑定一次
var activate = "mouseenter" //在移出移入时切换类名
var abandon = "mouseleave"
if (method === "active") { //在聚焦失焦中切换类名
elem.tabIndex = elem.tabIndex || -1
activate = "mousedown"
abandon = "mouseup"
var fn0 = $elem.bind("mouseleave", function() {
data.toggleClass && $elem.removeClass(data.newClass)
})
}
var fn1 = $elem.bind(activate, function() {
data.toggleClass && $elem.addClass(data.newClass)
})
var fn2 = $elem.bind(abandon, function() {
data.toggleClass && $elem.removeClass(data.newClass)
})
data.rollback = function() {
$elem.unbind("mouseleave", fn0)
$elem.unbind(activate, fn1)
$elem.unbind(abandon, fn2)
}
data.hasBindEvent = true
}
break;
}
}
}
"hover,active".replace(rword, function(method) {
bindingHandlers[method] = bindingHandlers["class"]
})
//ms-controller绑定已经在scanTag 方法中实现
//ms-css绑定已由ms-attr绑定实现
// bindingHandlers.data 定义在if.js
bindingExecutors.data = function(val, elem, data) {
var key = "data-" + data.param
if (val && typeof val === "object") {
elem[key] = val
} else {
elem.setAttribute(key, String(val))
}
}
//双工绑定
var duplexBinding = bindingHandlers.duplex = function(data, vmodels) {
var elem = data.element,
hasCast
parseExprProxy(data.value, vmodels, data, 0, 1)
data.changed = getBindingCallback(elem, "data-duplex-changed", vmodels) || noop
if (data.evaluator && data.args) {
var params = []
var casting = oneObject("string,number,boolean,checked")
if (elem.type === "radio" && data.param === "") {
data.param = "checked"
}
if (elem.msData) {
elem.msData["ms-duplex"] = data.value
}
data.param.replace(/\w+/g, function(name) {
if (/^(checkbox|radio)$/.test(elem.type) && /^(radio|checked)$/.test(name)) {
if (name === "radio")
log("ms-duplex-radio已经更名为ms-duplex-checked")
name = "checked"
data.isChecked = true
}
if (name === "bool") {
name = "boolean"
log("ms-duplex-bool已经更名为ms-duplex-boolean")
} else if (name === "text") {
name = "string"
log("ms-duplex-text已经更名为ms-duplex-string")
}
if (casting[name]) {
hasCast = true
}
avalon.Array.ensure(params, name)
})
if (!hasCast) {
params.push("string")
}
data.param = params.join("-")
data.bound = function(type, callback) {
if (elem.addEventListener) {
elem.addEventListener(type, callback, false)
} else {
elem.attachEvent("on" + type, callback)
}
var old = data.rollback
data.rollback = function() {
elem.avalonSetter = null
avalon.unbind(elem, type, callback)
old && old()
}
}
for (var i in avalon.vmodels) {
var v = avalon.vmodels[i]
v.$fire("avalon-ms-duplex-init", data)
}
var cpipe = data.pipe || (data.pipe = pipe)
cpipe(null, data, "init")
var tagName = elem.tagName
duplexBinding[tagName] && duplexBinding[tagName](elem, data.evaluator.apply(null, data.args), data)
}
}
//不存在 bindingExecutors.duplex
function fixNull(val) {
return val == null ? "" : val
}
avalon.duplexHooks = {
checked: {
get: function(val, data) {
return !data.element.oldValue
}
},
string: {
get: function(val) { //同步到VM
return val
},
set: fixNull
},
"boolean": {
get: function(val) {
return val === "true"
},
set: fixNull
},
number: {
get: function(val, data) {
var number = parseFloat(val)
if (-val === -number) {
return number
}
var arr = /strong|medium|weak/.exec(data.element.getAttribute("data-duplex-number")) || ["medium"]
switch (arr[0]) {
case "strong":
return 0
case "medium":
return val === "" ? "" : 0
case "weak":
return val
}
},
set: fixNull
}
}
function pipe(val, data, action, e) {
data.param.replace(/\w+/g, function(name) {
var hook = avalon.duplexHooks[name]
if (hook && typeof hook[action] === "function") {
val = hook[action](val, data)
}
})
return val
}
var TimerID, ribbon = []
avalon.tick = function(fn) {
if (ribbon.push(fn) === 1) {
TimerID = setInterval(ticker, 60)
}
}
function ticker() {
for (var n = ribbon.length - 1; n >= 0; n--) {
var el = ribbon[n]
if (el() === false) {
ribbon.splice(n, 1)
}
}
if (!ribbon.length) {
clearInterval(TimerID)
}
}
var watchValueInTimer = noop
var rmsinput = /text|password|hidden/
new function() { // jshint ignore:line
try { //#272 IE9-IE11, firefox
var setters = {}
var aproto = HTMLInputElement.prototype
var bproto = HTMLTextAreaElement.prototype
function newSetter(value) { // jshint ignore:line
if (avalon.contains(root, this)) {
setters[this.tagName].call(this, value)
if (!rmsinput.test(this.type))
return
if (!this.msFocus && this.avalonSetter) {
this.avalonSetter()
}
}
}
var inputProto = HTMLInputElement.prototype
Object.getOwnPropertyNames(inputProto) //故意引发IE6-8等浏览器报错
setters["INPUT"] = Object.getOwnPropertyDescriptor(aproto, "value").set
Object.defineProperty(aproto, "value", {
set: newSetter
})
setters["TEXTAREA"] = Object.getOwnPropertyDescriptor(bproto, "value").set
Object.defineProperty(bproto, "value", {
set: newSetter
})
} catch (e) {
//在chrome 43中 ms-duplex终于不需要使用定时器实现双向绑定了
// http://updates.html5rocks.com/2015/04/DOM-attributes-now-on-the-prototype
// https://docs.google.com/document/d/1jwA8mtClwxI-QJuHT7872Z0pxpZz8PBkf2bGAbsUtqs/edit?pli=1
watchValueInTimer = avalon.tick
}
} // jshint ignore:line
//处理radio, checkbox, text, textarea, password
duplexBinding.INPUT = function(element, evaluator, data) {
var $type = element.type,
bound = data.bound,
$elem = avalon(element),
composing = false
function callback(value) {
data.changed.call(this, value, data)
}
function compositionStart() {
composing = true
}
function compositionEnd() {
composing = false
}
//当value变化时改变model的值
var updateVModel = function() {
if (composing) //处理中文输入法在minlengh下引发的BUG
return
var val = element.oldValue = element.value //防止递归调用形成死循环
var lastValue = data.pipe(val, data, "get")
if ($elem.data("duplexObserve") !== false) {
evaluator(lastValue)
callback.call(element, lastValue)
if ($elem.data("duplex-focus")) {
avalon.nextTick(function() {
element.focus()
})
}
}
}
//当model变化时,它就会改变value的值
data.handler = function() {
var val = data.pipe(evaluator(), data, "set") + ""
if (val !== element.oldValue) {
element.value = val
}
}
if (data.isChecked || $type === "radio") {
updateVModel = function() {
if ($elem.data("duplexObserve") !== false) {
var lastValue = data.pipe(element.value, data, "get")
evaluator(lastValue)
callback.call(element, lastValue)
}
}
data.handler = function() {
var val = evaluator()
var checked = data.isChecked ? !! val : val + "" === element.value
element.checked = element.oldValue = checked
}
bound("click", updateVModel)
} else if ($type === "checkbox") {
updateVModel = function() {
if ($elem.data("duplexObserve") !== false) {
var method = element.checked ? "ensure" : "remove"
var array = evaluator()
if (!Array.isArray(array)) {
log("ms-duplex应用于checkbox上要对应一个数组")
array = [array]
}
avalon.Array[method](array, data.pipe(element.value, data, "get"))
callback.call(element, array)
}
}
data.handler = function() {
var array = [].concat(evaluator()) //强制转换为数组
element.checked = array.indexOf(data.pipe(element.value, data, "get")) > -1
}
bound("change", updateVModel)
} else {
var events = element.getAttribute("data-duplex-event") || "input"
if (element.attributes["data-event"]) {
log("data-event指令已经废弃,请改用data-duplex-event")
}
events.replace(rword, function(name) {
switch (name) {
case "input":
bound("input", updateVModel)
bound("DOMAutoComplete", updateVModel)
if (!IEVersion) {
bound("compositionstart", compositionStart)
bound("compositionend", compositionEnd)
}
break
default:
bound(name, updateVModel)
break
}
})
bound("focus", function() {
element.msFocus = true
})
bound("blur", function() {
element.msFocus = false
})
if (rmsinput.test($type)) {
watchValueInTimer(function() {
if (root.contains(element)) {
if (!element.msFocus && element.oldValue !== element.value) {
updateVModel()
}
} else if (!element.msRetain) {
return false
}
})
}
element.avalonSetter = updateVModel
}
element.oldValue = element.value
avalon.injectBinding(data)
callback.call(element, element.value)
}
duplexBinding.TEXTAREA = duplexBinding.INPUT
duplexBinding.SELECT = function(element, evaluator, data) {
var $elem = avalon(element)
function updateVModel() {
if ($elem.data("duplexObserve") !== false) {
var val = $elem.val() //字符串或字符串数组
if (Array.isArray(val)) {
val = val.map(function(v) {
return data.pipe(v, data, "get")
})
} else {
val = data.pipe(val, data, "get")
}
if (val + "" !== element.oldValue) {
evaluator(val)
}
data.changed.call(element, val, data)
}
}
data.handler = function() {
var val = evaluator()
val = val && val.$model || val
if (Array.isArray(val)) {
if (!element.multiple) {
log("ms-duplex在<select multiple=true>上要求对应一个数组")
}
} else {
if (element.multiple) {
log("ms-duplex在<select multiple=false>不能对应一个数组")
}
}
//必须变成字符串后才能比较
val = Array.isArray(val) ? val.map(String) : val + ""
if (val + "" !== element.oldValue) {
$elem.val(val)
element.oldValue = val + ""
}
}
data.bound("change", updateVModel)
element.msCallback = function() {
avalon.injectBinding(data)
data.changed.call(element, evaluator(), data)
}
}
// bindingHandlers.html 定义在if.js
bindingExecutors.html = function (val, elem, data) {
var isHtmlFilter = elem.nodeType !== 1
var parent = isHtmlFilter ? elem.parentNode : elem
if (!parent)
return
val = val == null ? "" : val
if (data.oldText !== val) {
data.oldText = val
} else {
return
}
if (elem.nodeType === 3) {
var signature = generateID("html")
parent.insertBefore(DOC.createComment(signature), elem)
data.element = DOC.createComment(signature + ":end")
parent.replaceChild(data.element, elem)
elem = data.element
}
if (typeof val !== "object") {//string, number, boolean
var fragment = avalon.parseHTML(String(val))
} else if (val.nodeType === 11) { //将val转换为文档碎片
fragment = val
} else if (val.nodeType === 1 || val.item) {
var nodes = val.nodeType === 1 ? val.childNodes : val.item
fragment = avalonFragment.cloneNode(true)
while (nodes[0]) {
fragment.appendChild(nodes[0])
}
}
nodes = avalon.slice(fragment.childNodes)
//插入占位符, 如果是过滤器,需要有节制地移除指定的数量,如果是html指令,直接清空
if (isHtmlFilter) {
var endValue = elem.nodeValue.slice(0, -4)
while (true) {
var node = elem.previousSibling
if (!node || node.nodeType === 8 && node.nodeValue === endValue) {
break
} else {
parent.removeChild(node)
}
}
parent.insertBefore(fragment, elem)
} else {
avalon.clearHTML(elem).appendChild(fragment)
}
scanNodeArray(nodes, data.vmodels)
}
bindingHandlers["if"] =
bindingHandlers.data =
bindingHandlers.text =
bindingHandlers.html =
function(data, vmodels) {
parseExprProxy(data.value, vmodels, data)
}
bindingExecutors["if"] = function(val, elem, data) {
try {
if(!elem.parentNode) return
} catch(e) {return}
if (val) { //插回DOM树
if (elem.nodeType === 8) {
elem.parentNode.replaceChild(data.template, elem)
// animate.enter(data.template, elem.parentNode)
elem = data.element = data.template //这时可能为null
}
if (elem.getAttribute(data.name)) {
elem.removeAttribute(data.name)
scanAttr(elem, data.vmodels)
}
data.rollback = null
} else { //移出DOM树,并用注释节点占据原位置
if (elem.nodeType === 1) {
var node = data.element = DOC.createComment("ms-if")
elem.parentNode.replaceChild(node, elem)
// animate.leave(elem, node.parentNode, node)
data.template = elem //元素节点
ifGroup.appendChild(elem)
data.rollback = function() {
if (elem.parentNode === ifGroup) {
ifGroup.removeChild(elem)
}
}
}
}
}
//ms-important绑定已经在scanTag 方法中实现
//ms-include绑定已由ms-attr绑定实现
var rdash = /\(([^)]*)\)/
bindingHandlers.on = function(data, vmodels) {
var value = data.value
data.type = "on"
var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
if (typeof bindingHandlers.on[eventType + "Hook"] === "function") {
bindingHandlers.on[eventType + "Hook"](data)
}
if (value.indexOf("(") > 0 && value.indexOf(")") > -1) {
var matched = (value.match(rdash) || ["", ""])[1].trim()
if (matched === "" || matched === "$event") { // aaa() aaa($event)当成aaa处理
value = value.replace(rdash, "")
}
}
parseExprProxy(value, vmodels, data)
}
bindingExecutors.on = function(callback, elem, data) {
callback = function(e) {
var fn = data.evaluator || noop
return fn.apply(this, data.args.concat(e))
}
var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
if (eventType === "scan") {
callback.call(elem, {
type: eventType
})
} else if (typeof data.specialBind === "function") {
data.specialBind(elem, callback)
} else {
var removeFn = avalon.bind(elem, eventType, callback)
}
data.rollback = function() {
if (typeof data.specialUnbind === "function") {
data.specialUnbind()
} else {
avalon.unbind(elem, eventType, removeFn)
}
}
}
bindingHandlers.repeat = function (data, vmodels) {
var type = data.type
parseExprProxy(data.value, vmodels, data, 0, 1)
var freturn = false
try {
var $repeat = data.$repeat = data.evaluator.apply(0, data.args || [])
var xtype = avalon.type($repeat)
if (xtype !== "object" && xtype !== "array") {
freturn = true
avalon.log("warning:" + data.value + "只能是对象或数组")
}
} catch (e) {
freturn = true
}
var arr = data.value.split(".") || []
if (arr.length > 1) {
arr.pop()
var n = arr[0]
for (var i = 0, v; v = vmodels[i++]; ) {
if (v && v.hasOwnProperty(n)) {
var events = v[n].$events || {}
events[subscribers] = events[subscribers] || []
events[subscribers].push(data)
break
}
}
}
var elem = data.element
if (elem.nodeType === 1) {
elem.removeAttribute(data.name)
data.sortedCallback = getBindingCallback(elem, "data-with-sorted", vmodels)
data.renderedCallback = getBindingCallback(elem, "data-" + type + "-rendered", vmodels)
var signature = generateID(type)
var start = DOC.createComment(signature)
var end = DOC.createComment(signature + ":end")
data.signature = signature
data.template = avalonFragment.cloneNode(false)
if (type === "repeat") {
var parent = elem.parentNode
parent.replaceChild(end, elem)
parent.insertBefore(start, end)
data.template.appendChild(elem)
} else {
while (elem.firstChild) {
data.template.appendChild(elem.firstChild)
}
elem.appendChild(start)
elem.appendChild(end)
}
data.element = end
data.handler = bindingExecutors.repeat
data.rollback = function () {
var elem = data.element
if (!elem)
return
data.handler("clear")
}
}
if (freturn) {
return
}
data.$outer = {}
var check0 = "$key"
var check1 = "$val"
if (Array.isArray($repeat)) {
if (!$repeat.$map) {
$repeat.$map = {
el: 1
}
var m = $repeat.length
var $proxy = []
for (i = 0; i < m; i++) {//生成代理VM
$proxy.push(eachProxyAgent(i, $repeat))
}
$repeat.$proxy = $proxy
}
$repeat.$map[data.param || "el"] = 1
check0 = "$first"
check1 = "$last"
}
for (i = 0; v = vmodels[i++]; ) {
if (v.hasOwnProperty(check0) && v.hasOwnProperty(check1)) {
data.$outer = v
break
}
}
var $events = $repeat.$events
var $list = ($events || {})[subscribers]
injectDependency($list, data)
if (xtype === "object") {
data.$with = true
$repeat.$proxy || ($repeat.$proxy = {})
data.handler("append", $repeat)
} else if ($repeat.length) {
data.handler("add", 0, $repeat.length)
}
}
bindingExecutors.repeat = function (method, pos, el) {
if (method) {
var data = this, start, fragment
var end = data.element
var comments = getComments(data)
var parent = end.parentNode
var transation = avalonFragment.cloneNode(false)
switch (method) {
case "add": //在pos位置后添加el数组(pos为插入位置,el为要插入的个数)
var n = pos + el
var fragments = []
var array = data.$repeat
for (var i = pos; i < n; i++) {
var proxy = array.$proxy[i]
proxy.$outer = data.$outer
shimController(data, transation, proxy, fragments)
}
parent.insertBefore(transation, comments[pos] || end)
for (i = 0; fragment = fragments[i++]; ) {
scanNodeArray(fragment.nodes, fragment.vmodels)
fragment.nodes = fragment.vmodels = null
}
break
case "del": //将pos后的el个元素删掉(pos, el都是数字)
sweepNodes(comments[pos], comments[pos + el] || end)
break
case "clear":
start = comments[0]
if (start) {
sweepNodes(start, end)
}
break
case "move":
start = comments[0]
if (start) {
var signature = start.nodeValue
var rooms = []
var room = [],
node
sweepNodes(start, end, function () {
room.unshift(this)
if (this.nodeValue === signature) {
rooms.unshift(room)
room = []
}
})
sortByIndex(rooms, pos)
while (room = rooms.shift()) {
while (node = room.shift()) {
transation.appendChild(node)
}
}
parent.insertBefore(transation, end)
}
break
case "append":
var object = pos //原来第2参数, 被循环对象
var pool = object.$proxy //代理对象组成的hash
var keys = []
fragments = []
for (var key in pool) {
if (!object.hasOwnProperty(key)) {
proxyRecycler(pool[key], withProxyPool) //去掉之前的代理VM
delete(pool[key])
}
}
for (key in object) { //得到所有键名
if (object.hasOwnProperty(key) && key !== "hasOwnProperty" && key !== "$proxy") {
keys.push(key)
}
}
if (data.sortedCallback) { //如果有回调,则让它们排序
var keys2 = data.sortedCallback.call(parent, keys)
if (keys2 && Array.isArray(keys2) && keys2.length) {
keys = keys2
}
}
for (i = 0; key = keys[i++]; ) {
if (key !== "hasOwnProperty") {
pool[key] = withProxyAgent(pool[key], key, data)
shimController(data, transation, pool[key], fragments)
}
}
parent.insertBefore(transation, end)
for (i = 0; fragment = fragments[i++]; ) {
scanNodeArray(fragment.nodes, fragment.vmodels)
fragment.nodes = fragment.vmodels = null
}
break
}
if (method === "clear")
method = "del"
var callback = data.renderedCallback || noop,
args = arguments
checkScan(parent, function () {
callback.apply(parent, args)
if (parent.oldValue && parent.tagName === "SELECT") { //fix #503
avalon(parent).val(parent.oldValue.split(","))
}
}, NaN)
}
}
"with,each".replace(rword, function (name) {
bindingHandlers[name] = bindingHandlers.repeat
})
avalon.pool = eachProxyPool
function shimController(data, transation, proxy, fragments) {
var content = data.template.cloneNode(true)
var nodes = avalon.slice(content.childNodes)
if (!data.$with) {
content.insertBefore(DOC.createComment(data.signature), content.firstChild)
}
transation.appendChild(content)
var nv = [proxy].concat(data.vmodels)
var fragment = {
nodes: nodes,
vmodels: nv
}
fragments.push(fragment)
}
function getComments(data) {
var end = data.element
var signature = end.nodeValue.replace(":end", "")
var node = end.previousSibling
var array = []
while (node) {
if (node.nodeValue === signature) {
array.unshift(node)
}
node = node.previousSibling
}
return array
}
//移除掉start与end之间的节点(保留end)
function sweepNodes(start, end, callback) {
while (true) {
var node = end.previousSibling
if (!node)
break
node.parentNode.removeChild(node)
callback && callback.call(node)
if (node === start) {
break
}
}
}
// 为ms-each,ms-with, ms-repeat会创建一个代理VM,
// 通过它们保持一个下上文,让用户能调用$index,$first,$last,$remove,$key,$val,$outer等属性与方法
// 所有代理VM的产生,消费,收集,存放通过xxxProxyFactory,xxxProxyAgent, recycleProxies,xxxProxyPool实现
var withProxyPool = []
function withProxyFactory() {
var proxy = modelFactory({
$key: "",
$outer: {},
$host: {},
$val: {
get: function () {
return this.$host[this.$key]
},
set: function (val) {
this.$host[this.$key] = val
}
}
}, {
$val: 1
})
proxy.$id = generateID("$proxy$with")
return proxy
}
function withProxyAgent(proxy, key, data) {
proxy = proxy || withProxyPool.pop()
if (!proxy) {
proxy = withProxyFactory()
}
var host = data.$repeat
proxy.$key = key
proxy.$host = host
proxy.$outer = data.$outer
if (host.$events) {
proxy.$events.$val = host.$events[key]
} else {
proxy.$events = {}
}
return proxy
}
function eachProxyRecycler(proxies) {
proxies.forEach(function (proxy) {
proxyRecycler(proxy, eachProxyPool)
})
proxies.length = 0
}
function proxyRecycler(proxy, proxyPool) {
for (var i in proxy.$events) {
if (Array.isArray(proxy.$events[i])) {
proxy.$events[i].forEach(function (data) {
if (typeof data === "object")
disposeData(data)
})// jshint ignore:line
proxy.$events[i].length = 0
}
}
proxy.$host = proxy.$outer = {}
if (proxyPool.unshift(proxy) > kernel.maxRepeatSize) {
proxyPool.pop()
}
}
/*********************************************************************
* 各种指令 *
**********************************************************************/
//ms-skip绑定已经在scanTag 方法中实现
// bindingHandlers.text 定义在if.js
bindingExecutors.text = function(val, elem) {
val = val == null ? "" : val //不在页面上显示undefined null
if (elem.nodeType === 3) { //绑定在文本节点上
try { //IE对游离于DOM树外的节点赋值会报错
elem.data = val
} catch (e) {}
} else { //绑定在特性节点上
elem.textContent = val
}
}
function parseDisplay(nodeName, val) {
//用于取得此类标签的默认display值
var key = "_" + nodeName
if (!parseDisplay[key]) {
var node = DOC.createElement(nodeName)
root.appendChild(node)
if (W3C) {
val = getComputedStyle(node, null).display
} else {
val = node.currentStyle.display
}
root.removeChild(node)
parseDisplay[key] = val
}
return parseDisplay[key]
}
avalon.parseDisplay = parseDisplay
bindingHandlers.visible = function(data, vmodels) {
var elem = avalon(data.element)
var display = elem.css("display")
if (display === "none") {
var style = elem[0].style
var has = /visibility/i.test(style.cssText)
var visible = elem.css("visibility")
style.display = ""
style.visibility = "hidden"
display = elem.css("display")
if (display === "none") {
display = parseDisplay(elem[0].nodeName)
}
style.visibility = has ? visible : ""
}
data.display = display
parseExprProxy(data.value, vmodels, data)
}
bindingExecutors.visible = function(val, elem, data) {
elem.style.display = val ? data.display : "none"
}
bindingHandlers.widget = function(data, vmodels) {
var args = data.value.match(rword)
var elem = data.element
var widget = args[0]
var id = args[1]
if (!id || id === "$") { //没有定义或为$时,取组件名+随机数
id = generateID(widget)
}
var optName = args[2] || widget //没有定义,取组件名
var constructor = avalon.ui[widget]
if (typeof constructor === "function") { //ms-widget="tabs,tabsAAA,optname"
vmodels = elem.vmodels || vmodels
for (var i = 0, v; v = vmodels[i++];) {
if (v.hasOwnProperty(optName) && typeof v[optName] === "object") {
var vmOptions = v[optName]
vmOptions = vmOptions.$model || vmOptions
break
}
}
if (vmOptions) {
var wid = vmOptions[widget + "Id"]
if (typeof wid === "string") {
log("warning!不再支持" + widget + "Id")
id = wid
}
}
//抽取data-tooltip-text、data-tooltip-attr属性,组成一个配置对象
var widgetData = avalon.getWidgetData(elem, widget)
data.value = [widget, id, optName].join(",")
data[widget + "Id"] = id
data.evaluator = noop
elem.msData["ms-widget-id"] = id
var options = data[widget + "Options"] = avalon.mix({}, constructor.defaults, vmOptions || {}, widgetData)
elem.removeAttribute("ms-widget")
var vmodel = constructor(elem, data, vmodels) || {} //防止组件不返回VM
if (vmodel.$id) {
avalon.vmodels[id] = vmodel
createSignalTower(elem, vmodel)
try {
vmodel.$init(function() {
avalon.scan(elem, [vmodel].concat(vmodels))
if (typeof options.onInit === "function") {
options.onInit.call(elem, vmodel, options, vmodels)
}
})
} catch (e) {}
data.rollback = function() {
try {
vmodel.widgetElement = null
vmodel.$remove()
} catch (e) {}
elem.msData = {}
delete avalon.vmodels[vmodel.$id]
}
injectDisposeQueue(data, widgetList)
if (window.chrome) {
elem.addEventListener("DOMNodeRemovedFromDocument", function() {
setTimeout(rejectDisposeQueue)
})
}
} else {
avalon.scan(elem, vmodels)
}
} else if (vmodels.length) { //如果该组件还没有加载,那么保存当前的vmodels
elem.vmodels = vmodels
}
}
var widgetList = []
//不存在 bindingExecutors.widget
/*********************************************************************
* 自带过滤器 *
**********************************************************************/
var rscripts = /<script[^>]*>([\S\s]*?)<\/script\s*>/gim
var ron = /\s+(on[^=\s]+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g
var ropen = /<\w+\b(?:(["'])[^"]*?(\1)|[^>])*>/ig
var rsanitize = {
a: /\b(href)\=("javascript[^"]*"|'javascript[^']*')/ig,
img: /\b(src)\=("javascript[^"]*"|'javascript[^']*')/ig,
form: /\b(action)\=("javascript[^"]*"|'javascript[^']*')/ig
}
var rsurrogate = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
var rnoalphanumeric = /([^\#-~| |!])/g;
function numberFormat(number, decimals, point, thousands) {
//form http://phpjs.org/functions/number_format/
//number 必需,要格式化的数字
//decimals 可选,规定多少个小数位。
//point 可选,规定用作小数点的字符串(默认为 . )。
//thousands 可选,规定用作千位分隔符的字符串(默认为 , ),如果设置了该参数,那么所有其他参数都是必需的。
number = (number + '')
.replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 3 : Math.abs(decimals),
sep = thousands || ",",
dec = point || ".",
s = '',
toFixedFix = function(n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
.split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '')
.length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1)
.join('0')
}
return s.join(dec)
}
var filters = avalon.filters = {
uppercase: function(str) {
return str.toUpperCase()
},
lowercase: function(str) {
return str.toLowerCase()
},
truncate: function(str, length, truncation) {
//length,新字符串长度,truncation,新字符串的结尾的字段,返回新字符串
length = length || 30
truncation = typeof truncation === "string" ? truncation : "..."
return str.length > length ? str.slice(0, length - truncation.length) + truncation : String(str)
},
$filter: function(val) {
for (var i = 1, n = arguments.length; i < n; i++) {
var array = arguments[i]
var fn = avalon.filters[array.shift()]
if (typeof fn === "function") {
var arr = [val].concat(array)
val = fn.apply(null, arr)
}
}
return val
},
camelize: camelize,
//https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// <a href="javasc
ript:alert('XSS')">chrome</a>
// <a href="data:text/html;base64, PGltZyBzcmM9eCBvbmVycm9yPWFsZXJ0KDEpPg==">chrome</a>
// <a href="jav ascript:alert('XSS');">IE67chrome</a>
// <a href="jav	ascript:alert('XSS');">IE67chrome</a>
// <a href="jav
ascript:alert('XSS');">IE67chrome</a>
sanitize: function(str) {
return str.replace(rscripts, "").replace(ropen, function(a, b) {
var match = a.toLowerCase().match(/<(\w+)\s/)
if (match) { //处理a标签的href属性,img标签的src属性,form标签的action属性
var reg = rsanitize[match[1]]
if (reg) {
a = a.replace(reg, function(s, name, value) {
var quote = value.charAt(0)
return name + "=" + quote + "javascript:void(0)" + quote// jshint ignore:line
})
}
}
return a.replace(ron, " ").replace(/\s+/g, " ") //移除onXXX事件
})
},
escape: function(str) {
//将字符串经过 str 转义得到适合在页面中显示的内容, 例如替换 < 为 <
return String(str).
replace(/&/g, '&').
replace(rsurrogate, function(value) {
var hi = value.charCodeAt(0)
var low = value.charCodeAt(1)
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'
}).
replace(rnoalphanumeric, function(value) {
return '&#' + value.charCodeAt(0) + ';'
}).
replace(/</g, '<').
replace(/>/g, '>')
},
currency: function(amount, symbol, fractionSize) {
return (symbol || "\uFFE5") + numberFormat(amount, isFinite(fractionSize) ? fractionSize : 2)
},
number: numberFormat
}
/*
'yyyy': 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
'yy': 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
'y': 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
'MMMM': Month in year (January-December)
'MMM': Month in year (Jan-Dec)
'MM': Month in year, padded (01-12)
'M': Month in year (1-12)
'dd': Day in month, padded (01-31)
'd': Day in month (1-31)
'EEEE': Day in Week,(Sunday-Saturday)
'EEE': Day in Week, (Sun-Sat)
'HH': Hour in day, padded (00-23)
'H': Hour in day (0-23)
'hh': Hour in am/pm, padded (01-12)
'h': Hour in am/pm, (1-12)
'mm': Minute in hour, padded (00-59)
'm': Minute in hour (0-59)
'ss': Second in minute, padded (00-59)
's': Second in minute (0-59)
'a': am/pm marker
'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200)
format string can also be one of the following predefined localizable formats:
'medium': equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 pm)
'short': equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 pm)
'fullDate': equivalent to 'EEEE, MMMM d,y' for en_US locale (e.g. Friday, September 3, 2010)
'longDate': equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010
'mediumDate': equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)
'shortDate': equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10)
'mediumTime': equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 pm)
'shortTime': equivalent to 'h:mm a' for en_US locale (e.g. 12:05 pm)
*/
new function() {// jshint ignore:line
function toInt(str) {
return parseInt(str, 10) || 0
}
function padNumber(num, digits, trim) {
var neg = ""
if (num < 0) {
neg = '-'
num = -num
}
num = "" + num
while (num.length < digits)
num = "0" + num
if (trim)
num = num.substr(num.length - digits)
return neg + num
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date["get" + name]()
if (offset > 0 || value > -offset)
value += offset
if (value === 0 && offset === -12) {
value = 12
}
return padNumber(value, size, trim)
}
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date["get" + name]()
var get = (shortForm ? ("SHORT" + name) : name).toUpperCase()
return formats[get][value]
}
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset()
var paddedZone = (zone >= 0) ? "+" : ""
paddedZone += padNumber(Math[zone > 0 ? "floor" : "ceil"](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2)
return paddedZone
}
//取得上午下午
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]
}
var DATE_FORMATS = {
yyyy: dateGetter("FullYear", 4),
yy: dateGetter("FullYear", 2, 0, true),
y: dateGetter("FullYear", 1),
MMMM: dateStrGetter("Month"),
MMM: dateStrGetter("Month", true),
MM: dateGetter("Month", 2, 1),
M: dateGetter("Month", 1, 1),
dd: dateGetter("Date", 2),
d: dateGetter("Date", 1),
HH: dateGetter("Hours", 2),
H: dateGetter("Hours", 1),
hh: dateGetter("Hours", 2, -12),
h: dateGetter("Hours", 1, -12),
mm: dateGetter("Minutes", 2),
m: dateGetter("Minutes", 1),
ss: dateGetter("Seconds", 2),
s: dateGetter("Seconds", 1),
sss: dateGetter("Milliseconds", 3),
EEEE: dateStrGetter("Day"),
EEE: dateStrGetter("Day", true),
a: ampmGetter,
Z: timeZoneGetter
}
var rdateFormat = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/
var raspnetjson = /^\/Date\((\d+)\)\/$/
filters.date = function(date, format) {
var locate = filters.date.locate,
text = "",
parts = [],
fn, match
format = format || "mediumDate"
format = locate[format] || format
if (typeof date === "string") {
if (/^\d+$/.test(date)) {
date = toInt(date)
} else if (raspnetjson.test(date)) {
date = +RegExp.$1
} else {
var trimDate = date.trim()
var dateArray = [0, 0, 0, 0, 0, 0, 0]
var oDate = new Date(0)
//取得年月日
trimDate = trimDate.replace(/^(\d+)\D(\d+)\D(\d+)/, function(_, a, b, c) {
var array = c.length === 4 ? [c, a, b] : [a, b, c]
dateArray[0] = toInt(array[0]) //年
dateArray[1] = toInt(array[1]) - 1 //月
dateArray[2] = toInt(array[2]) //日
return ""
})
var dateSetter = oDate.setFullYear
var timeSetter = oDate.setHours
trimDate = trimDate.replace(/[T\s](\d+):(\d+):?(\d+)?\.?(\d)?/, function(_, a, b, c, d) {
dateArray[3] = toInt(a) //小时
dateArray[4] = toInt(b) //分钟
dateArray[5] = toInt(c) //秒
if (d) { //毫秒
dateArray[6] = Math.round(parseFloat("0." + d) * 1000)
}
return ""
})
var tzHour = 0
var tzMin = 0
trimDate = trimDate.replace(/Z|([+-])(\d\d):?(\d\d)/, function(z, symbol, c, d) {
dateSetter = oDate.setUTCFullYear
timeSetter = oDate.setUTCHours
if (symbol) {
tzHour = toInt(symbol + c)
tzMin = toInt(symbol + d)
}
return ""
})
dateArray[3] -= tzHour
dateArray[4] -= tzMin
dateSetter.apply(oDate, dateArray.slice(0, 3))
timeSetter.apply(oDate, dateArray.slice(3))
date = oDate
}
}
if (typeof date === "number") {
date = new Date(date)
}
if (avalon.type(date) !== "date") {
return
}
while (format) {
match = rdateFormat.exec(format)
if (match) {
parts = parts.concat(match.slice(1))
format = parts.pop()
} else {
parts.push(format)
format = null
}
}
parts.forEach(function(value) {
fn = DATE_FORMATS[value]
text += fn ? fn(date, locate) : value.replace(/(^'|'$)/g, "").replace(/''/g, "'")
})
return text
}
var locate = {
AMPMS: {
0: "上午",
1: "下午"
},
DAY: {
0: "星期日",
1: "星期一",
2: "星期二",
3: "星期三",
4: "星期四",
5: "星期五",
6: "星期六"
},
MONTH: {
0: "1月",
1: "2月",
2: "3月",
3: "4月",
4: "5月",
5: "6月",
6: "7月",
7: "8月",
8: "9月",
9: "10月",
10: "11月",
11: "12月"
},
SHORTDAY: {
"0": "周日",
"1": "周一",
"2": "周二",
"3": "周三",
"4": "周四",
"5": "周五",
"6": "周六"
},
fullDate: "y年M月d日EEEE",
longDate: "y年M月d日",
medium: "yyyy-M-d H:mm:ss",
mediumDate: "yyyy-M-d",
mediumTime: "H:mm:ss",
"short": "yy-M-d ah:mm",
shortDate: "yy-M-d",
shortTime: "ah:mm"
}
locate.SHORTMONTH = locate.MONTH
filters.date.locate = locate
}// jshint ignore:line
/*********************************************************************
* END *
**********************************************************************/
new function () {
avalon.config({
loader: false
})
var fns = [], loaded = DOC.readyState === "complete", fn
function flush(f) {
loaded = 1
while (f = fns.shift())
f()
}
avalon.bind(DOC, "DOMContentLoaded", fn = function () {
avalon.unbind(DOC, "DOMContentLoaded", fn)
flush()
})
var id = setInterval(function () {
if (document.readyState === "complete" && document.body) {
clearInterval(id)
flush()
}
}, 50)
avalon.ready = function (fn) {
loaded ? fn(avalon) : fns.push(fn)
}
avalon.ready(function () {
avalon.scan(DOC.body)
})
}
// Register as a named AMD module, since avalon can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase avalon is used because AMD module names are
// derived from file names, and Avalon is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of avalon, it will work.
// Note that for maximum portability, libraries that are not avalon should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. avalon is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if (typeof define === "function" && define.amd) {
define("avalon", [], function() {
return avalon
})
}
// Map over avalon in case of overwrite
var _avalon = window.avalon
avalon.noConflict = function(deep) {
if (deep && window.avalon === avalon) {
window.avalon = _avalon
}
return avalon
}
// Expose avalon identifiers, even in AMD
// and CommonJS for browser emulators
if (noGlobal === void 0) {
window.avalon = avalon
}
return avalon
}));
|
dada0423/cdnjs
|
ajax/libs/avalon.js/1.4.4/avalon.modern.shim.js
|
JavaScript
|
mit
| 152,012
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Memory
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Value.php 24593 2012-01-05 20:35:02Z matthew $
*/
/**
* String value object
*
* It's an OO string wrapper.
* Used to intercept string updates.
*
* @category Zend
* @package Zend_Memory
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @todo also implement Countable for PHP 5.1 but not yet to stay 5.0 compatible
*/
class Zend_Memory_Value implements ArrayAccess {
/**
* Value
*
* @var string
*/
private $_value;
/**
* Container
*
* @var Zend_Memory_Container_Interface
*/
private $_container;
/**
* Boolean flag which signals to trace value modifications
*
* @var boolean
*/
private $_trace;
/**
* Object constructor
*
* @param string $value
* @param Zend_Memory_Container_Movable $container
*/
public function __construct($value, Zend_Memory_Container_Movable $container)
{
$this->_container = $container;
$this->_value = (string)$value;
/**
* Object is marked as just modified by memory manager
* So we don't need to trace followed object modifications and
* object is processed (and marked as traced) when another
* memory object is modified.
*
* It reduces overall numberr of calls necessary to modification trace
*/
$this->_trace = false;
}
/**
* ArrayAccess interface method
* returns true if string offset exists
*
* @param integer $offset
* @return boolean
*/
public function offsetExists($offset)
{
return $offset >= 0 && $offset < strlen($this->_value);
}
/**
* ArrayAccess interface method
* Get character at $offset position
*
* @param integer $offset
* @return string
*/
public function offsetGet($offset)
{
return $this->_value[$offset];
}
/**
* ArrayAccess interface method
* Set character at $offset position
*
* @param integer $offset
* @param string $char
*/
public function offsetSet($offset, $char)
{
$this->_value[$offset] = $char;
if ($this->_trace) {
$this->_trace = false;
$this->_container->processUpdate();
}
}
/**
* ArrayAccess interface method
* Unset character at $offset position
*
* @param integer $offset
*/
public function offsetUnset($offset)
{
unset($this->_value[$offset]);
if ($this->_trace) {
$this->_trace = false;
$this->_container->processUpdate();
}
}
/**
* To string conversion
*
* @return string
*/
public function __toString()
{
return $this->_value;
}
/**
* Get string value reference
*
* _Must_ be used for value access before PHP v 5.2
* or _may_ be used for performance considerations
*
* @internal
* @return string
*/
public function &getRef()
{
return $this->_value;
}
/**
* Start modifications trace
*
* _Must_ be used for value access before PHP v 5.2
* or _may_ be used for performance considerations
*
* @internal
*/
public function startTrace()
{
$this->_trace = true;
}
}
|
mattsimpson/entrada-1x
|
www-root/core/library/Zend/Memory/Value.php
|
PHP
|
gpl-3.0
| 4,163
|
jQuery.keyboard.language.pt={language:"Portuguese",display:{a:"✔:Aceitar (Shift+Enter)",accept:"Aceitar:Concluir (Shift+Enter)",alt:"AltGr:Carateres Adicionais/CTRL+ALT",b:"←:Retroceder",bksp:"← Bksp:Retroceder",c:"✖:Cancelar/Escape (Esc)",cancel:"Cancel:Cancelar/Escape(Esc)",clear:"C:Limpar",combo:"ö:Acentuação Automática",dec:".:Decimal",e:"↵:Introduzir/Mudar de Linha",enter:"Enter↵:Introduzir/Mudar de Linha",lock:"⇪ Lock:CapsLock/Maiúsculas",s:"⇧:Shift/Maiúsculas",shift:"⇪ Shift:Maiúsculas-Minúsculas",sign:"±:Mudar Sinal",space:" :Espaço",t:"⇥:Tab/Tabela/Avançar",tab:"⇥ Tab:Tabela/Avançar"},wheelMessage:"Use a roda do rato/navegador para ver mais teclas",comboRegex:/([`\'~\^\"ao\u00b4])([a-z])/gim,combos:{"´":{a:"á",A:"Á",e:"é",E:"É",i:"í",I:"Í",o:"ó",O:"Ó",u:"ú",U:"Ú",y:"ý",Y:"Ý"},"'":{}}};
|
dlueth/cdnjs
|
ajax/libs/virtual-keyboard/1.23.5/languages/pt.min.js
|
JavaScript
|
mit
| 857
|
/*
* LCD panel driver for Sharp LS037V7DW01
*
* Copyright (C) 2008 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <plat/display.h>
struct sharp_data {
struct backlight_device *bl;
};
static struct omap_video_timings sharp_ls_timings = {
.x_res = 480,
.y_res = 640,
.pixel_clock = 19200,
.hsw = 2,
.hfp = 1,
.hbp = 28,
.vsw = 1,
.vfp = 1,
.vbp = 1,
};
static int sharp_ls_bl_update_status(struct backlight_device *bl)
{
struct omap_dss_device *dssdev = dev_get_drvdata(&bl->dev);
int level;
if (!dssdev->set_backlight)
return -EINVAL;
if (bl->props.fb_blank == FB_BLANK_UNBLANK &&
bl->props.power == FB_BLANK_UNBLANK)
level = bl->props.brightness;
else
level = 0;
return dssdev->set_backlight(dssdev, level);
}
static int sharp_ls_bl_get_brightness(struct backlight_device *bl)
{
if (bl->props.fb_blank == FB_BLANK_UNBLANK &&
bl->props.power == FB_BLANK_UNBLANK)
return bl->props.brightness;
return 0;
}
static const struct backlight_ops sharp_ls_bl_ops = {
.get_brightness = sharp_ls_bl_get_brightness,
.update_status = sharp_ls_bl_update_status,
};
static int sharp_ls_panel_probe(struct omap_dss_device *dssdev)
{
struct backlight_properties props;
struct backlight_device *bl;
struct sharp_data *sd;
int r;
dssdev->panel.config = OMAP_DSS_LCD_TFT | OMAP_DSS_LCD_IVS |
OMAP_DSS_LCD_IHS;
dssdev->panel.acb = 0x28;
dssdev->panel.timings = sharp_ls_timings;
sd = kzalloc(sizeof(*sd), GFP_KERNEL);
if (!sd)
return -ENOMEM;
dev_set_drvdata(&dssdev->dev, sd);
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = dssdev->max_backlight_level;
props.type = BACKLIGHT_RAW;
bl = backlight_device_register("sharp-ls", &dssdev->dev, dssdev,
&sharp_ls_bl_ops, &props);
if (IS_ERR(bl)) {
r = PTR_ERR(bl);
kfree(sd);
return r;
}
sd->bl = bl;
bl->props.fb_blank = FB_BLANK_UNBLANK;
bl->props.power = FB_BLANK_UNBLANK;
bl->props.brightness = dssdev->max_backlight_level;
r = sharp_ls_bl_update_status(bl);
if (r < 0)
dev_err(&dssdev->dev, "failed to set lcd brightness\n");
return 0;
}
static void sharp_ls_panel_remove(struct omap_dss_device *dssdev)
{
struct sharp_data *sd = dev_get_drvdata(&dssdev->dev);
struct backlight_device *bl = sd->bl;
bl->props.power = FB_BLANK_POWERDOWN;
sharp_ls_bl_update_status(bl);
backlight_device_unregister(bl);
kfree(sd);
}
static int sharp_ls_power_on(struct omap_dss_device *dssdev)
{
int r = 0;
if (dssdev->state == OMAP_DSS_DISPLAY_ACTIVE)
return 0;
r = omapdss_dpi_display_enable(dssdev);
if (r)
goto err0;
/* wait couple of vsyncs until enabling the LCD */
msleep(50);
if (dssdev->platform_enable) {
r = dssdev->platform_enable(dssdev);
if (r)
goto err1;
}
return 0;
err1:
omapdss_dpi_display_disable(dssdev);
err0:
return r;
}
static void sharp_ls_power_off(struct omap_dss_device *dssdev)
{
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE)
return;
if (dssdev->platform_disable)
dssdev->platform_disable(dssdev);
/* wait at least 5 vsyncs after disabling the LCD */
msleep(100);
omapdss_dpi_display_disable(dssdev);
}
static int sharp_ls_panel_enable(struct omap_dss_device *dssdev)
{
int r;
r = sharp_ls_power_on(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
return r;
}
static void sharp_ls_panel_disable(struct omap_dss_device *dssdev)
{
sharp_ls_power_off(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_DISABLED;
}
static int sharp_ls_panel_suspend(struct omap_dss_device *dssdev)
{
sharp_ls_power_off(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_SUSPENDED;
return 0;
}
static int sharp_ls_panel_resume(struct omap_dss_device *dssdev)
{
int r;
r = sharp_ls_power_on(dssdev);
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
return r;
}
static struct omap_dss_driver sharp_ls_driver = {
.probe = sharp_ls_panel_probe,
.remove = sharp_ls_panel_remove,
.enable = sharp_ls_panel_enable,
.disable = sharp_ls_panel_disable,
.suspend = sharp_ls_panel_suspend,
.resume = sharp_ls_panel_resume,
.driver = {
.name = "sharp_ls_panel",
.owner = THIS_MODULE,
},
};
static int __init sharp_ls_panel_drv_init(void)
{
return omap_dss_register_driver(&sharp_ls_driver);
}
static void __exit sharp_ls_panel_drv_exit(void)
{
omap_dss_unregister_driver(&sharp_ls_driver);
}
module_init(sharp_ls_panel_drv_init);
module_exit(sharp_ls_panel_drv_exit);
MODULE_LICENSE("GPL");
|
chaoling/test123
|
linux-2.6.39/drivers/video/omap2/displays/panel-sharp-ls037v7dw01.c
|
C
|
gpl-2.0
| 5,203
|
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#ifndef __CGCOLORSPACE_H
#define __CGCOLORSPACE_H
class __CGColorSpace
{
public:
id isa;
surfaceFormat colorSpace;
char *palette;
int lastColor;
__CGColorSpace(surfaceFormat fmt);
~__CGColorSpace();
};
#endif
|
danielpunkass/WinObjC
|
Frameworks/include/CGColorSpaceInternal.h
|
C
|
mit
| 1,016
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleDependencyTemplateAsRequireId {
apply(dep, source, outputOptions, requestShortener) {
if(!dep.range) return;
const comment = outputOptions.pathinfo ?
`/*! ${requestShortener.shorten(dep.request)} */ ` : "";
let content;
if(dep.module)
content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`;
else
content = require("./WebpackMissingModule").module(dep.request);
source.replace(dep.range[0], dep.range[1] - 1, content);
}
}
module.exports = ModuleDependencyTemplateAsRequireId;
|
shikun2014010800/manga
|
web/console/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js
|
JavaScript
|
mit
| 669
|
/*
* mm/truncate.c - code for taking down pages from address_spaces
*
* Copyright (C) 2002, Linus Torvalds
*
* 10Sep2002 Andrew Morton
* Initial version.
*/
#include <linux/kernel.h>
#include <linux/backing-dev.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/module.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/pagevec.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/buffer_head.h> /* grr. try_to_release_page,
do_invalidatepage */
#include "internal.h"
/**
* do_invalidatepage - invalidate part or all of a page
* @page: the page which is affected
* @offset: the index of the truncation point
*
* do_invalidatepage() is called when all or part of the page has become
* invalidated by a truncate operation.
*
* do_invalidatepage() does not have to release all buffers, but it must
* ensure that no dirty buffer is left outside @offset and that no I/O
* is underway against any of the blocks which are outside the truncation
* point. Because the caller is about to free (and possibly reuse) those
* blocks on-disk.
*/
void do_invalidatepage(struct page *page, unsigned long offset)
{
void (*invalidatepage)(struct page *, unsigned long);
invalidatepage = page->mapping->a_ops->invalidatepage;
#ifdef CONFIG_BLOCK
if (!invalidatepage)
invalidatepage = block_invalidatepage;
#endif
if (invalidatepage)
(*invalidatepage)(page, offset);
}
static inline void truncate_partial_page(struct page *page, unsigned partial)
{
zero_user_segment(page, partial, PAGE_CACHE_SIZE);
if (PagePrivate(page))
do_invalidatepage(page, partial);
}
/*
* This cancels just the dirty bit on the kernel page itself, it
* does NOT actually remove dirty bits on any mmap's that may be
* around. It also leaves the page tagged dirty, so any sync
* activity will still find it on the dirty lists, and in particular,
* clear_page_dirty_for_io() will still look at the dirty bits in
* the VM.
*
* Doing this should *normally* only ever be done when a page
* is truncated, and is not actually mapped anywhere at all. However,
* fs/buffer.c does this when it notices that somebody has cleaned
* out all the buffers on a page without actually doing it through
* the VM. Can you say "ext3 is horribly ugly"? Tought you could.
*/
void cancel_dirty_page(struct page *page, unsigned int account_size)
{
if (TestClearPageDirty(page)) {
struct address_space *mapping = page->mapping;
if (mapping && mapping_cap_account_dirty(mapping)) {
dec_zone_page_state(page, NR_FILE_DIRTY);
dec_bdi_stat(mapping->backing_dev_info,
BDI_RECLAIMABLE);
if (account_size)
task_io_account_cancelled_write(account_size);
}
}
}
EXPORT_SYMBOL(cancel_dirty_page);
/*
* If truncate cannot remove the fs-private metadata from the page, the page
* becomes orphaned. It will be left on the LRU and may even be mapped into
* user pagetables if we're racing with filemap_fault().
*
* We need to bale out if page->mapping is no longer equal to the original
* mapping. This happens a) when the VM reclaimed the page while we waited on
* its lock, b) when a concurrent invalidate_mapping_pages got there first and
* c) when tmpfs swizzles a page between a tmpfs inode and swapper_space.
*/
static void
truncate_complete_page(struct address_space *mapping, struct page *page)
{
if (page->mapping != mapping)
return;
if (PagePrivate(page))
do_invalidatepage(page, 0);
cancel_dirty_page(page, PAGE_CACHE_SIZE);
clear_page_mlock(page);
remove_from_page_cache(page);
ClearPageMappedToDisk(page);
page_cache_release(page); /* pagecache ref */
}
/*
* This is for invalidate_mapping_pages(). That function can be called at
* any time, and is not supposed to throw away dirty pages. But pages can
* be marked dirty at any time too, so use remove_mapping which safely
* discards clean, unused pages.
*
* Returns non-zero if the page was successfully invalidated.
*/
static int
invalidate_complete_page(struct address_space *mapping, struct page *page)
{
int ret;
if (page->mapping != mapping)
return 0;
if (PagePrivate(page) && !try_to_release_page(page, 0))
return 0;
clear_page_mlock(page);
ret = remove_mapping(mapping, page);
return ret;
}
/**
* truncate_inode_pages - truncate range of pages specified by start & end byte offsets
* @mapping: mapping to truncate
* @lstart: offset from which to truncate
* @lend: offset to which to truncate
*
* Truncate the page cache, removing the pages that are between
* specified offsets (and zeroing out partial page
* (if lstart is not page aligned)).
*
* Truncate takes two passes - the first pass is nonblocking. It will not
* block on page locks and it will not block on writeback. The second pass
* will wait. This is to prevent as much IO as possible in the affected region.
* The first pass will remove most pages, so the search cost of the second pass
* is low.
*
* When looking at page->index outside the page lock we need to be careful to
* copy it into a local to avoid races (it could change at any time).
*
* We pass down the cache-hot hint to the page freeing code. Even if the
* mapping is large, it is probably the case that the final pages are the most
* recently touched, and freeing happens in ascending file offset order.
*/
void truncate_inode_pages_range(struct address_space *mapping,
loff_t lstart, loff_t lend)
{
const pgoff_t start = (lstart + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
pgoff_t end;
const unsigned partial = lstart & (PAGE_CACHE_SIZE - 1);
struct pagevec pvec;
pgoff_t next;
int i;
if (mapping->nrpages == 0)
return;
BUG_ON((lend & (PAGE_CACHE_SIZE - 1)) != (PAGE_CACHE_SIZE - 1));
end = (lend >> PAGE_CACHE_SHIFT);
pagevec_init(&pvec, 0);
next = start;
while (next <= end &&
pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
for (i = 0; i < pagevec_count(&pvec); i++) {
struct page *page = pvec.pages[i];
pgoff_t page_index = page->index;
if (page_index > end) {
next = page_index;
break;
}
if (page_index > next)
next = page_index;
next++;
if (!trylock_page(page))
continue;
if (PageWriteback(page)) {
unlock_page(page);
continue;
}
if (page_mapped(page)) {
unmap_mapping_range(mapping,
(loff_t)page_index<<PAGE_CACHE_SHIFT,
PAGE_CACHE_SIZE, 0);
}
truncate_complete_page(mapping, page);
unlock_page(page);
}
pagevec_release(&pvec);
cond_resched();
}
if (partial) {
struct page *page = find_lock_page(mapping, start - 1);
if (page) {
wait_on_page_writeback(page);
truncate_partial_page(page, partial);
unlock_page(page);
page_cache_release(page);
}
}
next = start;
for ( ; ; ) {
cond_resched();
if (!pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
if (next == start)
break;
next = start;
continue;
}
if (pvec.pages[0]->index > end) {
pagevec_release(&pvec);
break;
}
for (i = 0; i < pagevec_count(&pvec); i++) {
struct page *page = pvec.pages[i];
if (page->index > end)
break;
lock_page(page);
wait_on_page_writeback(page);
if (page_mapped(page)) {
unmap_mapping_range(mapping,
(loff_t)page->index<<PAGE_CACHE_SHIFT,
PAGE_CACHE_SIZE, 0);
}
if (page->index > next)
next = page->index;
next++;
truncate_complete_page(mapping, page);
unlock_page(page);
}
pagevec_release(&pvec);
}
}
EXPORT_SYMBOL(truncate_inode_pages_range);
/**
* truncate_inode_pages - truncate *all* the pages from an offset
* @mapping: mapping to truncate
* @lstart: offset from which to truncate
*
* Called under (and serialised by) inode->i_mutex.
*/
void truncate_inode_pages(struct address_space *mapping, loff_t lstart)
{
truncate_inode_pages_range(mapping, lstart, (loff_t)-1);
}
EXPORT_SYMBOL(truncate_inode_pages);
unsigned long __invalidate_mapping_pages(struct address_space *mapping,
pgoff_t start, pgoff_t end, bool be_atomic)
{
struct pagevec pvec;
pgoff_t next = start;
unsigned long ret = 0;
int i;
pagevec_init(&pvec, 0);
while (next <= end &&
pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) {
for (i = 0; i < pagevec_count(&pvec); i++) {
struct page *page = pvec.pages[i];
pgoff_t index;
int lock_failed;
lock_failed = !trylock_page(page);
/*
* We really shouldn't be looking at the ->index of an
* unlocked page. But we're not allowed to lock these
* pages. So we rely upon nobody altering the ->index
* of this (pinned-by-us) page.
*/
index = page->index;
if (index > next)
next = index;
next++;
if (lock_failed)
continue;
if (PageDirty(page) || PageWriteback(page))
goto unlock;
if (page_mapped(page))
goto unlock;
ret += invalidate_complete_page(mapping, page);
unlock:
unlock_page(page);
if (next > end)
break;
}
pagevec_release(&pvec);
if (likely(!be_atomic))
cond_resched();
}
return ret;
}
/**
* invalidate_mapping_pages - Invalidate all the unlocked pages of one inode
* @mapping: the address_space which holds the pages to invalidate
* @start: the offset 'from' which to invalidate
* @end: the offset 'to' which to invalidate (inclusive)
*
* This function only removes the unlocked pages, if you want to
* remove all the pages of one inode, you must call truncate_inode_pages.
*
* invalidate_mapping_pages() will not block on IO activity. It will not
* invalidate pages which are dirty, locked, under writeback or mapped into
* pagetables.
*/
unsigned long invalidate_mapping_pages(struct address_space *mapping,
pgoff_t start, pgoff_t end)
{
return __invalidate_mapping_pages(mapping, start, end, false);
}
EXPORT_SYMBOL(invalidate_mapping_pages);
/*
* This is like invalidate_complete_page(), except it ignores the page's
* refcount. We do this because invalidate_inode_pages2() needs stronger
* invalidation guarantees, and cannot afford to leave pages behind because
* shrink_page_list() has a temp ref on them, or because they're transiently
* sitting in the lru_cache_add() pagevecs.
*/
static int
invalidate_complete_page2(struct address_space *mapping, struct page *page)
{
if (page->mapping != mapping)
return 0;
if (PagePrivate(page) && !try_to_release_page(page, GFP_KERNEL))
return 0;
spin_lock_irq(&mapping->tree_lock);
if (PageDirty(page))
goto failed;
clear_page_mlock(page);
BUG_ON(PagePrivate(page));
__remove_from_page_cache(page);
spin_unlock_irq(&mapping->tree_lock);
page_cache_release(page); /* pagecache ref */
return 1;
failed:
spin_unlock_irq(&mapping->tree_lock);
return 0;
}
static int do_launder_page(struct address_space *mapping, struct page *page)
{
if (!PageDirty(page))
return 0;
if (page->mapping != mapping || mapping->a_ops->launder_page == NULL)
return 0;
return mapping->a_ops->launder_page(page);
}
/**
* invalidate_inode_pages2_range - remove range of pages from an address_space
* @mapping: the address_space
* @start: the page offset 'from' which to invalidate
* @end: the page offset 'to' which to invalidate (inclusive)
*
* Any pages which are found to be mapped into pagetables are unmapped prior to
* invalidation.
*
* Returns -EBUSY if any pages could not be invalidated.
*/
int invalidate_inode_pages2_range(struct address_space *mapping,
pgoff_t start, pgoff_t end)
{
struct pagevec pvec;
pgoff_t next;
int i;
int ret = 0;
int ret2 = 0;
int did_range_unmap = 0;
int wrapped = 0;
pagevec_init(&pvec, 0);
next = start;
while (next <= end && !wrapped &&
pagevec_lookup(&pvec, mapping, next,
min(end - next, (pgoff_t)PAGEVEC_SIZE - 1) + 1)) {
for (i = 0; i < pagevec_count(&pvec); i++) {
struct page *page = pvec.pages[i];
pgoff_t page_index;
lock_page(page);
if (page->mapping != mapping) {
unlock_page(page);
continue;
}
page_index = page->index;
next = page_index + 1;
if (next == 0)
wrapped = 1;
if (page_index > end) {
unlock_page(page);
break;
}
wait_on_page_writeback(page);
if (page_mapped(page)) {
if (!did_range_unmap) {
/*
* Zap the rest of the file in one hit.
*/
unmap_mapping_range(mapping,
(loff_t)page_index<<PAGE_CACHE_SHIFT,
(loff_t)(end - page_index + 1)
<< PAGE_CACHE_SHIFT,
0);
did_range_unmap = 1;
} else {
/*
* Just zap this page
*/
unmap_mapping_range(mapping,
(loff_t)page_index<<PAGE_CACHE_SHIFT,
PAGE_CACHE_SIZE, 0);
}
}
BUG_ON(page_mapped(page));
ret2 = do_launder_page(mapping, page);
if (ret2 == 0) {
if (!invalidate_complete_page2(mapping, page))
ret2 = -EBUSY;
}
if (ret2 < 0)
ret = ret2;
unlock_page(page);
}
pagevec_release(&pvec);
cond_resched();
}
return ret;
}
EXPORT_SYMBOL_GPL(invalidate_inode_pages2_range);
/**
* invalidate_inode_pages2 - remove all pages from an address_space
* @mapping: the address_space
*
* Any pages which are found to be mapped into pagetables are unmapped prior to
* invalidation.
*
* Returns -EIO if any pages could not be invalidated.
*/
int invalidate_inode_pages2(struct address_space *mapping)
{
return invalidate_inode_pages2_range(mapping, 0, -1);
}
EXPORT_SYMBOL_GPL(invalidate_inode_pages2);
|
felixhaedicke/nst-kernel
|
src/mm/truncate.c
|
C
|
gpl-2.0
| 13,303
|
/**
* @author alteredq / http://alteredqualia.com/
*
* AudioObject
*
* - 3d spatialized sound with Doppler-shift effect
*
* - uses Audio API (currently supported in WebKit-based browsers)
* https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
*
* - based on Doppler effect demo from Chromium
* http://chromium.googlecode.com/svn/trunk/samples/audio/doppler.html
*
* - parameters
*
* - listener
* dopplerFactor // A constant used to determine the amount of pitch shift to use when rendering a doppler effect.
* speedOfSound // The speed of sound used for calculating doppler shift. The default value is 343.3 meters / second.
*
* - panner
* refDistance // A reference distance for reducing volume as source move further from the listener.
* maxDistance // The maximum distance between source and listener, after which the volume will not be reduced any further.
* rolloffFactor // Describes how quickly the volume is reduced as source moves away from listener.
* coneInnerAngle // An angle inside of which there will be no volume reduction.
* coneOuterAngle // An angle outside of which the volume will be reduced to a constant value of coneOuterGain.
* coneOuterGain // Amount of volume reduction outside of the coneOuterAngle.
*/
THREE.AudioObject = function ( url, volume, playbackRate, loop ) {
THREE.Object3D.call( this );
if ( playbackRate === undefined ) playbackRate = 1;
if ( volume === undefined ) volume = 1;
if ( loop === undefined ) loop = true;
if ( ! this.context ) {
try {
THREE.AudioObject.prototype.context = new webkitAudioContext();
} catch ( error ) {
console.warn( "THREE.AudioObject: webkitAudioContext not found" );
return this;
}
}
this.directionalSource = false;
this.listener = this.context.listener;
this.panner = this.context.createPanner();
this.source = this.context.createBufferSource();
this.masterGainNode = this.context.createGainNode();
this.dryGainNode = this.context.createGainNode();
// Setup initial gains
this.masterGainNode.gain.value = volume;
this.dryGainNode.gain.value = 3.0;
// Connect dry mix
this.source.connect( this.panner );
this.panner.connect( this.dryGainNode );
this.dryGainNode.connect( this.masterGainNode );
// Connect master gain
this.masterGainNode.connect( this.context.destination );
// Set source parameters and load sound
this.source.playbackRate.value = playbackRate;
this.source.loop = loop;
loadBufferAndPlay( url );
// private properties
var soundPosition = new THREE.Vector3(),
cameraPosition = new THREE.Vector3(),
oldSoundPosition = new THREE.Vector3(),
oldCameraPosition = new THREE.Vector3(),
soundDelta = new THREE.Vector3(),
cameraDelta = new THREE.Vector3(),
soundFront = new THREE.Vector3(),
cameraFront = new THREE.Vector3(),
soundUp = new THREE.Vector3(),
cameraUp = new THREE.Vector3();
var _this = this;
// API
this.setVolume = function ( volume ) {
this.masterGainNode.gain.value = volume;
};
this.update = function ( camera ) {
oldSoundPosition.copy( soundPosition );
oldCameraPosition.copy( cameraPosition );
soundPosition.setFromMatrixPosition( this.matrixWorld );
cameraPosition.setFromMatrixPosition( camera.matrixWorld );
soundDelta.subVectors( soundPosition, oldSoundPosition );
cameraDelta.subVectors( cameraPosition, oldCameraPosition );
cameraUp.copy( camera.up );
cameraFront.set( 0, 0, -1 );
cameraFront.transformDirection( camera.matrixWorld );
this.listener.setPosition( cameraPosition.x, cameraPosition.y, cameraPosition.z );
this.listener.setVelocity( cameraDelta.x, cameraDelta.y, cameraDelta.z );
this.listener.setOrientation( cameraFront.x, cameraFront.y, cameraFront.z, cameraUp.x, cameraUp.y, cameraUp.z );
this.panner.setPosition( soundPosition.x, soundPosition.y, soundPosition.z );
this.panner.setVelocity( soundDelta.x, soundDelta.y, soundDelta.z );
if ( this.directionalSource ) {
soundFront.set( 0, 0, -1 );
soundFront.transformDirection( this.matrixWorld );
soundUp.copy( this.up );
this.panner.setOrientation( soundFront.x, soundFront.y, soundFront.z, soundUp.x, soundUp.y, soundUp.z );
}
};
function loadBufferAndPlay( url ) {
// Load asynchronously
var request = new XMLHttpRequest();
request.open( "GET", url, true );
request.responseType = "arraybuffer";
request.onload = function() {
_this.source.buffer = _this.context.createBuffer( request.response, true );
_this.source.noteOn( 0 );
}
request.send();
}
};
THREE.AudioObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.AudioObject.prototype.constructor = THREE.AudioObject;
THREE.AudioObject.prototype.context = null;
THREE.AudioObject.prototype.type = null;
|
thijskrooswijk/vis
|
threejs/AudioObject.js
|
JavaScript
|
mit
| 4,794
|
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_POWERPC_SECTIONS_H
#define _ASM_POWERPC_SECTIONS_H
#ifdef __KERNEL__
#include <linux/elf.h>
#include <linux/uaccess.h>
#define arch_is_kernel_initmem_freed arch_is_kernel_initmem_freed
#include <asm-generic/sections.h>
extern bool init_mem_is_free;
static inline int arch_is_kernel_initmem_freed(unsigned long addr)
{
if (!init_mem_is_free)
return 0;
return addr >= (unsigned long)__init_begin &&
addr < (unsigned long)__init_end;
}
extern char __head_end[];
#ifdef __powerpc64__
extern char __start_interrupts[];
extern char __end_interrupts[];
extern char __prom_init_toc_start[];
extern char __prom_init_toc_end[];
#ifdef CONFIG_PPC_POWERNV
extern char start_real_trampolines[];
extern char end_real_trampolines[];
extern char start_virt_trampolines[];
extern char end_virt_trampolines[];
#endif
static inline int in_kernel_text(unsigned long addr)
{
if (addr >= (unsigned long)_stext && addr < (unsigned long)__init_end)
return 1;
return 0;
}
static inline unsigned long kernel_toc_addr(void)
{
/* Defined by the linker, see vmlinux.lds.S */
extern unsigned long __toc_start;
/*
* The TOC register (r2) points 32kB into the TOC, so that 64kB of
* the TOC can be addressed using a single machine instruction.
*/
return (unsigned long)(&__toc_start) + 0x8000UL;
}
static inline int overlaps_interrupt_vector_text(unsigned long start,
unsigned long end)
{
unsigned long real_start, real_end;
real_start = __start_interrupts - _stext;
real_end = __end_interrupts - _stext;
return start < (unsigned long)__va(real_end) &&
(unsigned long)__va(real_start) < end;
}
static inline int overlaps_kernel_text(unsigned long start, unsigned long end)
{
return start < (unsigned long)__init_end &&
(unsigned long)_stext < end;
}
#ifdef PPC64_ELF_ABI_v1
#define HAVE_DEREFERENCE_FUNCTION_DESCRIPTOR 1
#undef dereference_function_descriptor
static inline void *dereference_function_descriptor(void *ptr)
{
struct ppc64_opd_entry *desc = ptr;
void *p;
if (!get_kernel_nofault(p, (void *)&desc->funcaddr))
ptr = p;
return ptr;
}
#undef dereference_kernel_function_descriptor
static inline void *dereference_kernel_function_descriptor(void *ptr)
{
if (ptr < (void *)__start_opd || ptr >= (void *)__end_opd)
return ptr;
return dereference_function_descriptor(ptr);
}
#endif /* PPC64_ELF_ABI_v1 */
#endif
#endif /* __KERNEL__ */
#endif /* _ASM_POWERPC_SECTIONS_H */
|
CSE3320/kernel-code
|
linux-5.8/arch/powerpc/include/asm/sections.h
|
C
|
gpl-2.0
| 2,472
|
/*! formstone v0.5.16 [tabs.css] 2015-05-21 | MIT License | formstone.it */
/**
* @class
* @name .fs-tabs-element
* @type element
* @description Target elmement
*/
/**
* @class
* @name .fs-tabs
* @type element
* @description Base widget class
*/
/**
* @class
* @name .fs-tabs.fs-tabs-enabled
* @type modifier
* @description Indicates enabled state
*/
.fs-tabs {
/**
* @class
* @name .fs-tabs-tab
* @type element
* @description Tab handle element
*/
/**
* @class
* @name .fs-tabs-tab.fs-tabs-enabled
* @type modifier
* @description Indicates enabled state
*/
/**
* @class
* @name .fs-tabs-tab.fs-tabs-active
* @type modifier
* @description Indicates active state
*/
/**
* @class
* @name .fs-tabs-tab.fs-tabs-mobile
* @type modifier
* @description Indicates mobile interface
*/
/**
* @class
* @name .fs-tabs-content
* @type element
* @description Tab content element
*/
/**
* @class
* @name .fs-tabs-content.fs-tabs-enabled
* @type modifier
* @description Indicates enabled state
*/
/**
* @class
* @name .fs-tabs-content.fs-tabs-active
* @type modifier
* @description Indicates active state
*/
/**
* @class
* @name .fs-tabs-tab_mobile
* @type element
* @description Mobile tab handle element
*/
/**
* @class
* @name .fs-tabs-tab_mobile.fs-tabs-active
* @type modifier
* @description Indicates active state
*/
}
.fs-tabs.fs-tabs-enabled:after {
clear: both;
content: '';
display: table;
}
.fs-tabs-tab.fs-tabs-enabled {
box-sizing: border-box;
border: none;
cursor: pointer;
}
.fs-tabs-tab.fs-tabs-enabled:focus {
outline: none;
}
.fs-tabs-content.fs-tabs-enabled {
box-sizing: border-box;
display: none;
}
.fs-tabs-content.fs-tabs-enabled:after {
clear: both;
content: '';
display: table;
}
.fs-tabs-content.fs-tabs-active {
display: block;
}
.fs-tabs-tab.fs-tabs-mobile,
.fs-tabs-tab_mobile,
.fs-tabs-tab_mobile.fs-tabs-active {
display: none;
}
.fs-tabs-tab_mobile.fs-tabs-mobile,
.fs-tabs-tab_mobile.fs-tabs-mobile.fs-tabs-active {
display: block;
}
|
gregorypratt/jsdelivr
|
files/formstone/0.5.16/css/tabs.css
|
CSS
|
mit
| 2,165
|
/*
* linux/arch/arm/kernel/signal.c
*
* Copyright (C) 1995-2009 Russell King
*
* 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/errno.h>
#include <linux/signal.h>
#include <linux/personality.h>
#include <linux/uaccess.h>
#include <linux/tracehook.h>
#include <asm/elf.h>
#include <asm/cacheflush.h>
#include <asm/ucontext.h>
#include <asm/unistd.h>
#include <asm/vfp.h>
#include "signal.h"
/*
* For ARM syscalls, we encode the syscall number into the instruction.
*/
#define SWI_SYS_SIGRETURN (0xef000000|(__NR_sigreturn)|(__NR_OABI_SYSCALL_BASE))
#define SWI_SYS_RT_SIGRETURN (0xef000000|(__NR_rt_sigreturn)|(__NR_OABI_SYSCALL_BASE))
/*
* With EABI, the syscall number has to be loaded into r7.
*/
#define MOV_R7_NR_SIGRETURN (0xe3a07000 | (__NR_sigreturn - __NR_SYSCALL_BASE))
#define MOV_R7_NR_RT_SIGRETURN (0xe3a07000 | (__NR_rt_sigreturn - __NR_SYSCALL_BASE))
/*
* For Thumb syscalls, we pass the syscall number via r7. We therefore
* need two 16-bit instructions.
*/
#define SWI_THUMB_SIGRETURN (0xdf00 << 16 | 0x2700 | (__NR_sigreturn - __NR_SYSCALL_BASE))
#define SWI_THUMB_RT_SIGRETURN (0xdf00 << 16 | 0x2700 | (__NR_rt_sigreturn - __NR_SYSCALL_BASE))
const unsigned long sigreturn_codes[7] = {
MOV_R7_NR_SIGRETURN, SWI_SYS_SIGRETURN, SWI_THUMB_SIGRETURN,
MOV_R7_NR_RT_SIGRETURN, SWI_SYS_RT_SIGRETURN, SWI_THUMB_RT_SIGRETURN,
};
#ifdef CONFIG_CRUNCH
static int preserve_crunch_context(struct crunch_sigframe __user *frame)
{
char kbuf[sizeof(*frame) + 8];
struct crunch_sigframe *kframe;
/* the crunch context must be 64 bit aligned */
kframe = (struct crunch_sigframe *)((unsigned long)(kbuf + 8) & ~7);
kframe->magic = CRUNCH_MAGIC;
kframe->size = CRUNCH_STORAGE_SIZE;
crunch_task_copy(current_thread_info(), &kframe->storage);
return __copy_to_user(frame, kframe, sizeof(*frame));
}
static int restore_crunch_context(struct crunch_sigframe __user *frame)
{
char kbuf[sizeof(*frame) + 8];
struct crunch_sigframe *kframe;
/* the crunch context must be 64 bit aligned */
kframe = (struct crunch_sigframe *)((unsigned long)(kbuf + 8) & ~7);
if (__copy_from_user(kframe, frame, sizeof(*frame)))
return -1;
if (kframe->magic != CRUNCH_MAGIC ||
kframe->size != CRUNCH_STORAGE_SIZE)
return -1;
crunch_task_restore(current_thread_info(), &kframe->storage);
return 0;
}
#endif
#ifdef CONFIG_IWMMXT
static int preserve_iwmmxt_context(struct iwmmxt_sigframe *frame)
{
char kbuf[sizeof(*frame) + 8];
struct iwmmxt_sigframe *kframe;
/* the iWMMXt context must be 64 bit aligned */
kframe = (struct iwmmxt_sigframe *)((unsigned long)(kbuf + 8) & ~7);
kframe->magic = IWMMXT_MAGIC;
kframe->size = IWMMXT_STORAGE_SIZE;
iwmmxt_task_copy(current_thread_info(), &kframe->storage);
return __copy_to_user(frame, kframe, sizeof(*frame));
}
static int restore_iwmmxt_context(struct iwmmxt_sigframe *frame)
{
char kbuf[sizeof(*frame) + 8];
struct iwmmxt_sigframe *kframe;
/* the iWMMXt context must be 64 bit aligned */
kframe = (struct iwmmxt_sigframe *)((unsigned long)(kbuf + 8) & ~7);
if (__copy_from_user(kframe, frame, sizeof(*frame)))
return -1;
if (kframe->magic != IWMMXT_MAGIC ||
kframe->size != IWMMXT_STORAGE_SIZE)
return -1;
iwmmxt_task_restore(current_thread_info(), &kframe->storage);
return 0;
}
#endif
#ifdef CONFIG_VFP
static int preserve_vfp_context(struct vfp_sigframe __user *frame)
{
const unsigned long magic = VFP_MAGIC;
const unsigned long size = VFP_STORAGE_SIZE;
int err = 0;
__put_user_error(magic, &frame->magic, err);
__put_user_error(size, &frame->size, err);
if (err)
return -EFAULT;
return vfp_preserve_user_clear_hwstate(&frame->ufp, &frame->ufp_exc);
}
static int restore_vfp_context(struct vfp_sigframe __user *frame)
{
unsigned long magic;
unsigned long size;
int err = 0;
__get_user_error(magic, &frame->magic, err);
__get_user_error(size, &frame->size, err);
if (err)
return -EFAULT;
if (magic != VFP_MAGIC || size != VFP_STORAGE_SIZE)
return -EINVAL;
return vfp_restore_user_hwstate(&frame->ufp, &frame->ufp_exc);
}
#endif
/*
* Do a signal return; undo the signal stack. These are aligned to 64-bit.
*/
struct sigframe {
struct ucontext uc;
unsigned long retcode[2];
};
struct rt_sigframe {
struct siginfo info;
struct sigframe sig;
};
static int restore_sigframe(struct pt_regs *regs, struct sigframe __user *sf)
{
struct aux_sigframe __user *aux;
sigset_t set;
int err;
err = __copy_from_user(&set, &sf->uc.uc_sigmask, sizeof(set));
if (err == 0)
set_current_blocked(&set);
__get_user_error(regs->ARM_r0, &sf->uc.uc_mcontext.arm_r0, err);
__get_user_error(regs->ARM_r1, &sf->uc.uc_mcontext.arm_r1, err);
__get_user_error(regs->ARM_r2, &sf->uc.uc_mcontext.arm_r2, err);
__get_user_error(regs->ARM_r3, &sf->uc.uc_mcontext.arm_r3, err);
__get_user_error(regs->ARM_r4, &sf->uc.uc_mcontext.arm_r4, err);
__get_user_error(regs->ARM_r5, &sf->uc.uc_mcontext.arm_r5, err);
__get_user_error(regs->ARM_r6, &sf->uc.uc_mcontext.arm_r6, err);
__get_user_error(regs->ARM_r7, &sf->uc.uc_mcontext.arm_r7, err);
__get_user_error(regs->ARM_r8, &sf->uc.uc_mcontext.arm_r8, err);
__get_user_error(regs->ARM_r9, &sf->uc.uc_mcontext.arm_r9, err);
__get_user_error(regs->ARM_r10, &sf->uc.uc_mcontext.arm_r10, err);
__get_user_error(regs->ARM_fp, &sf->uc.uc_mcontext.arm_fp, err);
__get_user_error(regs->ARM_ip, &sf->uc.uc_mcontext.arm_ip, err);
__get_user_error(regs->ARM_sp, &sf->uc.uc_mcontext.arm_sp, err);
__get_user_error(regs->ARM_lr, &sf->uc.uc_mcontext.arm_lr, err);
__get_user_error(regs->ARM_pc, &sf->uc.uc_mcontext.arm_pc, err);
__get_user_error(regs->ARM_cpsr, &sf->uc.uc_mcontext.arm_cpsr, err);
err |= !valid_user_regs(regs);
aux = (struct aux_sigframe __user *) sf->uc.uc_regspace;
#ifdef CONFIG_CRUNCH
if (err == 0)
err |= restore_crunch_context(&aux->crunch);
#endif
#ifdef CONFIG_IWMMXT
if (err == 0 && test_thread_flag(TIF_USING_IWMMXT))
err |= restore_iwmmxt_context(&aux->iwmmxt);
#endif
#ifdef CONFIG_VFP
if (err == 0)
err |= restore_vfp_context(&aux->vfp);
#endif
return err;
}
asmlinkage int sys_sigreturn(struct pt_regs *regs)
{
struct sigframe __user *frame;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
/*
* Since we stacked the signal on a 64-bit boundary,
* then 'sp' should be word aligned here. If it's
* not, then the user is trying to mess with us.
*/
if (regs->ARM_sp & 7)
goto badframe;
frame = (struct sigframe __user *)regs->ARM_sp;
if (!access_ok(VERIFY_READ, frame, sizeof (*frame)))
goto badframe;
if (restore_sigframe(regs, frame))
goto badframe;
return regs->ARM_r0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
asmlinkage int sys_rt_sigreturn(struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
/*
* Since we stacked the signal on a 64-bit boundary,
* then 'sp' should be word aligned here. If it's
* not, then the user is trying to mess with us.
*/
if (regs->ARM_sp & 7)
goto badframe;
frame = (struct rt_sigframe __user *)regs->ARM_sp;
if (!access_ok(VERIFY_READ, frame, sizeof (*frame)))
goto badframe;
if (restore_sigframe(regs, &frame->sig))
goto badframe;
if (restore_altstack(&frame->sig.uc.uc_stack))
goto badframe;
return regs->ARM_r0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
static int
setup_sigframe(struct sigframe __user *sf, struct pt_regs *regs, sigset_t *set)
{
struct aux_sigframe __user *aux;
int err = 0;
__put_user_error(regs->ARM_r0, &sf->uc.uc_mcontext.arm_r0, err);
__put_user_error(regs->ARM_r1, &sf->uc.uc_mcontext.arm_r1, err);
__put_user_error(regs->ARM_r2, &sf->uc.uc_mcontext.arm_r2, err);
__put_user_error(regs->ARM_r3, &sf->uc.uc_mcontext.arm_r3, err);
__put_user_error(regs->ARM_r4, &sf->uc.uc_mcontext.arm_r4, err);
__put_user_error(regs->ARM_r5, &sf->uc.uc_mcontext.arm_r5, err);
__put_user_error(regs->ARM_r6, &sf->uc.uc_mcontext.arm_r6, err);
__put_user_error(regs->ARM_r7, &sf->uc.uc_mcontext.arm_r7, err);
__put_user_error(regs->ARM_r8, &sf->uc.uc_mcontext.arm_r8, err);
__put_user_error(regs->ARM_r9, &sf->uc.uc_mcontext.arm_r9, err);
__put_user_error(regs->ARM_r10, &sf->uc.uc_mcontext.arm_r10, err);
__put_user_error(regs->ARM_fp, &sf->uc.uc_mcontext.arm_fp, err);
__put_user_error(regs->ARM_ip, &sf->uc.uc_mcontext.arm_ip, err);
__put_user_error(regs->ARM_sp, &sf->uc.uc_mcontext.arm_sp, err);
__put_user_error(regs->ARM_lr, &sf->uc.uc_mcontext.arm_lr, err);
__put_user_error(regs->ARM_pc, &sf->uc.uc_mcontext.arm_pc, err);
__put_user_error(regs->ARM_cpsr, &sf->uc.uc_mcontext.arm_cpsr, err);
__put_user_error(current->thread.trap_no, &sf->uc.uc_mcontext.trap_no, err);
__put_user_error(current->thread.error_code, &sf->uc.uc_mcontext.error_code, err);
__put_user_error(current->thread.address, &sf->uc.uc_mcontext.fault_address, err);
__put_user_error(set->sig[0], &sf->uc.uc_mcontext.oldmask, err);
err |= __copy_to_user(&sf->uc.uc_sigmask, set, sizeof(*set));
aux = (struct aux_sigframe __user *) sf->uc.uc_regspace;
#ifdef CONFIG_CRUNCH
if (err == 0)
err |= preserve_crunch_context(&aux->crunch);
#endif
#ifdef CONFIG_IWMMXT
if (err == 0 && test_thread_flag(TIF_USING_IWMMXT))
err |= preserve_iwmmxt_context(&aux->iwmmxt);
#endif
#ifdef CONFIG_VFP
if (err == 0)
err |= preserve_vfp_context(&aux->vfp);
#endif
__put_user_error(0, &aux->end_magic, err);
return err;
}
static inline void __user *
get_sigframe(struct ksignal *ksig, struct pt_regs *regs, int framesize)
{
unsigned long sp = sigsp(regs->ARM_sp, ksig);
void __user *frame;
/*
* ATPCS B01 mandates 8-byte alignment
*/
frame = (void __user *)((sp - framesize) & ~7);
/*
* Check that we can actually write to the signal frame.
*/
if (!access_ok(VERIFY_WRITE, frame, framesize))
frame = NULL;
return frame;
}
/*
* translate the signal
*/
static inline int map_sig(int sig)
{
struct thread_info *thread = current_thread_info();
if (sig < 32 && thread->exec_domain && thread->exec_domain->signal_invmap)
sig = thread->exec_domain->signal_invmap[sig];
return sig;
}
static int
setup_return(struct pt_regs *regs, struct ksignal *ksig,
unsigned long __user *rc, void __user *frame)
{
unsigned long handler = (unsigned long)ksig->ka.sa.sa_handler;
unsigned long retcode;
int thumb = 0;
unsigned long cpsr = regs->ARM_cpsr & ~(PSR_f | PSR_E_BIT);
cpsr |= PSR_ENDSTATE;
/*
* Maybe we need to deliver a 32-bit signal to a 26-bit task.
*/
if (ksig->ka.sa.sa_flags & SA_THIRTYTWO)
cpsr = (cpsr & ~MODE_MASK) | USR_MODE;
#ifdef CONFIG_ARM_THUMB
if (elf_hwcap & HWCAP_THUMB) {
/*
* The LSB of the handler determines if we're going to
* be using THUMB or ARM mode for this signal handler.
*/
thumb = handler & 1;
if (thumb) {
cpsr |= PSR_T_BIT;
#if __LINUX_ARM_ARCH__ >= 7
/* clear the If-Then Thumb-2 execution state */
cpsr &= ~PSR_IT_MASK;
#endif
} else
cpsr &= ~PSR_T_BIT;
}
#endif
if (ksig->ka.sa.sa_flags & SA_RESTORER) {
retcode = (unsigned long)ksig->ka.sa.sa_restorer;
} else {
unsigned int idx = thumb << 1;
if (ksig->ka.sa.sa_flags & SA_SIGINFO)
idx += 3;
if (__put_user(sigreturn_codes[idx], rc) ||
__put_user(sigreturn_codes[idx+1], rc+1))
return 1;
if (cpsr & MODE32_BIT) {
/*
* 32-bit code can use the new high-page
* signal return code support.
*/
retcode = KERN_SIGRETURN_CODE + (idx << 2) + thumb;
} else {
/*
* Ensure that the instruction cache sees
* the return code written onto the stack.
*/
flush_icache_range((unsigned long)rc,
(unsigned long)(rc + 2));
retcode = ((unsigned long)rc) + thumb;
}
}
regs->ARM_r0 = map_sig(ksig->sig);
regs->ARM_sp = (unsigned long)frame;
regs->ARM_lr = retcode;
regs->ARM_pc = handler;
regs->ARM_cpsr = cpsr;
return 0;
}
static int
setup_frame(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs)
{
struct sigframe __user *frame = get_sigframe(ksig, regs, sizeof(*frame));
int err = 0;
if (!frame)
return 1;
/*
* Set uc.uc_flags to a value which sc.trap_no would never have.
*/
__put_user_error(0x5ac3c35a, &frame->uc.uc_flags, err);
err |= setup_sigframe(frame, regs, set);
if (err == 0)
err = setup_return(regs, ksig, frame->retcode, frame);
return err;
}
static int
setup_rt_frame(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe __user *frame = get_sigframe(ksig, regs, sizeof(*frame));
int err = 0;
if (!frame)
return 1;
err |= copy_siginfo_to_user(&frame->info, &ksig->info);
__put_user_error(0, &frame->sig.uc.uc_flags, err);
__put_user_error(NULL, &frame->sig.uc.uc_link, err);
err |= __save_altstack(&frame->sig.uc.uc_stack, regs->ARM_sp);
err |= setup_sigframe(&frame->sig, regs, set);
if (err == 0)
err = setup_return(regs, ksig, frame->sig.retcode, frame);
if (err == 0) {
/*
* For realtime signals we must also set the second and third
* arguments for the signal handler.
* -- Peter Maydell <pmaydell@chiark.greenend.org.uk> 2000-12-06
*/
regs->ARM_r1 = (unsigned long)&frame->info;
regs->ARM_r2 = (unsigned long)&frame->sig.uc;
}
return err;
}
/*
* OK, we're invoking a handler
*/
static void handle_signal(struct ksignal *ksig, struct pt_regs *regs)
{
sigset_t *oldset = sigmask_to_save();
int ret;
/*
* Set up the stack frame
*/
if (ksig->ka.sa.sa_flags & SA_SIGINFO)
ret = setup_rt_frame(ksig, oldset, regs);
else
ret = setup_frame(ksig, oldset, regs);
/*
* Check that the resulting registers are actually sane.
*/
ret |= !valid_user_regs(regs);
signal_setup_done(ret, ksig, 0);
}
/*
* Note that 'init' is a special process: it doesn't get signals it doesn't
* want to handle. Thus you cannot kill init even with a SIGKILL even by
* mistake.
*
* Note that we go through the signals twice: once to check the signals that
* the kernel can handle, and then we build all the user-level signal handling
* stack-frames in one go after that.
*/
static int do_signal(struct pt_regs *regs, int syscall)
{
unsigned int retval = 0, continue_addr = 0, restart_addr = 0;
struct ksignal ksig;
int restart = 0;
/*
* If we were from a system call, check for system call restarting...
*/
if (syscall) {
continue_addr = regs->ARM_pc;
restart_addr = continue_addr - (thumb_mode(regs) ? 2 : 4);
retval = regs->ARM_r0;
/*
* Prepare for system call restart. We do this here so that a
* debugger will see the already changed PSW.
*/
switch (retval) {
case -ERESTART_RESTARTBLOCK:
restart -= 2;
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
restart++;
regs->ARM_r0 = regs->ARM_ORIG_r0;
regs->ARM_pc = restart_addr;
break;
}
}
/*
* Get the signal to deliver. When running under ptrace, at this
* point the debugger may change all our registers ...
*/
/*
* Depending on the signal settings we may need to revert the
* decision to restart the system call. But skip this if a
* debugger has chosen to restart at a different PC.
*/
if (get_signal(&ksig)) {
/* handler */
if (unlikely(restart) && regs->ARM_pc == restart_addr) {
if (retval == -ERESTARTNOHAND ||
retval == -ERESTART_RESTARTBLOCK
|| (retval == -ERESTARTSYS
&& !(ksig.ka.sa.sa_flags & SA_RESTART))) {
regs->ARM_r0 = -EINTR;
regs->ARM_pc = continue_addr;
}
}
handle_signal(&ksig, regs);
} else {
/* no handler */
restore_saved_sigmask();
if (unlikely(restart) && regs->ARM_pc == restart_addr) {
regs->ARM_pc = continue_addr;
return restart;
}
}
return 0;
}
asmlinkage int
do_work_pending(struct pt_regs *regs, unsigned int thread_flags, int syscall)
{
do {
if (likely(thread_flags & _TIF_NEED_RESCHED)) {
schedule();
} else {
if (unlikely(!user_mode(regs)))
return 0;
local_irq_enable();
if (thread_flags & _TIF_SIGPENDING) {
int restart = do_signal(regs, syscall);
if (unlikely(restart)) {
/*
* Restart without handlers.
* Deal with it without leaving
* the kernel space.
*/
return restart;
}
syscall = 0;
} else {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
}
}
local_irq_disable();
thread_flags = current_thread_info()->flags;
} while (thread_flags & _TIF_WORK_MASK);
return 0;
}
|
Carlstark/SAMA5D4-XULT
|
linux-at91-linux-3.10/arch/arm/kernel/signal.c
|
C
|
gpl-2.0
| 16,691
|
/*
* Backlight Driver for HP Jornada 680
*
* Copyright (c) 2005 Andriy Skulysh
*
* Based on Sharp's Corgi Backlight Driver
*
* 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.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <cpu/dac.h>
#include <mach/hp6xx.h>
#include <asm/hd64461.h>
#define HP680_MAX_INTENSITY 255
#define HP680_DEFAULT_INTENSITY 10
static int hp680bl_suspended;
static int current_intensity;
static DEFINE_SPINLOCK(bl_lock);
static void hp680bl_send_intensity(struct backlight_device *bd)
{
unsigned long flags;
u16 v;
int intensity = bd->props.brightness;
if (bd->props.power != FB_BLANK_UNBLANK)
intensity = 0;
if (bd->props.fb_blank != FB_BLANK_UNBLANK)
intensity = 0;
if (hp680bl_suspended)
intensity = 0;
spin_lock_irqsave(&bl_lock, flags);
if (intensity && current_intensity == 0) {
sh_dac_enable(DAC_LCD_BRIGHTNESS);
v = inw(HD64461_GPBDR);
v &= ~HD64461_GPBDR_LCDOFF;
outw(v, HD64461_GPBDR);
sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS);
} else if (intensity == 0 && current_intensity != 0) {
sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS);
sh_dac_disable(DAC_LCD_BRIGHTNESS);
v = inw(HD64461_GPBDR);
v |= HD64461_GPBDR_LCDOFF;
outw(v, HD64461_GPBDR);
} else if (intensity) {
sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS);
}
spin_unlock_irqrestore(&bl_lock, flags);
current_intensity = intensity;
}
#ifdef CONFIG_PM
static int hp680bl_suspend(struct platform_device *pdev, pm_message_t state)
{
struct backlight_device *bd = platform_get_drvdata(pdev);
hp680bl_suspended = 1;
hp680bl_send_intensity(bd);
return 0;
}
static int hp680bl_resume(struct platform_device *pdev)
{
struct backlight_device *bd = platform_get_drvdata(pdev);
hp680bl_suspended = 0;
hp680bl_send_intensity(bd);
return 0;
}
#else
#define hp680bl_suspend NULL
#define hp680bl_resume NULL
#endif
static int hp680bl_set_intensity(struct backlight_device *bd)
{
hp680bl_send_intensity(bd);
return 0;
}
static int hp680bl_get_intensity(struct backlight_device *bd)
{
return current_intensity;
}
static const struct backlight_ops hp680bl_ops = {
.get_brightness = hp680bl_get_intensity,
.update_status = hp680bl_set_intensity,
};
static int hp680bl_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct backlight_device *bd;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_RAW;
props.max_brightness = HP680_MAX_INTENSITY;
bd = backlight_device_register("hp680-bl", &pdev->dev, NULL,
&hp680bl_ops, &props);
if (IS_ERR(bd))
return PTR_ERR(bd);
platform_set_drvdata(pdev, bd);
bd->props.brightness = HP680_DEFAULT_INTENSITY;
hp680bl_send_intensity(bd);
return 0;
}
static int hp680bl_remove(struct platform_device *pdev)
{
struct backlight_device *bd = platform_get_drvdata(pdev);
bd->props.brightness = 0;
bd->props.power = 0;
hp680bl_send_intensity(bd);
backlight_device_unregister(bd);
return 0;
}
static struct platform_driver hp680bl_driver = {
.probe = hp680bl_probe,
.remove = hp680bl_remove,
.suspend = hp680bl_suspend,
.resume = hp680bl_resume,
.driver = {
.name = "hp680-bl",
},
};
static struct platform_device *hp680bl_device;
static int __init hp680bl_init(void)
{
int ret;
ret = platform_driver_register(&hp680bl_driver);
if (ret)
return ret;
hp680bl_device = platform_device_register_simple("hp680-bl", -1,
NULL, 0);
if (IS_ERR(hp680bl_device)) {
platform_driver_unregister(&hp680bl_driver);
return PTR_ERR(hp680bl_device);
}
return 0;
}
static void __exit hp680bl_exit(void)
{
platform_device_unregister(hp680bl_device);
platform_driver_unregister(&hp680bl_driver);
}
module_init(hp680bl_init);
module_exit(hp680bl_exit);
MODULE_AUTHOR("Andriy Skulysh <askulysh@gmail.com>");
MODULE_DESCRIPTION("HP Jornada 680 Backlight Driver");
MODULE_LICENSE("GPL");
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/linux-source-3.8.0/drivers/video/backlight/hp680_bl.c
|
C
|
gpl-2.0
| 4,175
|
[?php
require_once(dirname(__FILE__).'/../lib/Base<?php echo ucfirst($this->moduleName) ?>GeneratorConfiguration.class.php');
require_once(dirname(__FILE__).'/../lib/Base<?php echo ucfirst($this->moduleName) ?>GeneratorHelper.class.php');
/**
* <?php echo $this->getModuleName() ?> actions.
*
* @package ##PROJECT_NAME##
* @subpackage <?php echo $this->getModuleName()."\n" ?>
* @author ##AUTHOR_NAME##
* @version SVN: $Id: actions.class.php 31002 2010-09-27 12:04:07Z Kris.Wallsmith $
*/
abstract class <?php echo $this->getGeneratedModuleName() ?>Actions extends <?php echo $this->getActionsBaseClass()."\n" ?>
{
public function preExecute()
{
$this->configuration = new <?php echo $this->getModuleName() ?>GeneratorConfiguration();
if (!$this->getUser()->hasCredential($this->configuration->getCredentials($this->getActionName())))
{
$this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
}
$this->dispatcher->notify(new sfEvent($this, 'admin.pre_execute', array('configuration' => $this->configuration)));
$this->helper = new <?php echo $this->getModuleName() ?>GeneratorHelper();
parent::preExecute();
}
<?php include dirname(__FILE__).'/../../parts/indexAction.php' ?>
<?php if ($this->configuration->hasFilterForm()): ?>
<?php include dirname(__FILE__).'/../../parts/filterAction.php' ?>
<?php endif; ?>
<?php include dirname(__FILE__).'/../../parts/newAction.php' ?>
<?php include dirname(__FILE__).'/../../parts/createAction.php' ?>
<?php include dirname(__FILE__).'/../../parts/editAction.php' ?>
<?php include dirname(__FILE__).'/../../parts/updateAction.php' ?>
<?php include dirname(__FILE__).'/../../parts/deleteAction.php' ?>
<?php if ($this->configuration->getValue('list.batch_actions')): ?>
<?php include dirname(__FILE__).'/../../parts/batchAction.php' ?>
<?php endif; ?>
<?php include dirname(__FILE__).'/../../parts/processFormAction.php' ?>
<?php if ($this->configuration->hasFilterForm()): ?>
<?php include dirname(__FILE__).'/../../parts/filtersAction.php' ?>
<?php endif; ?>
<?php include dirname(__FILE__).'/../../parts/paginationAction.php' ?>
<?php include dirname(__FILE__).'/../../parts/sortingAction.php' ?>
}
|
monokal/docker-orangehrm
|
www/symfony/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/data/generator/sfDoctrineModule/admin/template/actions/actions.class.php
|
PHP
|
gpl-2.0
| 2,247
|
/*!
* tablesorter pager plugin
* updated 5/3/2012
*/
;(function($) {
$.extend({tablesorterPager: new function() {
this.defaults = {
// target the pager markup
container: null,
// use this format: "http:/mydatabase.com?page={page}&size={size}"
// where {page} is replaced by the page number and {size} is replaced by the number of records to show
ajaxUrl: null,
// process ajax so that the following information is returned:
// [ total_rows (number), rows (array of arrays), headers (array; optional) ]
// example:
// [
// 100, // total rows
// [
// [ "row1cell1", "row1cell2", ... "row1cellN" ],
// [ "row2cell1", "row2cell2", ... "row2cellN" ],
// ...
// [ "rowNcell1", "rowNcell2", ... "rowNcellN" ]
// ],
// [ "header1", "header2", ... "headerN" ] // optional
// ]
ajaxProcessing: function(ajax){ return [ 0, [], null ]; },
// output default: '{page}/{totalPages}'
output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}'
// apply disabled classname to the pager arrows when the rows at either extreme is visible
updateArrows: true,
// starting page of the pager (zero based index)
page: 0,
// Number of visible rows
size: 10,
// if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty
// table row set to a height to compensate; default is false
fixedHeight: false,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
removeRows: true, // removing rows in larger tables speeds up the sort
// css class names of pager arrows
cssNext: '.next', // next page arrow
cssPrev: '.prev', // previous page arrow
cssFirst: '.first', // first page arrow
cssLast: '.last', // last page arrow
cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
// class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled: 'disabled', // Note there is no period "." in front of this class name
// stuff not set by the user
totalRows: 0,
totalPages: 0
};
var $this = this,
// hide arrows at extremes
pagerArrows = function(c, disable) {
var a = 'addClass', r = 'removeClass',
d = c.cssDisabled, dis = !!disable;
if (c.updateArrows) {
c.container[(c.totalRows < c.size) ? a : r](d);
$(c.cssFirst + ',' + c.cssPrev, c.container)[(dis || c.page === 0) ? a : r](d);
$(c.cssNext + ',' + c.cssLast, c.container)[(dis || c.page === c.totalPages - 1) ? a : r](d);
}
},
updatePageDisplay = function(table, c) {
if (c.totalPages > 0) {
c.startRow = c.size * (c.page) + 1;
c.endRow = Math.min(c.totalRows, c.size * (c.page+1));
var out = $(c.cssPageDisplay, c.container),
// form the output string
s = c.output.replace(/\{(page|totalPages|startRow|endRow|totalRows)\}/gi, function(m){
return {
'{page}' : c.page + 1,
'{totalPages}' : c.totalPages,
'{startRow}' : c.startRow,
'{endRow}' : c.endRow,
'{totalRows}' : c.totalRows
}[m];
});
if (out[0]) {
out[ (out[0].tagName === 'INPUT') ? 'val' : 'html' ](s);
}
}
pagerArrows(c);
$(table).trigger('pagerComplete', c);
},
fixHeight = function(table, c) {
var d, h, $b = $(table.tBodies[0]);
if (c.fixedHeight) {
$b.find('tr.pagerSavedHeightSpacer').remove();
h = $.data(table, 'pagerSavedHeight');
if (h) {
d = h - $b.height();
if (d > 5 && $.data(table, 'pagerLastSize') === c.size && $b.find('tr:visible').length < c.size) {
$b.append('<tr class="pagerSavedHeightSpacer remove-me" style="height:' + d + 'px;"></tr>');
}
}
}
},
changeHeight = function(table, c) {
var $b = $(table.tBodies[0]);
$b.find('tr.pagerSavedHeightSpacer').remove();
$.data(table, 'pagerSavedHeight', $b.height());
fixHeight(table, c);
$.data(table, 'pagerLastSize', c.size);
},
hideRows = function(table, c){
var i, rows = $('tr:not(.' + table.config.cssChildRow + ')', table.tBodies[0]),
l = rows.length,
s = (c.page * c.size),
e = (s + c.size);
if (e > l) { e = l; }
for (i = 0; i < l; i++){
rows[i].style.display = (i >= s && i < e) ? '' : 'none';
}
},
hideRowsSetup = function(table, c){
c.size = parseInt($(c.cssPageSize, c.container).val(), 10) || c.size;
$.data(table, 'pagerLastSize', c.size);
pagerArrows(c);
if (!c.removeRows) {
hideRows(table, c);
$(table).bind('sortEnd.pager', function(){
hideRows(table, c);
});
}
},
renderAjax = function(data, table, c, exception){
// process data
if (typeof(c.ajaxProcessing) === "function") {
// ajaxProcessing result: [ total, rows, headers ]
var i, j, k, hsh, $f, $sh, $t = $(table), $b = $(table.tBodies[0]),
hl = $t.find('thead th').length, tds = '',
err = '<tr class="remove-me"><td style="text-align: center;" colspan="' + hl + '">' +
(exception ? exception.message + ' (' + exception.name + ')' : 'No rows found') + '</td></tr>',
result = c.ajaxProcessing(data) || [ 0, [] ],
d = result[1] || [], l = d.length, th = result[2];
if (l > 0) {
for ( i=0; i < l; i++ ) {
tds += '<tr>';
for (j=0; j < d[i].length; j++) {
// build tbody cells
tds += '<td>' + d[i][j] + '</td>';
}
tds += '</tr>';
}
}
// only add new header text if the length matches
if (th && th.length === hl) {
hsh = $t.hasClass('hasStickyHeaders');
$sh = $t.find('.' + ((c.widgetOptions && c.widgetOptions.stickyHeaders) || 'tablesorter-stickyheader'));
$f = $t.find('tfoot tr:first').children();
$t.find('thead tr.tablesorter-header th').each(function(j){
var $t = $(this),
// add new test within the first span it finds, or just in the header
tar = ($t.find('span').length) ? $t.find('span:first') : $t;
tar.html(th[j]);
$f.eq(j).html(th[j]);
// update sticky headers
if (hsh && $sh.length){
tar = $sh.find('th').eq(j);
tar = (tar.find('span').length) ? tar.find('span:first') : tar;
tar.html(th[j]);
}
});
}
if (exception) {
// add error row to thead instead of tbody, or clicking on the header will result in a parser error
$t.find('thead').append(err);
} else {
$b.html(tds); // add tbody
}
c.temp.remove(); // remove loading icon
$t.trigger('update');
c.totalRows = result[0] || 0;
c.totalPages = Math.ceil(c.totalRows / c.size);
updatePageDisplay(table, c);
fixHeight(table, c);
$t.trigger('pagerChange', c);
}
},
getAjax = function(table, c){
var $t = $(table),
url = c.ajaxUrl.replace(/\{page\}/g, c.page).replace(/\{size\}/g, c.size);
if (url !== '') {
// loading icon
c.temp = $('<div/>', {
id : 'tablesorterPagerLoading',
width : $t.outerWidth(true),
height: $t.outerHeight(true)
});
$t.before(c.temp);
$(document).ajaxError(function(e, xhr, settings, exception) {
renderAjax(null, table, c, exception);
});
$.getJSON(url, function(data) {
renderAjax(data, table, c);
});
}
},
renderTable = function(table, rows, c) {
var i, j, o,
f = document.createDocumentFragment(),
l = rows.length,
s = (c.page * c.size),
e = (s + c.size);
if (l < 1) { return; } // empty table, abort!
$(table).trigger('pagerChange', c);
if (!c.removeRows) {
hideRows(table, c);
} else {
if (e > rows.length ) {
e = rows.length;
}
$.tablesorter.clearTableBody(table);
for (i = s; i < e; i++) {
o = rows[i];
l = o.length;
for (j = 0; j < l; j++) {
f.appendChild(o[j]);
}
}
table.tBodies[0].appendChild(f);
}
if ( c.page >= c.totalPages ) {
moveToLastPage(table, c);
}
updatePageDisplay(table, c);
if (!c.isDisabled) { fixHeight(table, c); }
},
showAllRows = function(table, c){
if (c.ajax) {
pagerArrows(c, true);
} else {
c.isDisabled = true;
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.page = 0;
c.size = c.totalRows;
c.totalPages = 1;
$('tr.pagerSavedHeightSpacer', table.tBodies[0]).remove();
renderTable(table, table.config.rowsCopy, c);
}
// disable size selector
$(c.cssPageSize, c.container).addClass(c.cssDisabled)[0].disabled = true;
},
moveToPage = function(table, c) {
if (c.isDisabled) { return; }
if (c.page < 0 || c.page > (c.totalPages-1)) {
c.page = 0;
}
$.data(table, 'pagerLastPage', c.page);
if (c.ajax) {
getAjax(table, c);
} else {
renderTable(table, table.config.rowsCopy, c);
}
},
setPageSize = function(table, size, c) {
c.size = size;
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.totalPages = Math.ceil(c.totalRows / c.size);
moveToPage(table, c);
},
moveToFirstPage = function(table, c) {
c.page = 0;
moveToPage(table, c);
},
moveToLastPage = function(table, c) {
c.page = (c.totalPages-1);
moveToPage(table, c);
},
moveToNextPage = function(table, c) {
c.page++;
if (c.page >= (c.totalPages-1)) {
c.page = (c.totalPages-1);
}
moveToPage(table, c);
},
moveToPrevPage = function(table, c) {
c.page--;
if (c.page <= 0) {
c.page = 0;
}
moveToPage(table, c);
},
destroyPager = function(table, c){
showAllRows(table, c);
c.container.hide(); // hide pager
table.config.appender = null; // remove pager appender function
$(table).unbind('destroy.pager sortEnd.pager enable.pager disable.pager');
},
enablePager = function(table, c, triggered){
var p = $(c.cssPageSize, c.container).removeClass(c.cssDisabled).removeAttr('disabled');
c.isDisabled = false;
c.page = $.data(table, 'pagerLastPage') || c.page || 0;
c.size = $.data(table, 'pagerLastSize') || parseInt(p.val(), 10) || c.size;
c.totalPages = Math.ceil(c.totalRows / c.size);
if (triggered) {
$(table).trigger('update');
setPageSize(table, c.size, c);
hideRowsSetup(table, c);
fixHeight(table, c);
}
};
$this.appender = function(table, rows) {
var c = table.config.pager;
if (!c.ajax) {
table.config.rowsCopy = rows;
c.totalRows = rows.length;
c.size = $.data(table, 'pagerLastSize') || c.size;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table, rows, c);
}
};
$this.construct = function(settings) {
return this.each(function() {
var config = this.config,
c = config.pager = $.extend({}, $.tablesorterPager.defaults, settings),
table = this,
$t = $(table),
pager = $(c.container).show(); // added in case the pager is reinitialized after being destroyed.
config.appender = $this.appender;
enablePager(table, c, false);
if (typeof(c.ajaxUrl) === 'string') {
// ajax pager; interact with database
c.ajax = true;
getAjax(table, c);
} else {
c.ajax = false;
// Regular pager; all rows stored in memory
$(this).trigger("appendCache");
hideRowsSetup(table, c);
}
$(c.cssFirst,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToFirstPage(table, c); }
return false;
});
$(c.cssNext,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToNextPage(table, c); }
return false;
});
$(c.cssPrev,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToPrevPage(table, c); }
return false;
});
$(c.cssLast,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToLastPage(table, c); }
return false;
});
$(c.cssPageSize,pager).unbind('change.pager').bind('change.pager', function() {
$(c.cssPageSize,pager).val( $(this).val() ); // in case there are more than one pagers
if (!$(this).hasClass(c.cssDisabled)) {
setPageSize(table, parseInt($(this).val(), 10), c);
changeHeight(table, c);
}
return false;
});
$t
.unbind('disable.pager enable.pager destroy.pager')
.bind('disable.pager', function(){
showAllRows(table, c);
})
.bind('enable.pager', function(){
enablePager(table, c, true);
})
.bind('destroy.pager', function(){
destroyPager(table, c);
});
});
};
}
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery);
|
Dervisevic/cdnjs
|
ajax/libs/jquery.tablesorter/2.2/addons/pager/jquery.tablesorter.pager.js
|
JavaScript
|
mit
| 12,968
|
(function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else {
definition();
}
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite = globall.isFinite;
var defineProperty = function(object, name, method) {
if (!object[name]) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
}
};
var defineProperties = function(object, map) {
Object.keys(map).forEach(function(name) {
defineProperty(object, name, map[name]);
});
};
var sign = function(n) {
return (n < 0) ? -1 : 1;
};
var unique = function(iterable) {
return Array.from(Set.from(iterable));
};
// http://wiki.ecmascript.org/doku.php?id=harmony:string.prototype.repeat
// http://wiki.ecmascript.org/doku.php?id=harmony:string_extras
defineProperties(String.prototype, {
repeat: function(times) {
return new Array(times + 1).join(this);
},
startsWith: function(substring) {
return this.indexOf(substring) === 0;
},
endsWith: function(s) {
var t = String(s);
return this.lastIndexOf(t) === this.length - t.length;
},
contains: function(s) {
return this.indexOf(s) !== -1;
},
toArray: function() {
return this.split('');
}
});
// https://gist.github.com/1074126
defineProperties(Array, {
from: function(iterable) {
var object = Object(iterable);
var array = [];
for (var key = 0, length = object.length >>> 0; key < length; key++) {
if (key in object) {
array[key] = object[key];
}
}
return array;
},
of: function() {
return Array.prototype.slice.call(arguments);
}
});
defineProperties(Number, {
isInteger: function(value) {
return typeof value === 'number' && global_isFinite(value) &&
value > -9007199254740992 && value < 9007199254740992 &&
Math.floor(value) === value;
},
isNaN: function(value) {
return typeof value === 'number' && global_isNaN(value);
},
toInteger: function(value) {
var n = +value;
if (isNaN(n)) return +0;
if (n === 0 || !global_isFinite(n)) return n;
return sign(n) * Math.floor(Math.abs(n));
}
});
defineProperties(Object, {
getOwnPropertyDescriptors: function(subject) {
var descs = {};
Object.getOwnPropertyNames(subject).forEach(function(propName) {
descs[propName] = Object.getOwnPropertyDescriptor(subject, propName);
});
return descs;
},
getPropertyDescriptor: function(subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (pd === undefined && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
},
getPropertyNames: function(subject, name) {
var set = Set.from(Object.getOwnPropertyNames(subject));
var proto = Object.getPrototypeOf(subject);
while (proto !== null) {
Object.getOwnPropertyNames(proto).forEach(set.add);
proto = Object.getPrototypeOf(proto);
}
return Array.from(set);
},
is: function(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
}
});
defineProperties(globall, {
Map: (function() {
var indexOfIdentical = function(keys, key) {
for (var i = 0, length = keys.length; i < length; i++) {
if (Object.is(keys[i], key)) return i;
}
return -1;
};
function Map() {
if (!(this instanceof Map)) return new Map;
defineProperty(this, 'keys', []);
defineProperty(this, 'values', []);
}
defineProperties(Map.prototype, {
get: function(key) {
var index = indexOfIdentical(this.keys, key);
return index < 0 ? undefined : this.values[index];
},
has: function(key) {
return indexOfIdentical(this.keys, key) >= 0;
},
set: function(key, value) {
var keys = this.keys;
var values = this.values;
var index = indexOfIdentical(keys, key);
if (index < 0) index = keys.length;
keys[index] = key;
values[index] = value;
},
'delete': function(key) {
var keys = this.keys;
var values = this.values;
var index = indexOfIdentical(keys, key);
if (index < 0) return false;
keys.splice(index, 1);
values.splice(index, 1);
return true;
}
});
return Map;
// TODO: iteration.
})(),
Set: (function() {
function Set() {
if (!(this instanceof Set)) return new Set;
defineProperty(this, 'map', Map());
}
defineProperties(Set.prototype, {
has: function(key) {
return this.map.has(key);
},
add: function(key) {
this.map.set(key, true);
},
'delete': function(key) {
return this.map.delete(key);
}
});
return Set;
// TODO: iteration.
})()
});
defineProperties(globall.Set, {
from: function(iterable) {
var object = Object(iterable);
var set = Set();
for (var key = 0, length = object.length >>> 0; key < length; key++) {
if (key in object && !(set.has(key))) {
set.add(object[key]);
}
}
return set;
},
of: function() {
return Set.from(arguments);
}
});
});
|
pcarrier/cdnjs
|
ajax/libs/es6-shim/0.1.0/es6-shim.js
|
JavaScript
|
mit
| 6,147
|
<?php
/*
Plugin Name: Grunion Contact Form
Description: Add a contact form to any post, page or text widget. Emails will be sent to the post's author by default, or any email address you choose. As seen on WordPress.com.
Plugin URI: http://automattic.com/#
AUthor: Automattic, Inc.
Author URI: http://automattic.com/
Version: 2.4
License: GPLv2 or later
*/
define( 'GRUNION_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'GRUNION_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
if ( is_admin() )
require_once GRUNION_PLUGIN_DIR . '/admin.php';
/**
* Sets up various actions, filters, post types, post statuses, shortcodes.
*/
class Grunion_Contact_Form_Plugin {
/**
* @var string The Widget ID of the widget currently being processed. Used to build the unique contact-form ID for forms embedded in widgets.
*/
var $current_widget_id;
static $using_contact_form_field = false;
static function init() {
static $instance = false;
if ( !$instance ) {
$instance = new Grunion_Contact_Form_Plugin;
}
return $instance;
}
/**
* Strips HTML tags from input. Output is NOT HTML safe.
*
* @param string $string
* @return string
*/
public static function strip_tags( $string ) {
$string = wp_kses( $string, array() );
return str_replace( '&', '&', $string ); // undo damage done by wp_kses_normalize_entities()
}
function __construct() {
$this->add_shortcode();
// While generating the output of a text widget with a contact-form shortcode, we need to know its widget ID.
add_action( 'dynamic_sidebar', array( $this, 'track_current_widget' ) );
// Add a "widget" shortcode attribute to all contact-form shortcodes embedded in widgets
add_filter( 'widget_text', array( $this, 'widget_atts' ), 0 );
// If Text Widgets don't get shortcode processed, hack ours into place.
if ( !has_filter( 'widget_text', 'do_shortcode' ) )
add_filter( 'widget_text', array( $this, 'widget_shortcode_hack' ), 5 );
// Akismet to the rescue
if ( defined( 'AKISMET_VERSION' ) || function_exists( 'akismet_http_post' ) ) {
add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_akismet' ), 10, 2 );
add_action( 'contact_form_akismet', array( $this, 'akismet_submit' ), 10, 2 );
}
add_action( 'loop_start', array( 'Grunion_Contact_Form', '_style_on' ) );
add_action( 'wp_ajax_grunion-contact-form', array( $this, 'ajax_request' ) );
add_action( 'wp_ajax_nopriv_grunion-contact-form', array( $this, 'ajax_request' ) );
// Export to CSV feature
if ( is_admin() ) {
add_action( 'admin_init', array( $this, 'download_feedback_as_csv' ) );
add_action( 'admin_footer-edit.php', array( $this, 'export_form' ) );
}
// custom post type we'll use to keep copies of the feedback items
register_post_type( 'feedback', array(
'labels' => array(
'name' => __( 'Feedback', 'jetpack' ),
'singular_name' => __( 'Feedback', 'jetpack' ),
'search_items' => __( 'Search Feedback', 'jetpack' ),
'not_found' => __( 'No feedback found', 'jetpack' ),
'not_found_in_trash' => __( 'No feedback found', 'jetpack' )
),
'menu_icon' => GRUNION_PLUGIN_URL . '/images/grunion-menu.png',
'show_ui' => TRUE,
'show_in_admin_bar' => FALSE,
'public' => FALSE,
'rewrite' => FALSE,
'query_var' => FALSE,
'capability_type' => 'page'
) );
// Add to REST API post type whitelist
add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_feedback_rest_api_type' ) );
// Add "spam" as a post status
register_post_status( 'spam', array(
'label' => 'Spam',
'public' => FALSE,
'exclude_from_search' => TRUE,
'show_in_admin_all_list' => FALSE,
'label_count' => _n_noop( 'Spam <span class="count">(%s)</span>', 'Spam <span class="count">(%s)</span>', 'jetpack' ),
'protected' => TRUE,
'_builtin' => FALSE
) );
// POST handler
if (
isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' == strtoupper( $_SERVER['REQUEST_METHOD'] )
&&
isset( $_POST['action'] ) && 'grunion-contact-form' == $_POST['action']
&&
isset( $_POST['contact-form-id'] )
) {
add_action( 'template_redirect', array( $this, 'process_form_submission' ) );
}
/* Can be dequeued by placing the following in wp-content/themes/yourtheme/functions.php
*
* function remove_grunion_style() {
* wp_deregister_style('grunion.css');
* }
* add_action('wp_print_styles', 'remove_grunion_style');
*/
if( is_rtl() ){
wp_register_style( 'grunion.css', GRUNION_PLUGIN_URL . 'css/rtl/grunion-rtl.css', array(), JETPACK__VERSION );
} else {
wp_register_style( 'grunion.css', GRUNION_PLUGIN_URL . 'css/grunion.css', array(), JETPACK__VERSION );
}
}
/**
* Add to REST API post type whitelist
*/
function allow_feedback_rest_api_type( $post_types ) {
$post_types[] = 'feedback';
return $post_types;
}
/**
* Handles all contact-form POST submissions
*
* Conditionally attached to `template_redirect`
*/
function process_form_submission() {
// Add a filter to replace tokens in the subject field with sanitized field values
add_filter( 'contact_form_subject', array( $this, 'replace_tokens_with_input' ), 10, 2 );
$id = stripslashes( $_POST['contact-form-id'] );
if ( is_user_logged_in() ) {
check_admin_referer( "contact-form_{$id}" );
}
$is_widget = 0 === strpos( $id, 'widget-' );
$form = false;
if ( $is_widget ) {
// It's a form embedded in a text widget
$this->current_widget_id = substr( $id, 7 ); // remove "widget-"
$widget_type = implode( '-', array_slice( explode( '-', $this->current_widget_id ), 0, -1 ) ); // Remove trailing -#
// Is the widget active?
$sidebar = is_active_widget( false, $this->current_widget_id, $widget_type );
// This is lame - no core API for getting a widget by ID
$widget = isset( $GLOBALS['wp_registered_widgets'][$this->current_widget_id] ) ? $GLOBALS['wp_registered_widgets'][$this->current_widget_id] : false;
if ( $sidebar && $widget && isset( $widget['callback'] ) ) {
// This is lamer - no API for outputting a given widget by ID
ob_start();
// Process the widget to populate Grunion_Contact_Form::$last
call_user_func( $widget['callback'], array(), $widget['params'][0] );
ob_end_clean();
}
} else {
// It's a form embedded in a post
$post = get_post( $id );
// Process the content to populate Grunion_Contact_Form::$last
apply_filters( 'the_content', $post->post_content );
}
$form = Grunion_Contact_Form::$last;
// No form may mean user is using do_shortcode, grab the form using the stored post meta
if ( ! $form ) {
// Get shortcode from post meta
$shortcode = get_post_meta( $_POST['contact-form-id'], '_g_feedback_shortcode', true );
// Format it
if ( $shortcode != '' ) {
$shortcode = '[contact-form]' . $shortcode . '[/contact-form]';
do_shortcode( $shortcode );
// Recreate form
$form = Grunion_Contact_Form::$last;
}
if ( ! $form ) {
return false;
}
}
if ( is_wp_error( $form->errors ) && $form->errors->get_error_codes() )
return $form->errors;
// Process the form
return $form->process_submission();
}
function ajax_request() {
$submission_result = self::process_form_submission();
if ( ! $submission_result ) {
header( "HTTP/1.1 500 Server Error", 500, true );
echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
esc_html_e( 'An error occurred. Please try again later.', 'jetpack' );
echo '</li></ul></div>';
} elseif ( is_wp_error( $submission_result ) ) {
header( "HTTP/1.1 400 Bad Request", 403, true );
echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
echo esc_html( $submission_result->get_error_message() );
echo '</li></ul></div>';
} else {
echo '<h3>' . esc_html__( 'Message Sent', 'jetpack' ) . '</h3>' . $submission_result;
}
die;
}
/**
* Ensure the post author is always zero for contact-form feedbacks
* Attached to `wp_insert_post_data`
*
* @see Grunion_Contact_Form::process_submission()
*
* @param array $data the data to insert
* @param array $postarr the data sent to wp_insert_post()
* @return array The filtered $data to insert
*/
function insert_feedback_filter( $data, $postarr ) {
if ( $data['post_type'] == 'feedback' && $postarr['post_type'] == 'feedback' ) {
$data['post_author'] = 0;
}
return $data;
}
/*
* Adds our contact-form shortcode
* The "child" contact-field shortcode is enabled as needed by the contact-form shortcode handler
*/
function add_shortcode() {
add_shortcode( 'contact-form', array( 'Grunion_Contact_Form', 'parse' ) );
add_shortcode( 'contact-field', array( 'Grunion_Contact_Form', 'parse_contact_field' ) );
}
static function tokenize_label( $label ) {
return '{' . trim( preg_replace( '#^\d+_#', '', $label ) ) . '}';
}
static function sanitize_value( $value ) {
return preg_replace( '=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $value );
}
/**
* Replaces tokens like {city} or {City} (case insensitive) with the value
* of an input field of that name
*
* @param string $subject
* @param array $field_values Array with field label => field value associations
*
* @return string The filtered $subject with the tokens replaced
*/
function replace_tokens_with_input( $subject, $field_values ) {
// Wrap labels into tokens (inside {})
$wrapped_labels = array_map( array( 'Grunion_Contact_Form_Plugin', 'tokenize_label' ), array_keys( $field_values ) );
// Sanitize all values
$sanitized_values = array_map( array( 'Grunion_Contact_Form_Plugin', 'sanitize_value' ), array_values( $field_values ) );
// Search for all valid tokens (based on existing fields) and replace with the field's value
$subject = str_ireplace( $wrapped_labels, $sanitized_values, $subject );
return $subject;
}
/**
* Tracks the widget currently being processed.
* Attached to `dynamic_sidebar`
*
* @see $current_widget_id
*
* @param array $widget The widget data
*/
function track_current_widget( $widget ) {
$this->current_widget_id = $widget['id'];
}
/**
* Adds a "widget" attribute to every contact-form embedded in a text widget.
* Used to tell the difference between post-embedded contact-forms and widget-embedded contact-forms
* Attached to `widget_text`
*
* @param string $text The widget text
* @return string The filtered widget text
*/
function widget_atts( $text ) {
Grunion_Contact_Form::style( true );
return preg_replace( '/\[contact-form([^a-zA-Z_-])/', '[contact-form widget="' . $this->current_widget_id . '"\\1', $text );
}
/**
* For sites where text widgets are not processed for shortcodes, we add this hack to process just our shortcode
* Attached to `widget_text`
*
* @param string $text The widget text
* @return string The contact-form filtered widget text
*/
function widget_shortcode_hack( $text ) {
if ( !preg_match( '/\[contact-form([^a-zA-Z_-])/', $text ) ) {
return $text;
}
$old = $GLOBALS['shortcode_tags'];
remove_all_shortcodes();
Grunion_Contact_Form_Plugin::$using_contact_form_field = true;
$this->add_shortcode();
$text = do_shortcode( $text );
Grunion_Contact_Form_Plugin::$using_contact_form_field = false;
$GLOBALS['shortcode_tags'] = $old;
return $text;
}
/**
* Populate an array with all values necessary to submit a NEW contact-form feedback to Akismet.
* Note that this includes the current user_ip etc, so this should only be called when accepting a new item via $_POST
*
* @param array $form Contact form feedback array
* @return array feedback array with additional data ready for submission to Akismet
*/
function prepare_for_akismet( $form ) {
$form['comment_type'] = 'contact_form';
$form['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
$form['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$form['referrer'] = $_SERVER['HTTP_REFERER'];
$form['blog'] = get_option( 'home' );
$ignore = array( 'HTTP_COOKIE' );
foreach ( $_SERVER as $k => $value )
if ( !in_array( $k, $ignore ) && is_string( $value ) )
$form["$k"] = $value;
return $form;
}
/**
* Submit contact-form data to Akismet to check for spam.
* If you're accepting a new item via $_POST, run it Grunion_Contact_Form_Plugin::prepare_for_akismet() first
* Attached to `jetpack_contact_form_is_spam`
*
* @param bool $is_spam
* @param array $form
* @return bool|WP_Error TRUE => spam, FALSE => not spam, WP_Error => stop processing entirely
*/
function is_spam_akismet( $is_spam, $form = array() ) {
global $akismet_api_host, $akismet_api_port;
// The signature of this function changed from accepting just $form.
// If something only sends an array, assume it's still using the old
// signature and work around it.
if ( empty( $form ) && is_array( $is_spam ) ) {
$form = $is_spam;
$is_spam = false;
}
// If a previous filter has alrady marked this as spam, trust that and move on.
if ( $is_spam ) {
return $is_spam;
}
if ( !function_exists( 'akismet_http_post' ) && !defined( 'AKISMET_VERSION' ) )
return false;
$query_string = http_build_query( $form );
if ( method_exists( 'Akismet', 'http_post' ) ) {
$response = Akismet::http_post( $query_string, 'comment-check' );
} else {
$response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
}
$result = false;
if ( isset( $response[0]['x-akismet-pro-tip'] ) && 'discard' === trim( $response[0]['x-akismet-pro-tip'] ) && get_option( 'akismet_strictness' ) === '1' )
$result = new WP_Error( 'feedback-discarded', __('Feedback discarded.', 'jetpack' ) );
elseif ( isset( $response[1] ) && 'true' == trim( $response[1] ) ) // 'true' is spam
$result = true;
return apply_filters( 'contact_form_is_spam_akismet', $result, $form );
}
/**
* Submit a feedback as either spam or ham
*
* @param string $as Either 'spam' or 'ham'.
* @param array $form the contact-form data
*/
function akismet_submit( $as, $form ) {
global $akismet_api_host, $akismet_api_port;
if ( !in_array( $as, array( 'ham', 'spam' ) ) )
return false;
$query_string = '';
if ( is_array( $form ) )
$query_string = http_build_query( $form );
if ( method_exists( 'Akismet', 'http_post' ) ) {
$response = Akismet::http_post( $query_string, "submit-{$as}" );
} else {
$response = akismet_http_post( $query_string, $akismet_api_host, "/1.1/submit-{$as}", $akismet_api_port );
}
return trim( $response[1] );
}
/**
* Prints the menu
*/
function export_form() {
if ( get_current_screen()->id != 'edit-feedback' )
return;
if ( ! current_user_can( 'export' ) ) {
return;
}
// if there aren't any feedbacks, bail out
if ( ! (int) wp_count_posts( 'feedback' )->publish )
return;
?>
<div id="feedback-export" style="display:none">
<h2><?php _e( 'Export feedback as CSV', 'jetpack' ) ?></h2>
<div class="clear"></div>
<form action="<?php echo admin_url( 'admin-post.php' ); ?>" method="post" class="form">
<?php wp_nonce_field( 'feedback_export','feedback_export_nonce' ); ?>
<input name="action" value="feedback_export" type="hidden">
<label for="post"><?php _e( 'Select feedback to download', 'jetpack' ) ?></label>
<select name="post">
<option value="all"><?php esc_html_e( 'All posts', 'jetpack' ) ?></option>
<?php echo $this->get_feedbacks_as_options() ?>
</select>
<br><br>
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_html_e( 'Download', 'jetpack' ); ?>">
</form>
</div>
<?php
// There aren't any usable actions in core to output the "export feedback" form in the correct place,
// so this inline JS moves it from the top of the page to the bottom.
?>
<script type='text/javascript'>
var menu = document.getElementById( 'feedback-export' ),
wrapper = document.getElementsByClassName( 'wrap' )[0];
wrapper.appendChild(menu);
menu.style.display = 'block';
</script>
<?php
}
/**
* download as a csv a contact form or all of them in a csv file
*/
function download_feedback_as_csv() {
if ( empty( $_POST['feedback_export_nonce'] ) )
return;
check_admin_referer( 'feedback_export', 'feedback_export_nonce' );
if ( ! current_user_can( 'export' ) ) {
return;
}
$args = array(
'posts_per_page' => -1,
'post_type' => 'feedback',
'post_status' => 'publish',
'order' => 'ASC',
'fields' => 'ids',
'suppress_filters' => false,
);
$filename = date( "Y-m-d" ) . '-feedback-export.csv';
// Check if we want to download all the feedbacks or just a certain contact form
if ( ! empty( $_POST['post'] ) && $_POST['post'] !== 'all' ) {
$args['post_parent'] = (int) $_POST['post'];
$filename = date( "Y-m-d" ) . '-' . str_replace( ' ', '-', get_the_title( (int) $_POST['post'] ) ) . '.csv';
}
$feedbacks = get_posts( $args );
$filename = sanitize_file_name( $filename );
$fields = $this->get_field_names( $feedbacks );
array_unshift( $fields, __( 'Contact Form', 'jetpack' ) );
if ( empty( $feedbacks ) )
return;
// Forces the download of the CSV instead of echoing
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
header( 'Content-Type: text/csv; charset=utf-8' );
$output = fopen( 'php://output', 'w' );
// Prints the header
fputcsv( $output, $fields );
// Create the csv string from the array of post ids
foreach ( $feedbacks as $feedback ) {
fputcsv( $output, self::make_csv_row_from_feedback( $feedback, $fields ) );
}
fclose( $output );
}
/**
* Returns a string of HTML <option> items from an array of posts
*
* @return string a string of HTML <option> items
*/
protected function get_feedbacks_as_options() {
$options = '';
// Get the feedbacks' parents' post IDs
$feedbacks = get_posts( array(
'fields' => 'id=>parent',
'posts_per_page' => 100000,
'post_type' => 'feedback',
'post_status' => 'publish',
'suppress_filters' => false,
) );
$parents = array_unique( array_values( $feedbacks ) );
$posts = get_posts( array(
'orderby' => 'ID',
'posts_per_page' => 1000,
'post_type' => 'any',
'post__in' => array_values( $parents ),
'suppress_filters' => false,
) );
// creates the string of <option> elements
foreach ( $posts as $post ) {
$options .= sprintf( '<option value="%s">%s</option>', esc_attr( $post->ID ), esc_html( $post->post_title ) );
}
return $options;
}
/**
* Get the names of all the form's fields
*
* @param array|int $posts the post we want the fields of
* @return array the array of fields
*/
protected function get_field_names( $posts ) {
$posts = (array) $posts;
$all_fields = array();
foreach ( $posts as $post ){
$fields = self::parse_fields_from_content( $post );
if ( isset( $fields['_feedback_all_fields'] ) ) {
$extra_fields = array_keys( $fields['_feedback_all_fields'] );
$all_fields = array_merge( $all_fields, $extra_fields );
}
}
$all_fields = array_unique( $all_fields );
return $all_fields;
}
public static function parse_fields_from_content( $post_id ) {
static $post_fields;
if ( !is_array( $post_fields ) )
$post_fields = array();
if ( isset( $post_fields[$post_id] ) )
return $post_fields[$post_id];
$all_values = array();
$post_content = get_post_field( 'post_content', $post_id );
$content = explode( '<!--more-->', $post_content );
$lines = array();
if ( count( $content ) > 1 ) {
$content = str_ireplace( array( '<br />', ')</p>' ), '', $content[1] );
$one_line = preg_replace( '/\s+/', ' ', $content );
$one_line = preg_replace( '/.*Array \( (.*)\)/', '$1', $one_line );
preg_match_all( '/\[([^\]]+)\] =\>\; ([^\[]+)/', $one_line, $matches );
if ( count( $matches ) > 1 )
$all_values = array_combine( array_map('trim', $matches[1]), array_map('trim', $matches[2]) );
$lines = array_filter( explode( "\n", $content ) );
}
$var_map = array(
'AUTHOR' => '_feedback_author',
'AUTHOR EMAIL' => '_feedback_author_email',
'AUTHOR URL' => '_feedback_author_url',
'SUBJECT' => '_feedback_subject',
'IP' => '_feedback_ip'
);
$fields = array();
foreach( $lines as $line ) {
$vars = explode( ': ', $line, 2 );
if ( !empty( $vars ) ) {
if ( isset( $var_map[$vars[0]] ) ) {
$fields[$var_map[$vars[0]]] = self::strip_tags( trim( $vars[1] ) );
}
}
}
$fields['_feedback_all_fields'] = $all_values;
$post_fields[$post_id] = $fields;
return $fields;
}
/**
* Creates a valid csv row from a post id
*
* @param int $post_id The id of the post
* @param array $fields An array containing the names of all the fields of the csv
* @return String The csv row
*/
protected static function make_csv_row_from_feedback( $post_id, $fields ) {
$content_fields = self::parse_fields_from_content( $post_id );
$all_fields = array();
if ( isset( $content_fields['_feedback_all_fields'] ) )
$all_fields = $content_fields['_feedback_all_fields'];
// Overwrite the parsed content with the content we stored in post_meta in a better format.
$extra_fields = get_post_meta( $post_id, '_feedback_extra_fields', true );
foreach ( $extra_fields as $extra_field => $extra_value ) {
$all_fields[$extra_field] = $extra_value;
}
// The first element in all of the exports will be the subject
$row_items[] = $content_fields['_feedback_subject'];
// Loop the fields array in order to fill the $row_items array correctly
foreach ( $fields as $field ) {
if ( $field === __( 'Contact Form', 'jetpack' ) ) // the first field will ever be the contact form, so we can continue
continue;
elseif ( array_key_exists( $field, $all_fields ) )
$row_items[] = $all_fields[$field];
else
$row_items[] = '';
}
return $row_items;
}
public static function get_ip_address() {
return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : null;
}
}
/**
* Generic shortcode class.
* Does nothing other than store structured data and output the shortcode as a string
*
* Not very general - specific to Grunion.
*/
class Crunion_Contact_Form_Shortcode {
/**
* @var string the name of the shortcode: [$shortcode_name /]
*/
var $shortcode_name;
/**
* @var array key => value pairs for the shortcode's attributes: [$shortcode_name key="value" ... /]
*/
var $attributes;
/**
* @var array key => value pair for attribute defaults
*/
var $defaults = array();
/**
* @var null|string Null for selfclosing shortcodes. Hhe inner content of otherwise: [$shortcode_name]$content[/$shortcode_name]
*/
var $content;
/**
* @var array Associative array of inner "child" shortcodes equivalent to the $content: [$shortcode_name][child 1/][child 2/][/$shortcode_name]
*/
var $fields;
/**
* @var null|string The HTML of the parsed inner "child" shortcodes". Null for selfclosing shortcodes.
*/
var $body;
/**
* @param array $attributes An associative array of shortcode attributes. @see shortcode_atts()
* @param null|string $content Null for selfclosing shortcodes. The inner content otherwise.
*/
function __construct( $attributes, $content = null ) {
$this->attributes = $this->unesc_attr( $attributes );
if ( is_array( $content ) ) {
$string_content = '';
foreach ( $content as $field ) {
$string_content .= (string) $field;
}
$this->content = $string_content;
} else {
$this->content = $content;
}
$this->parse_content( $this->content );
}
/**
* Processes the shortcode's inner content for "child" shortcodes
*
* @param string $content The shortcode's inner content: [shortcode]$content[/shortcode]
*/
function parse_content( $content ) {
if ( is_null( $content ) ) {
$this->body = null;
}
$this->body = do_shortcode( $content );
}
/**
* Returns the value of the requested attribute.
*
* @param string $key The attribute to retrieve
* @return mixed
*/
function get_attribute( $key ) {
return isset( $this->attributes[$key] ) ? $this->attributes[$key] : null;
}
function esc_attr( $value ) {
if ( is_array( $value ) ) {
return array_map( array( $this, 'esc_attr' ), $value );
}
$value = Grunion_Contact_Form_Plugin::strip_tags( $value );
$value = _wp_specialchars( $value, ENT_QUOTES, false, true );
// Shortcode attributes can't contain "]"
$value = str_replace( ']', '', $value );
$value = str_replace( ',', ',', $value ); // store commas encoded
$value = strtr( $value, array( '%' => '%25', '&' => '%26' ) );
// shortcode_parse_atts() does stripcslashes()
$value = addslashes( $value );
return $value;
}
function unesc_attr( $value ) {
if ( is_array( $value ) ) {
return array_map( array( $this, 'unesc_attr' ), $value );
}
// For back-compat with old Grunion encoding
// Also, unencode commas
$value = strtr( $value, array( '%26' => '&', '%25' => '%' ) );
$value = preg_replace( array( '/�*22;/i', '/�*27;/i', '/�*26;/i', '/�*2c;/i' ), array( '"', "'", '&', ',' ), $value );
$value = htmlspecialchars_decode( $value, ENT_QUOTES );
$value = Grunion_Contact_Form_Plugin::strip_tags( $value );
return $value;
}
/**
* Generates the shortcode
*/
function __toString() {
$r = "[{$this->shortcode_name} ";
foreach ( $this->attributes as $key => $value ) {
if ( !$value ) {
continue;
}
if ( isset( $this->defaults[$key] ) && $this->defaults[$key] == $value ) {
continue;
}
if ( 'id' == $key ) {
continue;
}
$value = $this->esc_attr( $value );
if ( is_array( $value ) ) {
$value = join( ',', $value );
}
if ( false === strpos( $value, "'" ) ) {
$value = "'$value'";
} elseif ( false === strpos( $value, '"' ) ) {
$value = '"' . $value . '"';
} else {
// Shortcodes can't contain both '"' and "'". Strip one.
$value = str_replace( "'", '', $value );
$value = "'$value'";
}
$r .= "{$key}={$value} ";
}
$r = rtrim( $r );
if ( $this->fields ) {
$r .= ']';
foreach ( $this->fields as $field ) {
$r .= (string) $field;
}
$r .= "[/{$this->shortcode_name}]";
} else {
$r .= '/]';
}
return $r;
}
}
/**
* Class for the contact-form shortcode.
* Parses shortcode to output the contact form as HTML
* Sends email and stores the contact form response (a.k.a. "feedback")
*/
class Grunion_Contact_Form extends Crunion_Contact_Form_Shortcode {
var $shortcode_name = 'contact-form';
/**
* @var WP_Error stores form submission errors
*/
var $errors;
/**
* @var Grunion_Contact_Form The most recent (inclusive) contact-form shortcode processed
*/
static $last;
/**
* @var Whatever form we are currently looking at. If processed, will become $last
*/
static $current_form;
/**
* @var bool Whether to print the grunion.css style when processing the contact-form shortcode
*/
static $style = false;
function __construct( $attributes, $content = null ) {
global $post;
// Set up the default subject and recipient for this form
$default_to = '';
$default_subject = "[" . get_option( 'blogname' ) . "]";
if ( !empty( $attributes['widget'] ) && $attributes['widget'] ) {
$default_to .= get_option( 'admin_email' );
$attributes['id'] = 'widget-' . $attributes['widget'];
$default_subject = sprintf( _x( '%1$s Sidebar', '%1$s = blog name', 'jetpack' ), $default_subject );
} else if ( $post ) {
$attributes['id'] = $post->ID;
$default_subject = sprintf( _x( '%1$s %2$s', '%1$s = blog name, %2$s = post title', 'jetpack' ), $default_subject, Grunion_Contact_Form_Plugin::strip_tags( $post->post_title ) );
$post_author = get_userdata( $post->post_author );
$default_to .= $post_author->user_email;
}
// Keep reference to $this for parsing form fields
self::$current_form = $this;
$this->defaults = array(
'to' => $default_to,
'subject' => $default_subject,
'show_subject' => 'no', // only used in back-compat mode
'widget' => 0, // Not exposed to the user. Works with Grunion_Contact_Form_Plugin::widget_atts()
'id' => null, // Not exposed to the user. Set above.
'submit_button_text' => __( 'Submit »', 'jetpack' ),
);
$attributes = shortcode_atts( $this->defaults, $attributes, 'contact-form' );
// We only enable the contact-field shortcode temporarily while processing the contact-form shortcode
Grunion_Contact_Form_Plugin::$using_contact_form_field = true;
parent::__construct( $attributes, $content );
// There were no fields in the contact form. The form was probably just [contact-form /]. Build a default form.
if ( empty( $this->fields ) ) {
// same as the original Grunion v1 form
$default_form = '
[contact-field label="' . __( 'Name', 'jetpack' ) . '" type="name" required="true" /]
[contact-field label="' . __( 'Email', 'jetpack' ) . '" type="email" required="true" /]
[contact-field label="' . __( 'Website', 'jetpack' ) . '" type="url" /]';
if ( 'yes' == strtolower( $this->get_attribute( 'show_subject' ) ) ) {
$default_form .= '
[contact-field label="' . __( 'Subject', 'jetpack' ) . '" type="subject" /]';
}
$default_form .= '
[contact-field label="' . __( 'Message', 'jetpack' ) . '" type="textarea" /]';
$this->parse_content( $default_form );
// Store the shortcode
$this->store_shortcode( $default_form, $attributes );
} else {
// Store the shortcode
$this->store_shortcode( $content, $attributes );
}
// $this->body and $this->fields have been setup. We no longer need the contact-field shortcode.
Grunion_Contact_Form_Plugin::$using_contact_form_field = false;
}
/**
* Store shortcode content for recall later
* - used to receate shortcode when user uses do_shortcode
*
* @param string $content
*/
static function store_shortcode( $content = null, $attributes = null ) {
if ( $content != null and isset( $attributes['id'] ) ) {
$shortcode_meta = get_post_meta( $attributes['id'], '_g_feedback_shortcode', true );
if ( $shortcode_meta != '' or $shortcode_meta != $content ) {
update_post_meta( $attributes['id'], '_g_feedback_shortcode', $content );
}
}
}
/**
* Toggle for printing the grunion.css stylesheet
*
* @param bool $style
*/
static function style( $style ) {
$previous_style = self::$style;
self::$style = (bool) $style;
return $previous_style;
}
/**
* Turn on printing of grunion.css stylesheet
* @see ::style()
* @internal
* @param bool $style
*/
static function _style_on() {
return self::style( true );
}
/**
* The contact-form shortcode processor
*
* @param array $attributes Key => Value pairs as parsed by shortcode_parse_atts()
* @param string|null $content The shortcode's inner content: [contact-form]$content[/contact-form]
* @return string HTML for the concat form.
*/
static function parse( $attributes, $content ) {
// Create a new Grunion_Contact_Form object (this class)
$form = new Grunion_Contact_Form( $attributes, $content );
$id = $form->get_attribute( 'id' );
if ( !$id ) { // something terrible has happened
return '[contact-form]';
}
if ( is_feed() ) {
return '[contact-form]';
}
// Only allow one contact form per post/widget
if ( self::$last && $id == self::$last->get_attribute( 'id' ) ) {
// We're processing the same post
if ( self::$last->attributes != $form->attributes || self::$last->content != $form->content ) {
// And we're processing a different shortcode;
return '';
} // else, we're processing the same shortcode - probably a separate run of do_shortcode() - let it through
} else {
self::$last = $form;
}
// Enqueue the grunion.css stylesheet if self::$style allows it
if ( self::$style && ( empty( $_REQUEST['action'] ) || $_REQUEST['action'] != 'grunion_shortcode_to_json' ) ) {
// Enqueue the style here instead of printing it, because if some other plugin has run the_post()+rewind_posts(),
// (like VideoPress does), the style tag gets "printed" the first time and discarded, leaving the contact form unstyled.
// when WordPress does the real loop.
wp_enqueue_style( 'grunion.css' );
}
$r = '';
$r .= "<div id='contact-form-$id'>\n";
if ( is_wp_error( $form->errors ) && $form->errors->get_error_codes() ) {
// There are errors. Display them
$r .= "<div class='form-error'>\n<h3>" . __( 'Error!', 'jetpack' ) . "</h3>\n<ul class='form-errors'>\n";
foreach ( $form->errors->get_error_messages() as $message )
$r .= "\t<li class='form-error-message'>" . esc_html( $message ) . "</li>\n";
$r .= "</ul>\n</div>\n\n";
}
if ( isset( $_GET['contact-form-id'] ) && $_GET['contact-form-id'] == self::$last->get_attribute( 'id' ) && isset( $_GET['contact-form-sent'] ) ) {
// The contact form was submitted. Show the success message/results
$feedback_id = (int) $_GET['contact-form-sent'];
$back_url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce' ) );
$r_success_message =
"<h3>" . __( 'Message Sent', 'jetpack' ) .
' (<a href="' . esc_url( $back_url ) . '">' . esc_html__( 'go back', 'jetpack' ) . '</a>)' .
"</h3>\n\n";
// Don't show the feedback details unless the nonce matches
if ( $feedback_id && wp_verify_nonce( stripslashes( $_GET['_wpnonce'] ), "contact-form-sent-{$feedback_id}" ) ) {
$r_success_message .= self::success_message( $feedback_id, $form );
}
$r .= apply_filters( 'grunion_contact_form_success_message', $r_success_message );
} else {
// Nothing special - show the normal contact form
if ( $form->get_attribute( 'widget' ) ) {
// Submit form to the current URL
$url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', 'action', '_wpnonce' ) );
} else {
// Submit form to the post permalink
$url = get_permalink();
}
// For SSL/TLS page. See RFC 3986 Section 4.2
$url = set_url_scheme( $url );
// May eventually want to send this to admin-post.php...
$url = apply_filters( 'grunion_contact_form_form_action', "{$url}#contact-form-{$id}", $GLOBALS['post'], $id );
$r .= "<form action='" . esc_url( $url ) . "' method='post' class='contact-form commentsblock'>\n";
$r .= $form->body;
$r .= "\t<p class='contact-submit'>\n";
$r .= "\t\t<input type='submit' value='" . esc_attr( $form->get_attribute( 'submit_button_text' ) ) . "' class='pushbutton-wide'/>\n";
if ( is_user_logged_in() ) {
$r .= "\t\t" . wp_nonce_field( 'contact-form_' . $id, '_wpnonce', true, false ) . "\n"; // nonce and referer
}
$r .= "\t\t<input type='hidden' name='contact-form-id' value='$id' />\n";
$r .= "\t\t<input type='hidden' name='action' value='grunion-contact-form' />\n";
$r .= "\t</p>\n";
$r .= "</form>\n";
}
$r .= "</div>";
return $r;
}
static function success_message( $feedback_id, $form ) {
$r_success_message = '';
$feedback = get_post( $feedback_id );
$field_ids = $form->get_field_ids();
$content_fields = Grunion_Contact_Form_Plugin::parse_fields_from_content( $feedback_id );
// Maps field_ids to post_meta keys
$field_value_map = array(
'name' => 'author',
'email' => 'author_email',
'url' => 'author_url',
'subject' => 'subject',
'textarea' => false, // not a post_meta key. This is stored in post_content
);
$contact_form_message = "<blockquote>\n";
// "Standard" field whitelist
foreach ( $field_value_map as $type => $meta_key ) {
if ( isset( $field_ids[$type] ) ) {
$field = $form->fields[$field_ids[$type]];
if ( $meta_key ) {
if ( isset( $content_fields["_feedback_{$meta_key}"] ) )
$value = $content_fields["_feedback_{$meta_key}"];
} else {
// The feedback content is stored as the first "half" of post_content
$value = $feedback->post_content;
list( $value ) = explode( '<!--more-->', $value );
$value = trim( $value );
}
$contact_form_message .= sprintf(
_x( '%1$s: %2$s', '%1$s = form field label, %2$s = form field value', 'jetpack' ),
wp_kses( $field->get_attribute( 'label' ), array() ),
wp_kses( $value, array() )
) . '<br />';
}
}
// "Non-standard" fields
if ( $field_ids['extra'] ) {
// array indexed by field label (not field id)
$extra_fields = get_post_meta( $feedback_id, '_feedback_extra_fields', true );
$extra_field_keys = array_keys( $extra_fields );
$i = 0;
foreach ( $field_ids['extra'] as $field_id ) {
$field = $form->fields[$field_id];
$label = $field->get_attribute( 'label' );
$contact_form_message .= sprintf(
_x( '%1$s: %2$s', '%1$s = form field label, %2$s = form field value', 'jetpack' ),
wp_kses( $label, array() ),
wp_kses( $extra_fields[$extra_field_keys[$i]], array() )
) . '<br />';
$i++;
}
}
$contact_form_message .= "</blockquote><br /><br />";
$r_success_message .= wp_kses( $contact_form_message, array( 'br' => array(), 'blockquote' => array() ) );
return $r_success_message;
}
/**
* The contact-field shortcode processor
* We use an object method here instead of a static Grunion_Contact_Form_Field class method to parse contact-field shortcodes so that we can tie them to the contact-form object.
*
* @param array $attributes Key => Value pairs as parsed by shortcode_parse_atts()
* @param string|null $content The shortcode's inner content: [contact-field]$content[/contact-field]
* @return HTML for the contact form field
*/
static function parse_contact_field( $attributes, $content ) {
// Don't try to parse contact form fields if not inside a contact form
if ( ! Grunion_Contact_Form_Plugin::$using_contact_form_field ) {
$att_strs = array();
foreach ( $attributes as $att => $val ) {
if ( is_numeric( $att ) ) { // Is a valueless attribute
$att_strs[] = esc_html( $val );
} else if ( isset( $val ) ) { // A regular attr - value pair
$att_strs[] = esc_html( $att ) . '=\'' . esc_html( $val ) . '\'';
}
}
$html = '[contact-field ' . implode( ' ', $att_strs );
if ( isset( $content ) && ! empty( $content ) ) { // If there is content, let's add a closing tag
$html .= ']' . esc_html( $content ) . '[/contact-field]';
} else { // Otherwise let's add a closing slash in the first tag
$html .= '/]';
}
return $html;
}
$form = Grunion_Contact_Form::$current_form;
$field = new Grunion_Contact_Form_Field( $attributes, $content, $form );
$field_id = $field->get_attribute( 'id' );
if ( $field_id ) {
$form->fields[$field_id] = $field;
} else {
$form->fields[] = $field;
}
if (
isset( $_POST['action'] ) && 'grunion-contact-form' === $_POST['action']
&&
isset( $_POST['contact-form-id'] ) && $form->get_attribute( 'id' ) == $_POST['contact-form-id']
) {
// If we're processing a POST submission for this contact form, validate the field value so we can show errors as necessary.
$field->validate();
}
// Output HTML
return $field->render();
}
/**
* Loops through $this->fields to generate a (structured) list of field IDs
* @return array
*/
function get_field_ids() {
$field_ids = array(
'all' => array(), // array of all field_ids
'extra' => array(), // array of all non-whitelisted field IDs
// Whitelisted "standard" field IDs:
// 'email' => field_id,
// 'name' => field_id,
// 'url' => field_id,
// 'subject' => field_id,
// 'textarea' => field_id,
);
foreach ( $this->fields as $id => $field ) {
$field_ids['all'][] = $id;
$type = $field->get_attribute( 'type' );
if ( isset( $field_ids[$type] ) ) {
// This type of field is already present in our whitelist of "standard" fields for this form
// Put it in extra
$field_ids['extra'][] = $id;
continue;
}
switch ( $type ) {
case 'email' :
case 'telephone' :
case 'name' :
case 'url' :
case 'subject' :
case 'textarea' :
$field_ids[$type] = $id;
break;
default :
// Put everything else in extra
$field_ids['extra'][] = $id;
}
}
return $field_ids;
}
/**
* Process the contact form's POST submission
* Stores feedback. Sends email.
*/
function process_submission() {
global $post;
$plugin = Grunion_Contact_Form_Plugin::init();
$id = $this->get_attribute( 'id' );
$to = $this->get_attribute( 'to' );
$widget = $this->get_attribute( 'widget' );
$contact_form_subject = $this->get_attribute( 'subject' );
$to = str_replace( ' ', '', $to );
$emails = explode( ',', $to );
$valid_emails = array();
foreach ( (array) $emails as $email ) {
if ( !is_email( $email ) ) {
continue;
}
if ( function_exists( 'is_email_address_unsafe' ) && is_email_address_unsafe( $email ) ) {
continue;
}
$valid_emails[] = $email;
}
// No one to send it to, which means none of the "to" attributes are valid emails.
// Use default email instead.
if ( !$valid_emails ) {
$valid_emails = $this->defaults['to'];
}
$to = $valid_emails;
// Last ditch effort to set a recipient if somehow none have been set.
if ( empty( $to ) ) {
$to = get_option( 'admin_email' );
}
// Make sure we're processing the form we think we're processing... probably a redundant check.
if ( $widget ) {
if ( 'widget-' . $widget != $_POST['contact-form-id'] ) {
return false;
}
} else {
if ( $post->ID != $_POST['contact-form-id'] ) {
return false;
}
}
$field_ids = $this->get_field_ids();
// Initialize all these "standard" fields to null
$comment_author_email = $comment_author_email_label = // v
$comment_author = $comment_author_label = // v
$comment_author_url = $comment_author_url_label = // v
$comment_content = $comment_content_label = null;
// For each of the "standard" fields, grab their field label and value.
if ( isset( $field_ids['name'] ) ) {
$field = $this->fields[$field_ids['name']];
$comment_author = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( apply_filters( 'pre_comment_author_name', addslashes( $field->value ) ) ) );
$comment_author_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) );
}
if ( isset( $field_ids['email'] ) ) {
$field = $this->fields[$field_ids['email']];
$comment_author_email = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( apply_filters( 'pre_comment_author_email', addslashes( $field->value ) ) ) );
$comment_author_email_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) );
}
if ( isset( $field_ids['url'] ) ) {
$field = $this->fields[$field_ids['url']];
$comment_author_url = Grunion_Contact_Form_Plugin::strip_tags( stripslashes( apply_filters( 'pre_comment_author_url', addslashes( $field->value ) ) ) );
if ( 'http://' == $comment_author_url ) {
$comment_author_url = '';
}
$comment_author_url_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) );
}
if ( isset( $field_ids['textarea'] ) ) {
$field = $this->fields[$field_ids['textarea']];
$comment_content = trim( Grunion_Contact_Form_Plugin::strip_tags( $field->value ) );
$comment_content_label = Grunion_Contact_Form_Plugin::strip_tags( $field->get_attribute( 'label' ) );
}
if ( isset( $field_ids['subject'] ) ) {
$field = $this->fields[$field_ids['subject']];
if ( $field->value ) {
$contact_form_subject = Grunion_Contact_Form_Plugin::strip_tags( $field->value );
}
}
$all_values = $extra_values = array();
$i = 1; // Prefix counter for stored metadata
// For all fields, grab label and value
foreach ( $field_ids['all'] as $field_id ) {
$field = $this->fields[$field_id];
$label = $i . '_' . $field->get_attribute( 'label' );
$value = $field->value;
$all_values[$label] = $value;
$i++; // Increment prefix counter for the next field
}
// For the "non-standard" fields, grab label and value
// Extra fields have their prefix starting from count( $all_values ) + 1
foreach ( $field_ids['extra'] as $field_id ) {
$field = $this->fields[$field_id];
$label = $i . '_' . $field->get_attribute( 'label' );
$value = $field->value;
$extra_values[$label] = $value;
$i++; // Increment prefix counter for the next extra field
}
$contact_form_subject = trim( $contact_form_subject );
$comment_author_IP = Grunion_Contact_Form_Plugin::get_ip_address();
$vars = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'contact_form_subject', 'comment_author_IP' );
foreach ( $vars as $var )
$$var = str_replace( array( "\n", "\r" ), '', $$var );
// Ensure that Akismet gets all of the relevant information from the contact form,
// not just the textarea field and predetermined subject.
$akismet_vars = compact( $vars );
$akismet_vars['comment_content'] = $comment_content;
foreach ( array_merge( $field_ids['all'], $field_ids['extra'] ) as $field_id ) {
$field = $this->fields[$field_id];
// Normalize the label into a slug.
$field_slug = trim( // Strip all leading/trailing dashes.
preg_replace( // Normalize everything to a-z0-9_-
'/[^a-z0-9_]+/',
'-',
strtolower( $field->get_attribute( 'label' ) ) // Lowercase
),
'-'
);
$field_value = trim( $field->value );
// Skip any values that are already in the array we're sending.
if ( $field_value && in_array( $field_value, $akismet_vars ) ) {
continue;
}
$akismet_vars[ 'contact_form_field_' . $field_slug ] = $field_value;
}
$spam = '';
$akismet_values = $plugin->prepare_for_akismet( $akismet_vars );
// Is it spam?
$is_spam = apply_filters( 'jetpack_contact_form_is_spam', false, $akismet_values );
if ( is_wp_error( $is_spam ) ) // WP_Error to abort
return $is_spam; // abort
elseif ( $is_spam === TRUE ) // TRUE to flag a spam
$spam = '***SPAM*** ';
if ( !$comment_author )
$comment_author = $comment_author_email;
$to = (array) apply_filters( 'contact_form_to', $to );
foreach ( $to as $to_key => $to_value ) {
$to[$to_key] = Grunion_Contact_Form_Plugin::strip_tags( $to_value );
}
$blog_url = parse_url( site_url() );
$from_email_addr = 'wordpress@' . $blog_url['host'];
$reply_to_addr = $to[0];
if ( ! empty( $comment_author_email ) ) {
$reply_to_addr = $comment_author_email;
}
$headers = 'From: "' . $comment_author .'" <' . $from_email_addr . ">\r\n" .
'Reply-To: "' . $comment_author . '" <' . $reply_to_addr . ">\r\n" .
"Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"";
$subject = apply_filters( 'contact_form_subject', $contact_form_subject, $all_values );
$url = $widget ? home_url( '/' ) : get_permalink( $post->ID );
$date_time_format = _x( '%1$s \a\t %2$s', '{$date_format} \a\t {$time_format}', 'jetpack' );
$date_time_format = sprintf( $date_time_format, get_option( 'date_format' ), get_option( 'time_format' ) );
$time = date_i18n( $date_time_format, current_time( 'timestamp' ) );
$message = "$comment_author_label: $comment_author\n";
if ( !empty( $comment_author_email ) ) {
$message .= "$comment_author_email_label: $comment_author_email\n";
}
if ( !empty( $comment_author_url ) ) {
$message .= "$comment_author_url_label: $comment_author_url\n";
}
if ( !empty( $comment_content_label ) ) {
$message .= "$comment_content_label: $comment_content\n";
}
if ( !empty( $extra_values ) ) {
foreach ( $extra_values as $label => $value ) {
$message .= preg_replace( '#^\d+_#i', '', $label ) . ': ' . trim( $value ) . "\n";
}
}
$message .= "\n";
$message .= __( 'Time:', 'jetpack' ) . ' ' . $time . "\n";
$message .= __( 'IP Address:', 'jetpack' ) . ' ' . $comment_author_IP . "\n";
$message .= __( 'Contact Form URL:', 'jetpack' ) . " $url\n";
if ( is_user_logged_in() ) {
$message .= "\n";
$message .= sprintf(
__( 'Sent by a verified %s user.', 'jetpack' ),
isset( $GLOBALS['current_site']->site_name ) && $GLOBALS['current_site']->site_name ? $GLOBALS['current_site']->site_name : '"' . get_option( 'blogname' ) . '"'
);
} else {
$message .= __( 'Sent by an unverified visitor to your site.', 'jetpack' );
}
$message = apply_filters( 'contact_form_message', $message );
$message = Grunion_Contact_Form_Plugin::strip_tags( $message );
// keep a copy of the feedback as a custom post type
$feedback_time = current_time( 'mysql' );
$feedback_title = "{$comment_author} - {$feedback_time}";
$feedback_status = $is_spam === TRUE ? 'spam' : 'publish';
foreach ( (array) $akismet_values as $av_key => $av_value ) {
$akismet_values[$av_key] = Grunion_Contact_Form_Plugin::strip_tags( $av_value );
}
foreach ( (array) $all_values as $all_key => $all_value ) {
$all_values[$all_key] = Grunion_Contact_Form_Plugin::strip_tags( $all_value );
}
foreach ( (array) $extra_values as $ev_key => $ev_value ) {
$extra_values[$ev_key] = Grunion_Contact_Form_Plugin::strip_tags( $ev_value );
}
/* We need to make sure that the post author is always zero for contact
* form submissions. This prevents export/import from trying to create
* new users based on form submissions from people who were logged in
* at the time.
*
* Unfortunately wp_insert_post() tries very hard to make sure the post
* author gets the currently logged in user id. That is how we ended up
* with this work around. */
add_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10, 2 );
$post_id = wp_insert_post( array(
'post_date' => addslashes( $feedback_time ),
'post_type' => 'feedback',
'post_status' => addslashes( $feedback_status ),
'post_parent' => (int) $post->ID,
'post_title' => addslashes( wp_kses( $feedback_title, array() ) ),
'post_content' => addslashes( wp_kses( $comment_content . "\n<!--more-->\n" . "AUTHOR: {$comment_author}\nAUTHOR EMAIL: {$comment_author_email}\nAUTHOR URL: {$comment_author_url}\nSUBJECT: {$subject}\nIP: {$comment_author_IP}\n" . print_r( $all_values, TRUE ), array() ) ), // so that search will pick up this data
'post_name' => md5( $feedback_title ),
) );
// once insert has finished we don't need this filter any more
remove_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10, 2 );
update_post_meta( $post_id, '_feedback_extra_fields', $this->addslashes_deep( $extra_values ) );
update_post_meta( $post_id, '_feedback_akismet_values', $this->addslashes_deep( $akismet_values ) );
update_post_meta( $post_id, '_feedback_email', $this->addslashes_deep( compact( 'to', 'message' ) ) );
/**
* Fires right before the contact form message is sent via email to
* the recipient specified in the contact form.
*
* @since ?
* @module Contact_Forms
* @param integer $post_id Post contact form lives on
* @param array $all_values Contact form fields
* @param array $extra_values Contact form fields not included in $all_values
**/
do_action( 'grunion_pre_message_sent', $post_id, $all_values, $extra_values );
// schedule deletes of old spam feedbacks
if ( !wp_next_scheduled( 'grunion_scheduled_delete' ) ) {
wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete' );
}
if ( $is_spam !== TRUE && true === apply_filters( 'grunion_should_send_email', true, $post_id ) ) {
wp_mail( $to, "{$spam}{$subject}", $message, $headers );
} elseif ( true === $is_spam && apply_filters( 'grunion_still_email_spam', FALSE ) == TRUE ) { // don't send spam by default. Filterable.
wp_mail( $to, "{$spam}{$subject}", $message, $headers );
}
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return self::success_message( $post_id, $this );
}
$redirect = wp_get_referer();
if ( !$redirect ) { // wp_get_referer() returns false if the referer is the same as the current page
$redirect = $_SERVER['REQUEST_URI'];
}
$redirect = add_query_arg( urlencode_deep( array(
'contact-form-id' => $id,
'contact-form-sent' => $post_id,
'_wpnonce' => wp_create_nonce( "contact-form-sent-{$post_id}" ), // wp_nonce_url HTMLencodes :(
) ), $redirect );
$redirect = apply_filters( 'grunion_contact_form_redirect_url', $redirect, $id, $post_id );
wp_safe_redirect( $redirect );
exit;
}
function addslashes_deep( $value ) {
if ( is_array( $value ) ) {
return array_map( array( $this, 'addslashes_deep' ), $value );
} elseif ( is_object( $value ) ) {
$vars = get_object_vars( $value );
foreach ( $vars as $key => $data ) {
$value->{$key} = $this->addslashes_deep( $data );
}
return $value;
}
return addslashes( $value );
}
}
/**
* Class for the contact-field shortcode.
* Parses shortcode to output the contact form field as HTML.
* Validates input.
*/
class Grunion_Contact_Form_Field extends Crunion_Contact_Form_Shortcode {
var $shortcode_name = 'contact-field';
/**
* @var Grunion_Contact_Form parent form
*/
var $form;
/**
* @var string default or POSTed value
*/
var $value;
/**
* @var bool Is the input invalid?
*/
var $error = false;
/**
* @param array $attributes An associative array of shortcode attributes. @see shortcode_atts()
* @param null|string $content Null for selfclosing shortcodes. The inner content otherwise.
* @param Grunion_Contact_Form $form The parent form
*/
function __construct( $attributes, $content = null, $form = null ) {
$attributes = shortcode_atts( array(
'label' => null,
'type' => 'text',
'required' => false,
'options' => array(),
'id' => null,
'default' => null,
'placeholder' => null,
), $attributes, 'contact-field' );
// special default for subject field
if ( 'subject' == $attributes['type'] && is_null( $attributes['default'] ) && !is_null( $form ) ) {
$attributes['default'] = $form->get_attribute( 'subject' );
}
// allow required=1 or required=true
if ( '1' == $attributes['required'] || 'true' == strtolower( $attributes['required'] ) )
$attributes['required'] = true;
else
$attributes['required'] = false;
// parse out comma-separated options list (for selects and radios)
if ( !empty( $attributes['options'] ) && is_string( $attributes['options'] ) ) {
$attributes['options'] = array_map( 'trim', explode( ',', $attributes['options'] ) );
}
if ( $form ) {
// make a unique field ID based on the label, with an incrementing number if needed to avoid clashes
$form_id = $form->get_attribute( 'id' );
$id = isset( $attributes['id'] ) ? $attributes['id'] : false;
$unescaped_label = $this->unesc_attr( $attributes['label'] );
$unescaped_label = str_replace( '%', '-', $unescaped_label ); // jQuery doesn't like % in IDs?
$unescaped_label = preg_replace( '/[^a-zA-Z0-9.-_:]/', '', $unescaped_label );
if ( empty( $id ) ) {
$id = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label );
$i = 0;
$max_tries = 24;
while ( isset( $form->fields[$id] ) ) {
$i++;
$id = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label . '-' . $i );
if ( $i > $max_tries ) {
break;
}
}
}
$attributes['id'] = $id;
}
parent::__construct( $attributes, $content );
// Store parent form
$this->form = $form;
}
/**
* This field's input is invalid. Flag as invalid and add an error to the parent form
*
* @param string $message The error message to display on the form.
*/
function add_error( $message ) {
$this->is_error = true;
if ( !is_wp_error( $this->form->errors ) ) {
$this->form->errors = new WP_Error;
}
$this->form->errors->add( $this->get_attribute( 'id' ), $message );
}
/**
* Is the field input invalid?
*
* @see $error
*
* @return bool
*/
function is_error() {
return $this->error;
}
/**
* Validates the form input
*/
function validate() {
// If it's not required, there's nothing to validate
if ( !$this->get_attribute( 'required' ) ) {
return;
}
$field_id = $this->get_attribute( 'id' );
$field_type = $this->get_attribute( 'type' );
$field_label = $this->get_attribute( 'label' );
$field_value = isset( $_POST[$field_id] ) ? stripslashes( $_POST[$field_id] ) : '';
switch ( $field_type ) {
case 'email' :
// Make sure the email address is valid
if ( !is_email( $field_value ) ) {
$this->add_error( sprintf( __( '%s requires a valid email address', 'jetpack' ), $field_label ) );
}
break;
default :
// Just check for presence of any text
if ( !strlen( trim( $field_value ) ) ) {
$this->add_error( sprintf( __( '%s is required', 'jetpack' ), $field_label ) );
}
}
}
/**
* Outputs the HTML for this form field
*
* @return string HTML
*/
function render() {
global $current_user, $user_identity;
$r = '';
$field_id = $this->get_attribute( 'id' );
$field_type = $this->get_attribute( 'type' );
$field_label = $this->get_attribute( 'label' );
$field_required = $this->get_attribute( 'required' );
$placeholder = $this->get_attribute( 'placeholder' );
$field_placeholder = ( ! empty( $placeholder ) ) ? "placeholder='" . esc_attr( $placeholder ) . "'" : '';
if ( isset( $_POST[$field_id] ) ) {
$this->value = stripslashes( (string) $_POST[$field_id] );
} elseif (
is_user_logged_in()
&& ( ( defined( 'IS_WPCOM' ) && IS_WPCOM )
|| true === apply_filters( 'jetpack_auto_fill_logged_in_user', false )
)
) {
// Special defaults for logged-in users
switch ( $this->get_attribute( 'type' ) ) {
case 'email' :
$this->value = $current_user->data->user_email;
break;
case 'name' :
$this->value = $user_identity;
break;
case 'url' :
$this->value = $current_user->data->user_url;
break;
default :
$this->value = $this->get_attribute( 'default' );
}
} else {
$this->value = $this->get_attribute( 'default' );
}
$field_value = Grunion_Contact_Form_Plugin::strip_tags( $this->value );
$field_label = Grunion_Contact_Form_Plugin::strip_tags( $field_label );
switch ( $field_type ) {
case 'email' :
$r .= "\n<div>\n";
$r .= "\t\t<label for='" . esc_attr( $field_id ) . "' class='grunion-field-label email" . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<input type='email' name='" . esc_attr( $field_id ) . "' id='" . esc_attr( $field_id ) . "' value='" . esc_attr( $field_value ) . "' class='email' " . $field_placeholder . " " . ( $field_required ? "required aria-required='true'" : "" ) . "/>\n";
$r .= "\t</div>\n";
break;
case 'telephone' :
$r .= "\n<div>\n";
$r .= "\t\t<label for='" . esc_attr( $field_id ) . "' class='grunion-field-label telephone" . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<input type='tel' name='" . esc_attr( $field_id ) . "' id='" . esc_attr( $field_id ) . "' value='" . esc_attr( $field_value ) . "' class='telephone' " . $field_placeholder . "/>\n";
case 'textarea' :
$r .= "\n<div>\n";
$r .= "\t\t<label for='contact-form-comment-" . esc_attr( $field_id ) . "' class='grunion-field-label textarea" . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<textarea name='" . esc_attr( $field_id ) . "' id='contact-form-comment-" . esc_attr( $field_id ) . "' rows='20' " . $field_placeholder . " " . ( $field_required ? "required aria-required='true'" : "" ) . ">" . esc_textarea( $field_value ) . "</textarea>\n";
$r .= "\t</div>\n";
break;
case 'radio' :
$r .= "\t<div><label class='grunion-field-label" . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
foreach ( $this->get_attribute( 'options' ) as $option ) {
$option = Grunion_Contact_Form_Plugin::strip_tags( $option );
$r .= "\t\t<label class='grunion-radio-label radio" . ( $this->is_error() ? ' form-error' : '' ) . "'>";
$r .= "<input type='radio' name='" . esc_attr( $field_id ) . "' value='" . esc_attr( $option ) . "' class='radio' " . checked( $option, $field_value, false ) . " " . ( $field_required ? "required aria-required='true'" : "" ) . "/> ";
$r .= esc_html( $option ) . "</label>\n";
$r .= "\t\t<div class='clear-form'></div>\n";
}
$r .= "\t\t</div>\n";
break;
case 'checkbox' :
$r .= "\t<div>\n";
$r .= "\t\t<label class='grunion-field-label checkbox" . ( $this->is_error() ? ' form-error' : '' ) . "'>\n";
$r .= "\t\t<input type='checkbox' name='" . esc_attr( $field_id ) . "' value='" . esc_attr__( 'Yes', 'jetpack' ) . "' class='checkbox' " . checked( (bool) $field_value, true, false ) . " " . ( $field_required ? "required aria-required='true'" : "" ) . "/> \n";
$r .= "\t\t" . esc_html( $field_label ) . ( $field_required ? '<span>'. __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<div class='clear-form'></div>\n";
$r .= "\t</div>\n";
break;
case 'select' :
$r .= "\n<div>\n";
$r .= "\t\t<label for='" . esc_attr( $field_id ) . "' class='grunion-field-label select" . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>'. __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t<select name='" . esc_attr( $field_id ) . "' id='" . esc_attr( $field_id ) . "' class='select' " . ( $field_required ? "required aria-required='true'" : "" ) . ">\n";
foreach ( $this->get_attribute( 'options' ) as $option ) {
$option = Grunion_Contact_Form_Plugin::strip_tags( $option );
$r .= "\t\t<option" . selected( $option, $field_value, false ) . ">" . esc_html( $option ) . "</option>\n";
}
$r .= "\t</select>\n";
$r .= "\t</div>\n";
break;
case 'date' :
$r .= "\n<div>\n";
$r .= "\t\t<label for='" . esc_attr( $field_id ) . "' class='grunion-field-label " . esc_attr( $field_type ) . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<input type='date' name='" . esc_attr( $field_id ) . "' id='" . esc_attr( $field_id ) . "' value='" . esc_attr( $field_value ) . "' class='" . esc_attr( $field_type ) . "' " . ( $field_required ? "required aria-required='true'" : "" ) . "/>\n";
$r .= "\t</div>\n";
wp_enqueue_script( 'grunion-frontend', plugins_url( 'js/grunion-frontend.js', __FILE__ ), array( 'jquery', 'jquery-ui-datepicker' ) );
break;
default : // text field
// note that any unknown types will produce a text input, so we can use arbitrary type names to handle
// input fields like name, email, url that require special validation or handling at POST
$r .= "\n<div>\n";
$r .= "\t\t<label for='" . esc_attr( $field_id ) . "' class='grunion-field-label " . esc_attr( $field_type ) . ( $this->is_error() ? ' form-error' : '' ) . "'>" . esc_html( $field_label ) . ( $field_required ? '<span>' . __( "(required)", 'jetpack' ) . '</span>' : '' ) . "</label>\n";
$r .= "\t\t<input type='text' name='" . esc_attr( $field_id ) . "' id='" . esc_attr( $field_id ) . "' value='" . esc_attr( $field_value ) . "' class='" . esc_attr( $field_type ) . "' " . $field_placeholder . " " . ( $field_required ? "required aria-required='true'" : "" ) . "/>\n";
$r .= "\t</div>\n";
}
return apply_filters( 'grunion_contact_form_field_html', $r, $field_label, ( in_the_loop() ? get_the_ID() : null ) );
}
}
add_action( 'init', array( 'Grunion_Contact_Form_Plugin', 'init' ) );
add_action( 'grunion_scheduled_delete', 'grunion_delete_old_spam' );
/**
* Deletes old spam feedbacks to keep the posts table size under control
*/
function grunion_delete_old_spam() {
global $wpdb;
$grunion_delete_limit = 100;
$now_gmt = current_time( 'mysql', 1 );
$sql = $wpdb->prepare( "
SELECT `ID`
FROM $wpdb->posts
WHERE DATE_SUB( %s, INTERVAL 15 DAY ) > `post_date_gmt`
AND `post_type` = 'feedback'
AND `post_status` = 'spam'
LIMIT %d
", $now_gmt, $grunion_delete_limit );
$post_ids = $wpdb->get_col( $sql );
foreach ( (array) $post_ids as $post_id ) {
# force a full delete, skip the trash
wp_delete_post( $post_id, TRUE );
}
# Arbitrary check points for running OPTIMIZE
# nothing special about 5000 or 11
# just trying to periodically recover deleted rows
$random_num = mt_rand( 1, 5000 );
if ( apply_filters( 'grunion_optimize_table', ( $random_num == 11 ) ) ) {
$wpdb->query( "OPTIMIZE TABLE $wpdb->posts" );
}
# if we hit the max then schedule another run
if ( count( $post_ids ) >= $grunion_delete_limit ) {
wp_schedule_single_event( time() + 700, 'grunion_scheduled_delete' );
}
}
|
cashmanbiz/rainbow
|
wp-content/plugins/jetpack/modules/contact-form/grunion-contact-form.php
|
PHP
|
gpl-2.0
| 66,028
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
struct Good1
{
MatrixXd m; // good: m will allocate its own array, taking care of alignment.
Good1() : m(20,20) {}
};
struct Good2
{
Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be aligned
};
struct Good3
{
Vector2f m; // good: same reason
};
struct Bad4
{
Vector2d m; // bad: sizeof(m)%16==0 so alignment is required
};
struct Bad5
{
Matrix<float, 2, 6> m; // bad: same reason
};
struct Bad6
{
Matrix<double, 3, 4> m; // bad: same reason
};
struct Good7
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Vector2d m;
float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects
};
struct Good8
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
float f; // try the f at first -- the EIGEN_ALIGN_128 attribute of m should make that still work
Matrix4f m;
};
struct Good9
{
Matrix<float,2,2,DontAlign> m; // good: no alignment requested
float f;
};
template<bool Align> struct Depends
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align)
Vector2d m;
float f;
};
template<typename T>
void check_unalignedassert_good()
{
T *x, *y;
x = new T;
delete x;
y = new T[2];
delete[] y;
}
#if EIGEN_ARCH_WANTS_ALIGNMENT
template<typename T>
void check_unalignedassert_bad()
{
float buf[sizeof(T)+16];
float *unaligned = buf;
while((reinterpret_cast<std::size_t>(unaligned)&0xf)==0) ++unaligned; // make sure unaligned is really unaligned
T *x = ::new(static_cast<void*>(unaligned)) T;
x->~T();
}
#endif
void unalignedassert()
{
check_unalignedassert_good<Good1>();
check_unalignedassert_good<Good2>();
check_unalignedassert_good<Good3>();
#if EIGEN_ARCH_WANTS_ALIGNMENT
VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad4>());
VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad5>());
VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad6>());
#endif
check_unalignedassert_good<Good7>();
check_unalignedassert_good<Good8>();
check_unalignedassert_good<Good9>();
check_unalignedassert_good<Depends<true> >();
#if EIGEN_ARCH_WANTS_ALIGNMENT
VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Depends<false> >());
#endif
}
void test_eigen2_unalignedassert()
{
CALL_SUBTEST(unalignedassert());
}
|
yxiong/xyMatlabUtils-release
|
xyCppUtils/ThirdParty/eigen/test/eigen2/eigen2_unalignedassert.cpp
|
C++
|
mit
| 2,638
|
/*
* Copyright (C) 2018 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _mp_11_0_2_OFFSET_HEADER
#define _mp_11_0_2_OFFSET_HEADER
// addressBlock: mp_SmuMp0_SmnDec
// base address: 0x0
#define mmMP0_SMN_C2PMSG_32 0x0060
#define mmMP0_SMN_C2PMSG_32_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_33 0x0061
#define mmMP0_SMN_C2PMSG_33_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_34 0x0062
#define mmMP0_SMN_C2PMSG_34_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_35 0x0063
#define mmMP0_SMN_C2PMSG_35_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_36 0x0064
#define mmMP0_SMN_C2PMSG_36_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_37 0x0065
#define mmMP0_SMN_C2PMSG_37_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_38 0x0066
#define mmMP0_SMN_C2PMSG_38_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_39 0x0067
#define mmMP0_SMN_C2PMSG_39_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_40 0x0068
#define mmMP0_SMN_C2PMSG_40_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_41 0x0069
#define mmMP0_SMN_C2PMSG_41_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_42 0x006a
#define mmMP0_SMN_C2PMSG_42_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_43 0x006b
#define mmMP0_SMN_C2PMSG_43_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_44 0x006c
#define mmMP0_SMN_C2PMSG_44_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_45 0x006d
#define mmMP0_SMN_C2PMSG_45_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_46 0x006e
#define mmMP0_SMN_C2PMSG_46_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_47 0x006f
#define mmMP0_SMN_C2PMSG_47_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_48 0x0070
#define mmMP0_SMN_C2PMSG_48_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_49 0x0071
#define mmMP0_SMN_C2PMSG_49_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_50 0x0072
#define mmMP0_SMN_C2PMSG_50_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_51 0x0073
#define mmMP0_SMN_C2PMSG_51_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_52 0x0074
#define mmMP0_SMN_C2PMSG_52_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_53 0x0075
#define mmMP0_SMN_C2PMSG_53_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_54 0x0076
#define mmMP0_SMN_C2PMSG_54_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_55 0x0077
#define mmMP0_SMN_C2PMSG_55_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_56 0x0078
#define mmMP0_SMN_C2PMSG_56_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_57 0x0079
#define mmMP0_SMN_C2PMSG_57_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_58 0x007a
#define mmMP0_SMN_C2PMSG_58_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_59 0x007b
#define mmMP0_SMN_C2PMSG_59_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_60 0x007c
#define mmMP0_SMN_C2PMSG_60_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_61 0x007d
#define mmMP0_SMN_C2PMSG_61_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_62 0x007e
#define mmMP0_SMN_C2PMSG_62_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_63 0x007f
#define mmMP0_SMN_C2PMSG_63_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_64 0x0080
#define mmMP0_SMN_C2PMSG_64_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_65 0x0081
#define mmMP0_SMN_C2PMSG_65_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_66 0x0082
#define mmMP0_SMN_C2PMSG_66_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_67 0x0083
#define mmMP0_SMN_C2PMSG_67_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_68 0x0084
#define mmMP0_SMN_C2PMSG_68_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_69 0x0085
#define mmMP0_SMN_C2PMSG_69_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_70 0x0086
#define mmMP0_SMN_C2PMSG_70_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_71 0x0087
#define mmMP0_SMN_C2PMSG_71_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_72 0x0088
#define mmMP0_SMN_C2PMSG_72_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_73 0x0089
#define mmMP0_SMN_C2PMSG_73_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_74 0x008a
#define mmMP0_SMN_C2PMSG_74_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_75 0x008b
#define mmMP0_SMN_C2PMSG_75_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_76 0x008c
#define mmMP0_SMN_C2PMSG_76_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_77 0x008d
#define mmMP0_SMN_C2PMSG_77_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_78 0x008e
#define mmMP0_SMN_C2PMSG_78_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_79 0x008f
#define mmMP0_SMN_C2PMSG_79_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_80 0x0090
#define mmMP0_SMN_C2PMSG_80_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_81 0x0091
#define mmMP0_SMN_C2PMSG_81_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_82 0x0092
#define mmMP0_SMN_C2PMSG_82_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_83 0x0093
#define mmMP0_SMN_C2PMSG_83_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_84 0x0094
#define mmMP0_SMN_C2PMSG_84_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_85 0x0095
#define mmMP0_SMN_C2PMSG_85_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_86 0x0096
#define mmMP0_SMN_C2PMSG_86_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_87 0x0097
#define mmMP0_SMN_C2PMSG_87_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_88 0x0098
#define mmMP0_SMN_C2PMSG_88_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_89 0x0099
#define mmMP0_SMN_C2PMSG_89_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_90 0x009a
#define mmMP0_SMN_C2PMSG_90_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_91 0x009b
#define mmMP0_SMN_C2PMSG_91_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_92 0x009c
#define mmMP0_SMN_C2PMSG_92_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_93 0x009d
#define mmMP0_SMN_C2PMSG_93_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_94 0x009e
#define mmMP0_SMN_C2PMSG_94_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_95 0x009f
#define mmMP0_SMN_C2PMSG_95_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_96 0x00a0
#define mmMP0_SMN_C2PMSG_96_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_97 0x00a1
#define mmMP0_SMN_C2PMSG_97_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_98 0x00a2
#define mmMP0_SMN_C2PMSG_98_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_99 0x00a3
#define mmMP0_SMN_C2PMSG_99_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_100 0x00a4
#define mmMP0_SMN_C2PMSG_100_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_101 0x00a5
#define mmMP0_SMN_C2PMSG_101_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_102 0x00a6
#define mmMP0_SMN_C2PMSG_102_BASE_IDX 0
#define mmMP0_SMN_C2PMSG_103 0x00a7
#define mmMP0_SMN_C2PMSG_103_BASE_IDX 0
#define mmMP0_SMN_ACTIVE_FCN_ID 0x00c0
#define mmMP0_SMN_ACTIVE_FCN_ID_BASE_IDX 0
#define mmMP0_SMN_IH_CREDIT 0x00c1
#define mmMP0_SMN_IH_CREDIT_BASE_IDX 0
#define mmMP0_SMN_IH_SW_INT 0x00c2
#define mmMP0_SMN_IH_SW_INT_BASE_IDX 0
#define mmMP0_SMN_IH_SW_INT_CTRL 0x00c3
#define mmMP0_SMN_IH_SW_INT_CTRL_BASE_IDX 0
// addressBlock: mp_SmuMp1_SmnDec
// base address: 0x0
#define mmMP1_SMN_C2PMSG_32 0x0260
#define mmMP1_SMN_C2PMSG_32_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_33 0x0261
#define mmMP1_SMN_C2PMSG_33_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_34 0x0262
#define mmMP1_SMN_C2PMSG_34_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_35 0x0263
#define mmMP1_SMN_C2PMSG_35_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_36 0x0264
#define mmMP1_SMN_C2PMSG_36_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_37 0x0265
#define mmMP1_SMN_C2PMSG_37_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_38 0x0266
#define mmMP1_SMN_C2PMSG_38_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_39 0x0267
#define mmMP1_SMN_C2PMSG_39_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_40 0x0268
#define mmMP1_SMN_C2PMSG_40_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_41 0x0269
#define mmMP1_SMN_C2PMSG_41_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_42 0x026a
#define mmMP1_SMN_C2PMSG_42_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_43 0x026b
#define mmMP1_SMN_C2PMSG_43_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_44 0x026c
#define mmMP1_SMN_C2PMSG_44_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_45 0x026d
#define mmMP1_SMN_C2PMSG_45_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_46 0x026e
#define mmMP1_SMN_C2PMSG_46_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_47 0x026f
#define mmMP1_SMN_C2PMSG_47_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_48 0x0270
#define mmMP1_SMN_C2PMSG_48_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_49 0x0271
#define mmMP1_SMN_C2PMSG_49_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_50 0x0272
#define mmMP1_SMN_C2PMSG_50_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_51 0x0273
#define mmMP1_SMN_C2PMSG_51_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_52 0x0274
#define mmMP1_SMN_C2PMSG_52_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_53 0x0275
#define mmMP1_SMN_C2PMSG_53_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_54 0x0276
#define mmMP1_SMN_C2PMSG_54_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_55 0x0277
#define mmMP1_SMN_C2PMSG_55_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_56 0x0278
#define mmMP1_SMN_C2PMSG_56_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_57 0x0279
#define mmMP1_SMN_C2PMSG_57_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_58 0x027a
#define mmMP1_SMN_C2PMSG_58_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_59 0x027b
#define mmMP1_SMN_C2PMSG_59_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_60 0x027c
#define mmMP1_SMN_C2PMSG_60_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_61 0x027d
#define mmMP1_SMN_C2PMSG_61_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_62 0x027e
#define mmMP1_SMN_C2PMSG_62_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_63 0x027f
#define mmMP1_SMN_C2PMSG_63_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_64 0x0280
#define mmMP1_SMN_C2PMSG_64_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_65 0x0281
#define mmMP1_SMN_C2PMSG_65_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_66 0x0282
#define mmMP1_SMN_C2PMSG_66_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_67 0x0283
#define mmMP1_SMN_C2PMSG_67_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_68 0x0284
#define mmMP1_SMN_C2PMSG_68_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_69 0x0285
#define mmMP1_SMN_C2PMSG_69_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_70 0x0286
#define mmMP1_SMN_C2PMSG_70_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_71 0x0287
#define mmMP1_SMN_C2PMSG_71_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_72 0x0288
#define mmMP1_SMN_C2PMSG_72_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_73 0x0289
#define mmMP1_SMN_C2PMSG_73_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_74 0x028a
#define mmMP1_SMN_C2PMSG_74_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_75 0x028b
#define mmMP1_SMN_C2PMSG_75_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_76 0x028c
#define mmMP1_SMN_C2PMSG_76_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_77 0x028d
#define mmMP1_SMN_C2PMSG_77_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_78 0x028e
#define mmMP1_SMN_C2PMSG_78_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_79 0x028f
#define mmMP1_SMN_C2PMSG_79_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_80 0x0290
#define mmMP1_SMN_C2PMSG_80_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_81 0x0291
#define mmMP1_SMN_C2PMSG_81_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_82 0x0292
#define mmMP1_SMN_C2PMSG_82_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_83 0x0293
#define mmMP1_SMN_C2PMSG_83_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_84 0x0294
#define mmMP1_SMN_C2PMSG_84_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_85 0x0295
#define mmMP1_SMN_C2PMSG_85_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_86 0x0296
#define mmMP1_SMN_C2PMSG_86_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_87 0x0297
#define mmMP1_SMN_C2PMSG_87_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_88 0x0298
#define mmMP1_SMN_C2PMSG_88_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_89 0x0299
#define mmMP1_SMN_C2PMSG_89_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_90 0x029a
#define mmMP1_SMN_C2PMSG_90_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_91 0x029b
#define mmMP1_SMN_C2PMSG_91_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_92 0x029c
#define mmMP1_SMN_C2PMSG_92_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_93 0x029d
#define mmMP1_SMN_C2PMSG_93_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_94 0x029e
#define mmMP1_SMN_C2PMSG_94_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_95 0x029f
#define mmMP1_SMN_C2PMSG_95_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_96 0x02a0
#define mmMP1_SMN_C2PMSG_96_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_97 0x02a1
#define mmMP1_SMN_C2PMSG_97_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_98 0x02a2
#define mmMP1_SMN_C2PMSG_98_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_99 0x02a3
#define mmMP1_SMN_C2PMSG_99_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_100 0x02a4
#define mmMP1_SMN_C2PMSG_100_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_101 0x02a5
#define mmMP1_SMN_C2PMSG_101_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_102 0x02a6
#define mmMP1_SMN_C2PMSG_102_BASE_IDX 0
#define mmMP1_SMN_C2PMSG_103 0x02a7
#define mmMP1_SMN_C2PMSG_103_BASE_IDX 0
#define mmMP1_SMN_ACTIVE_FCN_ID 0x02c0
#define mmMP1_SMN_ACTIVE_FCN_ID_BASE_IDX 0
#define mmMP1_SMN_IH_CREDIT 0x02c1
#define mmMP1_SMN_IH_CREDIT_BASE_IDX 0
#define mmMP1_SMN_IH_SW_INT 0x02c2
#define mmMP1_SMN_IH_SW_INT_BASE_IDX 0
#define mmMP1_SMN_IH_SW_INT_CTRL 0x02c3
#define mmMP1_SMN_IH_SW_INT_CTRL_BASE_IDX 0
#define mmMP1_SMN_FPS_CNT 0x02c4
#define mmMP1_SMN_FPS_CNT_BASE_IDX 0
#define mmMP1_SMN_PUB_CTRL 0x02c5
#define mmMP1_SMN_PUB_CTRL_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH0 0x03c0
#define mmMP1_SMN_EXT_SCRATCH0_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH1 0x03c1
#define mmMP1_SMN_EXT_SCRATCH1_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH2 0x03c2
#define mmMP1_SMN_EXT_SCRATCH2_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH3 0x03c3
#define mmMP1_SMN_EXT_SCRATCH3_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH4 0x03c4
#define mmMP1_SMN_EXT_SCRATCH4_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH5 0x03c5
#define mmMP1_SMN_EXT_SCRATCH5_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH6 0x03c6
#define mmMP1_SMN_EXT_SCRATCH6_BASE_IDX 0
#define mmMP1_SMN_EXT_SCRATCH7 0x03c7
#define mmMP1_SMN_EXT_SCRATCH7_BASE_IDX 0
#endif
|
CSE3320/kernel-code
|
linux-5.8/drivers/gpu/drm/amd/include/asic_reg/mp/mp_11_0_offset.h
|
C
|
gpl-2.0
| 36,143
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\sqlite;
use yii\base\NotSupportedException;
use yii\db\Expression;
use yii\db\TableSchema;
use yii\db\ColumnSchema;
use yii\db\Transaction;
/**
* Schema is the class for retrieving metadata from a SQLite (2/3) database.
*
* @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
* This can be either [[Transaction::READ_UNCOMMITTED]] or [[Transaction::SERIALIZABLE]].
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Schema extends \yii\db\Schema
{
/**
* @var array mapping from physical column types (keys) to abstract column types (values)
*/
public $typeMap = [
'tinyint' => self::TYPE_SMALLINT,
'bit' => self::TYPE_SMALLINT,
'boolean' => self::TYPE_BOOLEAN,
'bool' => self::TYPE_BOOLEAN,
'smallint' => self::TYPE_SMALLINT,
'mediumint' => self::TYPE_INTEGER,
'int' => self::TYPE_INTEGER,
'integer' => self::TYPE_INTEGER,
'bigint' => self::TYPE_BIGINT,
'float' => self::TYPE_FLOAT,
'double' => self::TYPE_DOUBLE,
'real' => self::TYPE_FLOAT,
'decimal' => self::TYPE_DECIMAL,
'numeric' => self::TYPE_DECIMAL,
'tinytext' => self::TYPE_TEXT,
'mediumtext' => self::TYPE_TEXT,
'longtext' => self::TYPE_TEXT,
'text' => self::TYPE_TEXT,
'varchar' => self::TYPE_STRING,
'string' => self::TYPE_STRING,
'char' => self::TYPE_STRING,
'blob' => self::TYPE_BINARY,
'datetime' => self::TYPE_DATETIME,
'year' => self::TYPE_DATE,
'date' => self::TYPE_DATE,
'time' => self::TYPE_TIME,
'timestamp' => self::TYPE_TIMESTAMP,
'enum' => self::TYPE_STRING,
];
/**
* Quotes a table name for use in a query.
* A simple table name has no schema prefix.
* @param string $name table name
* @return string the properly quoted table name
*/
public function quoteSimpleTableName($name)
{
return strpos($name, "`") !== false ? $name : "`" . $name . "`";
}
/**
* Quotes a column name for use in a query.
* A simple column name has no prefix.
* @param string $name column name
* @return string the properly quoted column name
*/
public function quoteSimpleColumnName($name)
{
return strpos($name, '`') !== false || $name === '*' ? $name : '`' . $name . '`';
}
/**
* Creates a query builder for the MySQL database.
* This method may be overridden by child classes to create a DBMS-specific query builder.
* @return QueryBuilder query builder instance
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->db);
}
/**
* Returns all table names in the database.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
* @return array all table names in the database. The names have NO schema name prefix.
*/
protected function findTableNames($schema = '')
{
$sql = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name<>'sqlite_sequence' ORDER BY tbl_name";
return $this->db->createCommand($sql)->queryColumn();
}
/**
* Loads the metadata for the specified table.
* @param string $name table name
* @return TableSchema driver dependent table metadata. Null if the table does not exist.
*/
protected function loadTableSchema($name)
{
$table = new TableSchema;
$table->name = $name;
$table->fullName = $name;
if ($this->findColumns($table)) {
$this->findConstraints($table);
return $table;
} else {
return null;
}
}
/**
* Collects the table column metadata.
* @param TableSchema $table the table metadata
* @return boolean whether the table exists in the database
*/
protected function findColumns($table)
{
$sql = "PRAGMA table_info(" . $this->quoteSimpleTableName($table->name) . ')';
$columns = $this->db->createCommand($sql)->queryAll();
if (empty($columns)) {
return false;
}
foreach ($columns as $info) {
$column = $this->loadColumnSchema($info);
$table->columns[$column->name] = $column;
if ($column->isPrimaryKey) {
$table->primaryKey[] = $column->name;
}
}
if (count($table->primaryKey) === 1 && !strncasecmp($table->columns[$table->primaryKey[0]]->dbType, 'int', 3)) {
$table->sequenceName = '';
$table->columns[$table->primaryKey[0]]->autoIncrement = true;
}
return true;
}
/**
* Collects the foreign key column details for the given table.
* @param TableSchema $table the table metadata
*/
protected function findConstraints($table)
{
$sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')';
$keys = $this->db->createCommand($sql)->queryAll();
foreach ($keys as $key) {
$id = (int) $key['id'];
if (!isset($table->foreignKeys[$id])) {
$table->foreignKeys[$id] = [$key['table'], $key['from'] => $key['to']];
} else {
// composite FK
$table->foreignKeys[$id][$key['from']] = $key['to'];
}
}
}
/**
* Returns all unique indexes for the given table.
* Each array element is of the following structure:
*
* ~~~
* [
* 'IndexName1' => ['col1' [, ...]],
* 'IndexName2' => ['col2' [, ...]],
* ]
* ~~~
*
* @param TableSchema $table the table metadata
* @return array all unique indexes for the given table.
*/
public function findUniqueIndexes($table)
{
$sql = "PRAGMA index_list(" . $this->quoteSimpleTableName($table->name) . ')';
$indexes = $this->db->createCommand($sql)->queryAll();
$uniqueIndexes = [];
foreach ($indexes as $index) {
$indexName = $index['name'];
$indexInfo = $this->db->createCommand("PRAGMA index_info(" . $this->quoteValue($index['name']) . ")")->queryAll();
if ($index['unique']) {
$uniqueIndexes[$indexName] = [];
foreach ($indexInfo as $row) {
$uniqueIndexes[$indexName][] = $row['name'];
}
}
}
return $uniqueIndexes;
}
/**
* Loads the column information into a [[ColumnSchema]] object.
* @param array $info column information
* @return ColumnSchema the column schema object
*/
protected function loadColumnSchema($info)
{
$column = $this->createColumnSchema();
$column->name = $info['name'];
$column->allowNull = !$info['notnull'];
$column->isPrimaryKey = $info['pk'] != 0;
$column->dbType = strtolower($info['type']);
$column->unsigned = strpos($column->dbType, 'unsigned') !== false;
$column->type = self::TYPE_STRING;
if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
$type = strtolower($matches[1]);
if (isset($this->typeMap[$type])) {
$column->type = $this->typeMap[$type];
}
if (!empty($matches[2])) {
$values = explode(',', $matches[2]);
$column->size = $column->precision = (int) $values[0];
if (isset($values[1])) {
$column->scale = (int) $values[1];
}
if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
$column->type = 'boolean';
} elseif ($type === 'bit') {
if ($column->size > 32) {
$column->type = 'bigint';
} elseif ($column->size === 32) {
$column->type = 'integer';
}
}
}
}
$column->phpType = $this->getColumnPhpType($column);
if (!$column->isPrimaryKey) {
if ($info['dflt_value'] === 'null' || $info['dflt_value'] === '' || $info['dflt_value'] === null) {
$column->defaultValue = null;
} elseif ($column->type === 'timestamp' && $info['dflt_value'] === 'CURRENT_TIMESTAMP') {
$column->defaultValue = new Expression('CURRENT_TIMESTAMP');
} else {
$value = trim($info['dflt_value'], "'\"");
$column->defaultValue = $column->phpTypecast($value);
}
}
return $column;
}
/**
* Sets the isolation level of the current transaction.
* @param string $level The transaction isolation level to use for this transaction.
* This can be either [[Transaction::READ_UNCOMMITTED]] or [[Transaction::SERIALIZABLE]].
* @throws \yii\base\NotSupportedException when unsupported isolation levels are used.
* SQLite only supports SERIALIZABLE and READ UNCOMMITTED.
* @see http://www.sqlite.org/pragma.html#pragma_read_uncommitted
*/
public function setTransactionIsolationLevel($level)
{
switch($level)
{
case Transaction::SERIALIZABLE:
$this->db->createCommand("PRAGMA read_uncommitted = False;")->execute();
break;
case Transaction::READ_UNCOMMITTED:
$this->db->createCommand("PRAGMA read_uncommitted = True;")->execute();
break;
default:
throw new NotSupportedException(get_class($this) . ' only supports transaction isolation levels READ UNCOMMITTED and SERIALIZABLE.');
}
}
}
|
Dareen/desyii2
|
www/default/vendor/yiisoft/yii2/db/sqlite/Schema.php
|
PHP
|
mit
| 10,034
|
#!/usr/bin/env perl
#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# March, May, June 2010
#
# The module implements "4-bit" GCM GHASH function and underlying
# single multiplication operation in GF(2^128). "4-bit" means that it
# uses 256 bytes per-key table [+64/128 bytes fixed table]. It has two
# code paths: vanilla x86 and vanilla MMX. Former will be executed on
# 486 and Pentium, latter on all others. MMX GHASH features so called
# "528B" variant of "4-bit" method utilizing additional 256+16 bytes
# of per-key storage [+512 bytes shared table]. Performance results
# are for streamed GHASH subroutine and are expressed in cycles per
# processed byte, less is better:
#
# gcc 2.95.3(*) MMX assembler x86 assembler
#
# Pentium 105/111(**) - 50
# PIII 68 /75 12.2 24
# P4 125/125 17.8 84(***)
# Opteron 66 /70 10.1 30
# Core2 54 /67 8.4 18
#
# (*) gcc 3.4.x was observed to generate few percent slower code,
# which is one of reasons why 2.95.3 results were chosen,
# another reason is lack of 3.4.x results for older CPUs;
# comparison with MMX results is not completely fair, because C
# results are for vanilla "256B" implementation, while
# assembler results are for "528B";-)
# (**) second number is result for code compiled with -fPIC flag,
# which is actually more relevant, because assembler code is
# position-independent;
# (***) see comment in non-MMX routine for further details;
#
# To summarize, it's >2-5 times faster than gcc-generated code. To
# anchor it to something else SHA1 assembler processes one byte in
# 11-13 cycles on contemporary x86 cores. As for choice of MMX in
# particular, see comment at the end of the file...
# May 2010
#
# Add PCLMULQDQ version performing at 2.10 cycles per processed byte.
# The question is how close is it to theoretical limit? The pclmulqdq
# instruction latency appears to be 14 cycles and there can't be more
# than 2 of them executing at any given time. This means that single
# Karatsuba multiplication would take 28 cycles *plus* few cycles for
# pre- and post-processing. Then multiplication has to be followed by
# modulo-reduction. Given that aggregated reduction method [see
# "Carry-less Multiplication and Its Usage for Computing the GCM Mode"
# white paper by Intel] allows you to perform reduction only once in
# a while we can assume that asymptotic performance can be estimated
# as (28+Tmod/Naggr)/16, where Tmod is time to perform reduction
# and Naggr is the aggregation factor.
#
# Before we proceed to this implementation let's have closer look at
# the best-performing code suggested by Intel in their white paper.
# By tracing inter-register dependencies Tmod is estimated as ~19
# cycles and Naggr chosen by Intel is 4, resulting in 2.05 cycles per
# processed byte. As implied, this is quite optimistic estimate,
# because it does not account for Karatsuba pre- and post-processing,
# which for a single multiplication is ~5 cycles. Unfortunately Intel
# does not provide performance data for GHASH alone. But benchmarking
# AES_GCM_encrypt ripped out of Fig. 15 of the white paper with aadt
# alone resulted in 2.46 cycles per byte of out 16KB buffer. Note that
# the result accounts even for pre-computing of degrees of the hash
# key H, but its portion is negligible at 16KB buffer size.
#
# Moving on to the implementation in question. Tmod is estimated as
# ~13 cycles and Naggr is 2, giving asymptotic performance of ...
# 2.16. How is it possible that measured performance is better than
# optimistic theoretical estimate? There is one thing Intel failed
# to recognize. By serializing GHASH with CTR in same subroutine
# former's performance is really limited to above (Tmul + Tmod/Naggr)
# equation. But if GHASH procedure is detached, the modulo-reduction
# can be interleaved with Naggr-1 multiplications at instruction level
# and under ideal conditions even disappear from the equation. So that
# optimistic theoretical estimate for this implementation is ...
# 28/16=1.75, and not 2.16. Well, it's probably way too optimistic,
# at least for such small Naggr. I'd argue that (28+Tproc/Naggr),
# where Tproc is time required for Karatsuba pre- and post-processing,
# is more realistic estimate. In this case it gives ... 1.91 cycles.
# Or in other words, depending on how well we can interleave reduction
# and one of the two multiplications the performance should be betwen
# 1.91 and 2.16. As already mentioned, this implementation processes
# one byte out of 8KB buffer in 2.10 cycles, while x86_64 counterpart
# - in 2.02. x86_64 performance is better, because larger register
# bank allows to interleave reduction and multiplication better.
#
# Does it make sense to increase Naggr? To start with it's virtually
# impossible in 32-bit mode, because of limited register bank
# capacity. Otherwise improvement has to be weighed agiainst slower
# setup, as well as code size and complexity increase. As even
# optimistic estimate doesn't promise 30% performance improvement,
# there are currently no plans to increase Naggr.
#
# Special thanks to David Woodhouse <dwmw2@infradead.org> for
# providing access to a Westmere-based system on behalf of Intel
# Open Source Technology Centre.
# January 2010
#
# Tweaked to optimize transitions between integer and FP operations
# on same XMM register, PCLMULQDQ subroutine was measured to process
# one byte in 2.07 cycles on Sandy Bridge, and in 2.12 - on Westmere.
# The minor regression on Westmere is outweighed by ~15% improvement
# on Sandy Bridge. Strangely enough attempt to modify 64-bit code in
# similar manner resulted in almost 20% degradation on Sandy Bridge,
# where original 64-bit code processes one byte in 1.95 cycles.
$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
push(@INC,"${dir}","${dir}../../perlasm");
require "x86asm.pl";
&asm_init($ARGV[0],"ghash-x86.pl",$x86only = $ARGV[$#ARGV] eq "386");
$sse2=0;
for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); }
($Zhh,$Zhl,$Zlh,$Zll) = ("ebp","edx","ecx","ebx");
$inp = "edi";
$Htbl = "esi";
$unroll = 0; # Affects x86 loop. Folded loop performs ~7% worse
# than unrolled, which has to be weighted against
# 2.5x x86-specific code size reduction.
sub x86_loop {
my $off = shift;
my $rem = "eax";
&mov ($Zhh,&DWP(4,$Htbl,$Zll));
&mov ($Zhl,&DWP(0,$Htbl,$Zll));
&mov ($Zlh,&DWP(12,$Htbl,$Zll));
&mov ($Zll,&DWP(8,$Htbl,$Zll));
&xor ($rem,$rem); # avoid partial register stalls on PIII
# shrd practically kills P4, 2.5x deterioration, but P4 has
# MMX code-path to execute. shrd runs tad faster [than twice
# the shifts, move's and or's] on pre-MMX Pentium (as well as
# PIII and Core2), *but* minimizes code size, spares register
# and thus allows to fold the loop...
if (!$unroll) {
my $cnt = $inp;
&mov ($cnt,15);
&jmp (&label("x86_loop"));
&set_label("x86_loop",16);
for($i=1;$i<=2;$i++) {
&mov (&LB($rem),&LB($Zll));
&shrd ($Zll,$Zlh,4);
&and (&LB($rem),0xf);
&shrd ($Zlh,$Zhl,4);
&shrd ($Zhl,$Zhh,4);
&shr ($Zhh,4);
&xor ($Zhh,&DWP($off+16,"esp",$rem,4));
&mov (&LB($rem),&BP($off,"esp",$cnt));
if ($i&1) {
&and (&LB($rem),0xf0);
} else {
&shl (&LB($rem),4);
}
&xor ($Zll,&DWP(8,$Htbl,$rem));
&xor ($Zlh,&DWP(12,$Htbl,$rem));
&xor ($Zhl,&DWP(0,$Htbl,$rem));
&xor ($Zhh,&DWP(4,$Htbl,$rem));
if ($i&1) {
&dec ($cnt);
&js (&label("x86_break"));
} else {
&jmp (&label("x86_loop"));
}
}
&set_label("x86_break",16);
} else {
for($i=1;$i<32;$i++) {
&comment($i);
&mov (&LB($rem),&LB($Zll));
&shrd ($Zll,$Zlh,4);
&and (&LB($rem),0xf);
&shrd ($Zlh,$Zhl,4);
&shrd ($Zhl,$Zhh,4);
&shr ($Zhh,4);
&xor ($Zhh,&DWP($off+16,"esp",$rem,4));
if ($i&1) {
&mov (&LB($rem),&BP($off+15-($i>>1),"esp"));
&and (&LB($rem),0xf0);
} else {
&mov (&LB($rem),&BP($off+15-($i>>1),"esp"));
&shl (&LB($rem),4);
}
&xor ($Zll,&DWP(8,$Htbl,$rem));
&xor ($Zlh,&DWP(12,$Htbl,$rem));
&xor ($Zhl,&DWP(0,$Htbl,$rem));
&xor ($Zhh,&DWP(4,$Htbl,$rem));
}
}
&bswap ($Zll);
&bswap ($Zlh);
&bswap ($Zhl);
if (!$x86only) {
&bswap ($Zhh);
} else {
&mov ("eax",$Zhh);
&bswap ("eax");
&mov ($Zhh,"eax");
}
}
if ($unroll) {
&function_begin_B("_x86_gmult_4bit_inner");
&x86_loop(4);
&ret ();
&function_end_B("_x86_gmult_4bit_inner");
}
sub deposit_rem_4bit {
my $bias = shift;
&mov (&DWP($bias+0, "esp"),0x0000<<16);
&mov (&DWP($bias+4, "esp"),0x1C20<<16);
&mov (&DWP($bias+8, "esp"),0x3840<<16);
&mov (&DWP($bias+12,"esp"),0x2460<<16);
&mov (&DWP($bias+16,"esp"),0x7080<<16);
&mov (&DWP($bias+20,"esp"),0x6CA0<<16);
&mov (&DWP($bias+24,"esp"),0x48C0<<16);
&mov (&DWP($bias+28,"esp"),0x54E0<<16);
&mov (&DWP($bias+32,"esp"),0xE100<<16);
&mov (&DWP($bias+36,"esp"),0xFD20<<16);
&mov (&DWP($bias+40,"esp"),0xD940<<16);
&mov (&DWP($bias+44,"esp"),0xC560<<16);
&mov (&DWP($bias+48,"esp"),0x9180<<16);
&mov (&DWP($bias+52,"esp"),0x8DA0<<16);
&mov (&DWP($bias+56,"esp"),0xA9C0<<16);
&mov (&DWP($bias+60,"esp"),0xB5E0<<16);
}
$suffix = $x86only ? "" : "_x86";
&function_begin("gcm_gmult_4bit".$suffix);
&stack_push(16+4+1); # +1 for stack alignment
&mov ($inp,&wparam(0)); # load Xi
&mov ($Htbl,&wparam(1)); # load Htable
&mov ($Zhh,&DWP(0,$inp)); # load Xi[16]
&mov ($Zhl,&DWP(4,$inp));
&mov ($Zlh,&DWP(8,$inp));
&mov ($Zll,&DWP(12,$inp));
&deposit_rem_4bit(16);
&mov (&DWP(0,"esp"),$Zhh); # copy Xi[16] on stack
&mov (&DWP(4,"esp"),$Zhl);
&mov (&DWP(8,"esp"),$Zlh);
&mov (&DWP(12,"esp"),$Zll);
&shr ($Zll,20);
&and ($Zll,0xf0);
if ($unroll) {
&call ("_x86_gmult_4bit_inner");
} else {
&x86_loop(0);
&mov ($inp,&wparam(0));
}
&mov (&DWP(12,$inp),$Zll);
&mov (&DWP(8,$inp),$Zlh);
&mov (&DWP(4,$inp),$Zhl);
&mov (&DWP(0,$inp),$Zhh);
&stack_pop(16+4+1);
&function_end("gcm_gmult_4bit".$suffix);
&function_begin("gcm_ghash_4bit".$suffix);
&stack_push(16+4+1); # +1 for 64-bit alignment
&mov ($Zll,&wparam(0)); # load Xi
&mov ($Htbl,&wparam(1)); # load Htable
&mov ($inp,&wparam(2)); # load in
&mov ("ecx",&wparam(3)); # load len
&add ("ecx",$inp);
&mov (&wparam(3),"ecx");
&mov ($Zhh,&DWP(0,$Zll)); # load Xi[16]
&mov ($Zhl,&DWP(4,$Zll));
&mov ($Zlh,&DWP(8,$Zll));
&mov ($Zll,&DWP(12,$Zll));
&deposit_rem_4bit(16);
&set_label("x86_outer_loop",16);
&xor ($Zll,&DWP(12,$inp)); # xor with input
&xor ($Zlh,&DWP(8,$inp));
&xor ($Zhl,&DWP(4,$inp));
&xor ($Zhh,&DWP(0,$inp));
&mov (&DWP(12,"esp"),$Zll); # dump it on stack
&mov (&DWP(8,"esp"),$Zlh);
&mov (&DWP(4,"esp"),$Zhl);
&mov (&DWP(0,"esp"),$Zhh);
&shr ($Zll,20);
&and ($Zll,0xf0);
if ($unroll) {
&call ("_x86_gmult_4bit_inner");
} else {
&x86_loop(0);
&mov ($inp,&wparam(2));
}
&lea ($inp,&DWP(16,$inp));
&cmp ($inp,&wparam(3));
&mov (&wparam(2),$inp) if (!$unroll);
&jb (&label("x86_outer_loop"));
&mov ($inp,&wparam(0)); # load Xi
&mov (&DWP(12,$inp),$Zll);
&mov (&DWP(8,$inp),$Zlh);
&mov (&DWP(4,$inp),$Zhl);
&mov (&DWP(0,$inp),$Zhh);
&stack_pop(16+4+1);
&function_end("gcm_ghash_4bit".$suffix);
if (!$x86only) {{{
&static_label("rem_4bit");
if (!$sse2) {{ # pure-MMX "May" version...
$S=12; # shift factor for rem_4bit
&function_begin_B("_mmx_gmult_4bit_inner");
# MMX version performs 3.5 times better on P4 (see comment in non-MMX
# routine for further details), 100% better on Opteron, ~70% better
# on Core2 and PIII... In other words effort is considered to be well
# spent... Since initial release the loop was unrolled in order to
# "liberate" register previously used as loop counter. Instead it's
# used to optimize critical path in 'Z.hi ^= rem_4bit[Z.lo&0xf]'.
# The path involves move of Z.lo from MMX to integer register,
# effective address calculation and finally merge of value to Z.hi.
# Reference to rem_4bit is scheduled so late that I had to >>4
# rem_4bit elements. This resulted in 20-45% procent improvement
# on contemporary µ-archs.
{
my $cnt;
my $rem_4bit = "eax";
my @rem = ($Zhh,$Zll);
my $nhi = $Zhl;
my $nlo = $Zlh;
my ($Zlo,$Zhi) = ("mm0","mm1");
my $tmp = "mm2";
&xor ($nlo,$nlo); # avoid partial register stalls on PIII
&mov ($nhi,$Zll);
&mov (&LB($nlo),&LB($nhi));
&shl (&LB($nlo),4);
&and ($nhi,0xf0);
&movq ($Zlo,&QWP(8,$Htbl,$nlo));
&movq ($Zhi,&QWP(0,$Htbl,$nlo));
&movd ($rem[0],$Zlo);
for ($cnt=28;$cnt>=-2;$cnt--) {
my $odd = $cnt&1;
my $nix = $odd ? $nlo : $nhi;
&shl (&LB($nlo),4) if ($odd);
&psrlq ($Zlo,4);
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&pxor ($Zlo,&QWP(8,$Htbl,$nix));
&mov (&LB($nlo),&BP($cnt/2,$inp)) if (!$odd && $cnt>=0);
&psllq ($tmp,60);
&and ($nhi,0xf0) if ($odd);
&pxor ($Zhi,&QWP(0,$rem_4bit,$rem[1],8)) if ($cnt<28);
&and ($rem[0],0xf);
&pxor ($Zhi,&QWP(0,$Htbl,$nix));
&mov ($nhi,$nlo) if (!$odd && $cnt>=0);
&movd ($rem[1],$Zlo);
&pxor ($Zlo,$tmp);
push (@rem,shift(@rem)); # "rotate" registers
}
&mov ($inp,&DWP(4,$rem_4bit,$rem[1],8)); # last rem_4bit[rem]
&psrlq ($Zlo,32); # lower part of Zlo is already there
&movd ($Zhl,$Zhi);
&psrlq ($Zhi,32);
&movd ($Zlh,$Zlo);
&movd ($Zhh,$Zhi);
&shl ($inp,4); # compensate for rem_4bit[i] being >>4
&bswap ($Zll);
&bswap ($Zhl);
&bswap ($Zlh);
&xor ($Zhh,$inp);
&bswap ($Zhh);
&ret ();
}
&function_end_B("_mmx_gmult_4bit_inner");
&function_begin("gcm_gmult_4bit_mmx");
&mov ($inp,&wparam(0)); # load Xi
&mov ($Htbl,&wparam(1)); # load Htable
&call (&label("pic_point"));
&set_label("pic_point");
&blindpop("eax");
&lea ("eax",&DWP(&label("rem_4bit")."-".&label("pic_point"),"eax"));
&movz ($Zll,&BP(15,$inp));
&call ("_mmx_gmult_4bit_inner");
&mov ($inp,&wparam(0)); # load Xi
&emms ();
&mov (&DWP(12,$inp),$Zll);
&mov (&DWP(4,$inp),$Zhl);
&mov (&DWP(8,$inp),$Zlh);
&mov (&DWP(0,$inp),$Zhh);
&function_end("gcm_gmult_4bit_mmx");
# Streamed version performs 20% better on P4, 7% on Opteron,
# 10% on Core2 and PIII...
&function_begin("gcm_ghash_4bit_mmx");
&mov ($Zhh,&wparam(0)); # load Xi
&mov ($Htbl,&wparam(1)); # load Htable
&mov ($inp,&wparam(2)); # load in
&mov ($Zlh,&wparam(3)); # load len
&call (&label("pic_point"));
&set_label("pic_point");
&blindpop("eax");
&lea ("eax",&DWP(&label("rem_4bit")."-".&label("pic_point"),"eax"));
&add ($Zlh,$inp);
&mov (&wparam(3),$Zlh); # len to point at the end of input
&stack_push(4+1); # +1 for stack alignment
&mov ($Zll,&DWP(12,$Zhh)); # load Xi[16]
&mov ($Zhl,&DWP(4,$Zhh));
&mov ($Zlh,&DWP(8,$Zhh));
&mov ($Zhh,&DWP(0,$Zhh));
&jmp (&label("mmx_outer_loop"));
&set_label("mmx_outer_loop",16);
&xor ($Zll,&DWP(12,$inp));
&xor ($Zhl,&DWP(4,$inp));
&xor ($Zlh,&DWP(8,$inp));
&xor ($Zhh,&DWP(0,$inp));
&mov (&wparam(2),$inp);
&mov (&DWP(12,"esp"),$Zll);
&mov (&DWP(4,"esp"),$Zhl);
&mov (&DWP(8,"esp"),$Zlh);
&mov (&DWP(0,"esp"),$Zhh);
&mov ($inp,"esp");
&shr ($Zll,24);
&call ("_mmx_gmult_4bit_inner");
&mov ($inp,&wparam(2));
&lea ($inp,&DWP(16,$inp));
&cmp ($inp,&wparam(3));
&jb (&label("mmx_outer_loop"));
&mov ($inp,&wparam(0)); # load Xi
&emms ();
&mov (&DWP(12,$inp),$Zll);
&mov (&DWP(4,$inp),$Zhl);
&mov (&DWP(8,$inp),$Zlh);
&mov (&DWP(0,$inp),$Zhh);
&stack_pop(4+1);
&function_end("gcm_ghash_4bit_mmx");
}} else {{ # "June" MMX version...
# ... has slower "April" gcm_gmult_4bit_mmx with folded
# loop. This is done to conserve code size...
$S=16; # shift factor for rem_4bit
sub mmx_loop() {
# MMX version performs 2.8 times better on P4 (see comment in non-MMX
# routine for further details), 40% better on Opteron and Core2, 50%
# better on PIII... In other words effort is considered to be well
# spent...
my $inp = shift;
my $rem_4bit = shift;
my $cnt = $Zhh;
my $nhi = $Zhl;
my $nlo = $Zlh;
my $rem = $Zll;
my ($Zlo,$Zhi) = ("mm0","mm1");
my $tmp = "mm2";
&xor ($nlo,$nlo); # avoid partial register stalls on PIII
&mov ($nhi,$Zll);
&mov (&LB($nlo),&LB($nhi));
&mov ($cnt,14);
&shl (&LB($nlo),4);
&and ($nhi,0xf0);
&movq ($Zlo,&QWP(8,$Htbl,$nlo));
&movq ($Zhi,&QWP(0,$Htbl,$nlo));
&movd ($rem,$Zlo);
&jmp (&label("mmx_loop"));
&set_label("mmx_loop",16);
&psrlq ($Zlo,4);
&and ($rem,0xf);
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&pxor ($Zlo,&QWP(8,$Htbl,$nhi));
&mov (&LB($nlo),&BP(0,$inp,$cnt));
&psllq ($tmp,60);
&pxor ($Zhi,&QWP(0,$rem_4bit,$rem,8));
&dec ($cnt);
&movd ($rem,$Zlo);
&pxor ($Zhi,&QWP(0,$Htbl,$nhi));
&mov ($nhi,$nlo);
&pxor ($Zlo,$tmp);
&js (&label("mmx_break"));
&shl (&LB($nlo),4);
&and ($rem,0xf);
&psrlq ($Zlo,4);
&and ($nhi,0xf0);
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&pxor ($Zlo,&QWP(8,$Htbl,$nlo));
&psllq ($tmp,60);
&pxor ($Zhi,&QWP(0,$rem_4bit,$rem,8));
&movd ($rem,$Zlo);
&pxor ($Zhi,&QWP(0,$Htbl,$nlo));
&pxor ($Zlo,$tmp);
&jmp (&label("mmx_loop"));
&set_label("mmx_break",16);
&shl (&LB($nlo),4);
&and ($rem,0xf);
&psrlq ($Zlo,4);
&and ($nhi,0xf0);
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&pxor ($Zlo,&QWP(8,$Htbl,$nlo));
&psllq ($tmp,60);
&pxor ($Zhi,&QWP(0,$rem_4bit,$rem,8));
&movd ($rem,$Zlo);
&pxor ($Zhi,&QWP(0,$Htbl,$nlo));
&pxor ($Zlo,$tmp);
&psrlq ($Zlo,4);
&and ($rem,0xf);
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&pxor ($Zlo,&QWP(8,$Htbl,$nhi));
&psllq ($tmp,60);
&pxor ($Zhi,&QWP(0,$rem_4bit,$rem,8));
&movd ($rem,$Zlo);
&pxor ($Zhi,&QWP(0,$Htbl,$nhi));
&pxor ($Zlo,$tmp);
&psrlq ($Zlo,32); # lower part of Zlo is already there
&movd ($Zhl,$Zhi);
&psrlq ($Zhi,32);
&movd ($Zlh,$Zlo);
&movd ($Zhh,$Zhi);
&bswap ($Zll);
&bswap ($Zhl);
&bswap ($Zlh);
&bswap ($Zhh);
}
&function_begin("gcm_gmult_4bit_mmx");
&mov ($inp,&wparam(0)); # load Xi
&mov ($Htbl,&wparam(1)); # load Htable
&call (&label("pic_point"));
&set_label("pic_point");
&blindpop("eax");
&lea ("eax",&DWP(&label("rem_4bit")."-".&label("pic_point"),"eax"));
&movz ($Zll,&BP(15,$inp));
&mmx_loop($inp,"eax");
&emms ();
&mov (&DWP(12,$inp),$Zll);
&mov (&DWP(4,$inp),$Zhl);
&mov (&DWP(8,$inp),$Zlh);
&mov (&DWP(0,$inp),$Zhh);
&function_end("gcm_gmult_4bit_mmx");
######################################################################
# Below subroutine is "528B" variant of "4-bit" GCM GHASH function
# (see gcm128.c for details). It provides further 20-40% performance
# improvement over above mentioned "May" version.
&static_label("rem_8bit");
&function_begin("gcm_ghash_4bit_mmx");
{ my ($Zlo,$Zhi) = ("mm7","mm6");
my $rem_8bit = "esi";
my $Htbl = "ebx";
# parameter block
&mov ("eax",&wparam(0)); # Xi
&mov ("ebx",&wparam(1)); # Htable
&mov ("ecx",&wparam(2)); # inp
&mov ("edx",&wparam(3)); # len
&mov ("ebp","esp"); # original %esp
&call (&label("pic_point"));
&set_label ("pic_point");
&blindpop ($rem_8bit);
&lea ($rem_8bit,&DWP(&label("rem_8bit")."-".&label("pic_point"),$rem_8bit));
&sub ("esp",512+16+16); # allocate stack frame...
&and ("esp",-64); # ...and align it
&sub ("esp",16); # place for (u8)(H[]<<4)
&add ("edx","ecx"); # pointer to the end of input
&mov (&DWP(528+16+0,"esp"),"eax"); # save Xi
&mov (&DWP(528+16+8,"esp"),"edx"); # save inp+len
&mov (&DWP(528+16+12,"esp"),"ebp"); # save original %esp
{ my @lo = ("mm0","mm1","mm2");
my @hi = ("mm3","mm4","mm5");
my @tmp = ("mm6","mm7");
my ($off1,$off2,$i) = (0,0,);
&add ($Htbl,128); # optimize for size
&lea ("edi",&DWP(16+128,"esp"));
&lea ("ebp",&DWP(16+256+128,"esp"));
# decompose Htable (low and high parts are kept separately),
# generate Htable[]>>4, (u8)(Htable[]<<4), save to stack...
for ($i=0;$i<18;$i++) {
&mov ("edx",&DWP(16*$i+8-128,$Htbl)) if ($i<16);
&movq ($lo[0],&QWP(16*$i+8-128,$Htbl)) if ($i<16);
&psllq ($tmp[1],60) if ($i>1);
&movq ($hi[0],&QWP(16*$i+0-128,$Htbl)) if ($i<16);
&por ($lo[2],$tmp[1]) if ($i>1);
&movq (&QWP($off1-128,"edi"),$lo[1]) if ($i>0 && $i<17);
&psrlq ($lo[1],4) if ($i>0 && $i<17);
&movq (&QWP($off1,"edi"),$hi[1]) if ($i>0 && $i<17);
&movq ($tmp[0],$hi[1]) if ($i>0 && $i<17);
&movq (&QWP($off2-128,"ebp"),$lo[2]) if ($i>1);
&psrlq ($hi[1],4) if ($i>0 && $i<17);
&movq (&QWP($off2,"ebp"),$hi[2]) if ($i>1);
&shl ("edx",4) if ($i<16);
&mov (&BP($i,"esp"),&LB("edx")) if ($i<16);
unshift (@lo,pop(@lo)); # "rotate" registers
unshift (@hi,pop(@hi));
unshift (@tmp,pop(@tmp));
$off1 += 8 if ($i>0);
$off2 += 8 if ($i>1);
}
}
&movq ($Zhi,&QWP(0,"eax"));
&mov ("ebx",&DWP(8,"eax"));
&mov ("edx",&DWP(12,"eax")); # load Xi
&set_label("outer",16);
{ my $nlo = "eax";
my $dat = "edx";
my @nhi = ("edi","ebp");
my @rem = ("ebx","ecx");
my @red = ("mm0","mm1","mm2");
my $tmp = "mm3";
&xor ($dat,&DWP(12,"ecx")); # merge input data
&xor ("ebx",&DWP(8,"ecx"));
&pxor ($Zhi,&QWP(0,"ecx"));
&lea ("ecx",&DWP(16,"ecx")); # inp+=16
#&mov (&DWP(528+12,"esp"),$dat); # save inp^Xi
&mov (&DWP(528+8,"esp"),"ebx");
&movq (&QWP(528+0,"esp"),$Zhi);
&mov (&DWP(528+16+4,"esp"),"ecx"); # save inp
&xor ($nlo,$nlo);
&rol ($dat,8);
&mov (&LB($nlo),&LB($dat));
&mov ($nhi[1],$nlo);
&and (&LB($nlo),0x0f);
&shr ($nhi[1],4);
&pxor ($red[0],$red[0]);
&rol ($dat,8); # next byte
&pxor ($red[1],$red[1]);
&pxor ($red[2],$red[2]);
# Just like in "May" verson modulo-schedule for critical path in
# 'Z.hi ^= rem_8bit[Z.lo&0xff^((u8)H[nhi]<<4)]<<48'. Final 'pxor'
# is scheduled so late that rem_8bit[] has to be shifted *right*
# by 16, which is why last argument to pinsrw is 2, which
# corresponds to <<32=<<48>>16...
for ($j=11,$i=0;$i<15;$i++) {
if ($i>0) {
&pxor ($Zlo,&QWP(16,"esp",$nlo,8)); # Z^=H[nlo]
&rol ($dat,8); # next byte
&pxor ($Zhi,&QWP(16+128,"esp",$nlo,8));
&pxor ($Zlo,$tmp);
&pxor ($Zhi,&QWP(16+256+128,"esp",$nhi[0],8));
&xor (&LB($rem[1]),&BP(0,"esp",$nhi[0])); # rem^(H[nhi]<<4)
} else {
&movq ($Zlo,&QWP(16,"esp",$nlo,8));
&movq ($Zhi,&QWP(16+128,"esp",$nlo,8));
}
&mov (&LB($nlo),&LB($dat));
&mov ($dat,&DWP(528+$j,"esp")) if (--$j%4==0);
&movd ($rem[0],$Zlo);
&movz ($rem[1],&LB($rem[1])) if ($i>0);
&psrlq ($Zlo,8); # Z>>=8
&movq ($tmp,$Zhi);
&mov ($nhi[0],$nlo);
&psrlq ($Zhi,8);
&pxor ($Zlo,&QWP(16+256+0,"esp",$nhi[1],8)); # Z^=H[nhi]>>4
&and (&LB($nlo),0x0f);
&psllq ($tmp,56);
&pxor ($Zhi,$red[1]) if ($i>1);
&shr ($nhi[0],4);
&pinsrw ($red[0],&WP(0,$rem_8bit,$rem[1],2),2) if ($i>0);
unshift (@red,pop(@red)); # "rotate" registers
unshift (@rem,pop(@rem));
unshift (@nhi,pop(@nhi));
}
&pxor ($Zlo,&QWP(16,"esp",$nlo,8)); # Z^=H[nlo]
&pxor ($Zhi,&QWP(16+128,"esp",$nlo,8));
&xor (&LB($rem[1]),&BP(0,"esp",$nhi[0])); # rem^(H[nhi]<<4)
&pxor ($Zlo,$tmp);
&pxor ($Zhi,&QWP(16+256+128,"esp",$nhi[0],8));
&movz ($rem[1],&LB($rem[1]));
&pxor ($red[2],$red[2]); # clear 2nd word
&psllq ($red[1],4);
&movd ($rem[0],$Zlo);
&psrlq ($Zlo,4); # Z>>=4
&movq ($tmp,$Zhi);
&psrlq ($Zhi,4);
&shl ($rem[0],4); # rem<<4
&pxor ($Zlo,&QWP(16,"esp",$nhi[1],8)); # Z^=H[nhi]
&psllq ($tmp,60);
&movz ($rem[0],&LB($rem[0]));
&pxor ($Zlo,$tmp);
&pxor ($Zhi,&QWP(16+128,"esp",$nhi[1],8));
&pinsrw ($red[0],&WP(0,$rem_8bit,$rem[1],2),2);
&pxor ($Zhi,$red[1]);
&movd ($dat,$Zlo);
&pinsrw ($red[2],&WP(0,$rem_8bit,$rem[0],2),3); # last is <<48
&psllq ($red[0],12); # correct by <<16>>4
&pxor ($Zhi,$red[0]);
&psrlq ($Zlo,32);
&pxor ($Zhi,$red[2]);
&mov ("ecx",&DWP(528+16+4,"esp")); # restore inp
&movd ("ebx",$Zlo);
&movq ($tmp,$Zhi); # 01234567
&psllw ($Zhi,8); # 1.3.5.7.
&psrlw ($tmp,8); # .0.2.4.6
&por ($Zhi,$tmp); # 10325476
&bswap ($dat);
&pshufw ($Zhi,$Zhi,0b00011011); # 76543210
&bswap ("ebx");
&cmp ("ecx",&DWP(528+16+8,"esp")); # are we done?
&jne (&label("outer"));
}
&mov ("eax",&DWP(528+16+0,"esp")); # restore Xi
&mov (&DWP(12,"eax"),"edx");
&mov (&DWP(8,"eax"),"ebx");
&movq (&QWP(0,"eax"),$Zhi);
&mov ("esp",&DWP(528+16+12,"esp")); # restore original %esp
&emms ();
}
&function_end("gcm_ghash_4bit_mmx");
}}
if ($sse2) {{
######################################################################
# PCLMULQDQ version.
$Xip="eax";
$Htbl="edx";
$const="ecx";
$inp="esi";
$len="ebx";
($Xi,$Xhi)=("xmm0","xmm1"); $Hkey="xmm2";
($T1,$T2,$T3)=("xmm3","xmm4","xmm5");
($Xn,$Xhn)=("xmm6","xmm7");
&static_label("bswap");
sub clmul64x64_T2 { # minimal "register" pressure
my ($Xhi,$Xi,$Hkey)=@_;
&movdqa ($Xhi,$Xi); #
&pshufd ($T1,$Xi,0b01001110);
&pshufd ($T2,$Hkey,0b01001110);
&pxor ($T1,$Xi); #
&pxor ($T2,$Hkey);
&pclmulqdq ($Xi,$Hkey,0x00); #######
&pclmulqdq ($Xhi,$Hkey,0x11); #######
&pclmulqdq ($T1,$T2,0x00); #######
&xorps ($T1,$Xi); #
&xorps ($T1,$Xhi); #
&movdqa ($T2,$T1); #
&psrldq ($T1,8);
&pslldq ($T2,8); #
&pxor ($Xhi,$T1);
&pxor ($Xi,$T2); #
}
sub clmul64x64_T3 {
# Even though this subroutine offers visually better ILP, it
# was empirically found to be a tad slower than above version.
# At least in gcm_ghash_clmul context. But it's just as well,
# because loop modulo-scheduling is possible only thanks to
# minimized "register" pressure...
my ($Xhi,$Xi,$Hkey)=@_;
&movdqa ($T1,$Xi); #
&movdqa ($Xhi,$Xi);
&pclmulqdq ($Xi,$Hkey,0x00); #######
&pclmulqdq ($Xhi,$Hkey,0x11); #######
&pshufd ($T2,$T1,0b01001110); #
&pshufd ($T3,$Hkey,0b01001110);
&pxor ($T2,$T1); #
&pxor ($T3,$Hkey);
&pclmulqdq ($T2,$T3,0x00); #######
&pxor ($T2,$Xi); #
&pxor ($T2,$Xhi); #
&movdqa ($T3,$T2); #
&psrldq ($T2,8);
&pslldq ($T3,8); #
&pxor ($Xhi,$T2);
&pxor ($Xi,$T3); #
}
if (1) { # Algorithm 9 with <<1 twist.
# Reduction is shorter and uses only two
# temporary registers, which makes it better
# candidate for interleaving with 64x64
# multiplication. Pre-modulo-scheduled loop
# was found to be ~20% faster than Algorithm 5
# below. Algorithm 9 was therefore chosen for
# further optimization...
sub reduction_alg9 { # 17/13 times faster than Intel version
my ($Xhi,$Xi) = @_;
# 1st phase
&movdqa ($T1,$Xi); #
&psllq ($Xi,1);
&pxor ($Xi,$T1); #
&psllq ($Xi,5); #
&pxor ($Xi,$T1); #
&psllq ($Xi,57); #
&movdqa ($T2,$Xi); #
&pslldq ($Xi,8);
&psrldq ($T2,8); #
&pxor ($Xi,$T1);
&pxor ($Xhi,$T2); #
# 2nd phase
&movdqa ($T2,$Xi);
&psrlq ($Xi,5);
&pxor ($Xi,$T2); #
&psrlq ($Xi,1); #
&pxor ($Xi,$T2); #
&pxor ($T2,$Xhi);
&psrlq ($Xi,1); #
&pxor ($Xi,$T2); #
}
&function_begin_B("gcm_init_clmul");
&mov ($Htbl,&wparam(0));
&mov ($Xip,&wparam(1));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Hkey,&QWP(0,$Xip));
&pshufd ($Hkey,$Hkey,0b01001110);# dword swap
# <<1 twist
&pshufd ($T2,$Hkey,0b11111111); # broadcast uppermost dword
&movdqa ($T1,$Hkey);
&psllq ($Hkey,1);
&pxor ($T3,$T3); #
&psrlq ($T1,63);
&pcmpgtd ($T3,$T2); # broadcast carry bit
&pslldq ($T1,8);
&por ($Hkey,$T1); # H<<=1
# magic reduction
&pand ($T3,&QWP(16,$const)); # 0x1c2_polynomial
&pxor ($Hkey,$T3); # if(carry) H^=0x1c2_polynomial
# calculate H^2
&movdqa ($Xi,$Hkey);
&clmul64x64_T2 ($Xhi,$Xi,$Hkey);
&reduction_alg9 ($Xhi,$Xi);
&movdqu (&QWP(0,$Htbl),$Hkey); # save H
&movdqu (&QWP(16,$Htbl),$Xi); # save H^2
&ret ();
&function_end_B("gcm_init_clmul");
&function_begin_B("gcm_gmult_clmul");
&mov ($Xip,&wparam(0));
&mov ($Htbl,&wparam(1));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Xi,&QWP(0,$Xip));
&movdqa ($T3,&QWP(0,$const));
&movups ($Hkey,&QWP(0,$Htbl));
&pshufb ($Xi,$T3);
&clmul64x64_T2 ($Xhi,$Xi,$Hkey);
&reduction_alg9 ($Xhi,$Xi);
&pshufb ($Xi,$T3);
&movdqu (&QWP(0,$Xip),$Xi);
&ret ();
&function_end_B("gcm_gmult_clmul");
&function_begin("gcm_ghash_clmul");
&mov ($Xip,&wparam(0));
&mov ($Htbl,&wparam(1));
&mov ($inp,&wparam(2));
&mov ($len,&wparam(3));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Xi,&QWP(0,$Xip));
&movdqa ($T3,&QWP(0,$const));
&movdqu ($Hkey,&QWP(0,$Htbl));
&pshufb ($Xi,$T3);
&sub ($len,0x10);
&jz (&label("odd_tail"));
#######
# Xi+2 =[H*(Ii+1 + Xi+1)] mod P =
# [(H*Ii+1) + (H*Xi+1)] mod P =
# [(H*Ii+1) + H^2*(Ii+Xi)] mod P
#
&movdqu ($T1,&QWP(0,$inp)); # Ii
&movdqu ($Xn,&QWP(16,$inp)); # Ii+1
&pshufb ($T1,$T3);
&pshufb ($Xn,$T3);
&pxor ($Xi,$T1); # Ii+Xi
&clmul64x64_T2 ($Xhn,$Xn,$Hkey); # H*Ii+1
&movups ($Hkey,&QWP(16,$Htbl)); # load H^2
&lea ($inp,&DWP(32,$inp)); # i+=2
&sub ($len,0x20);
&jbe (&label("even_tail"));
&set_label("mod_loop");
&clmul64x64_T2 ($Xhi,$Xi,$Hkey); # H^2*(Ii+Xi)
&movdqu ($T1,&QWP(0,$inp)); # Ii
&movups ($Hkey,&QWP(0,$Htbl)); # load H
&pxor ($Xi,$Xn); # (H*Ii+1) + H^2*(Ii+Xi)
&pxor ($Xhi,$Xhn);
&movdqu ($Xn,&QWP(16,$inp)); # Ii+1
&pshufb ($T1,$T3);
&pshufb ($Xn,$T3);
&movdqa ($T3,$Xn); #&clmul64x64_TX ($Xhn,$Xn,$Hkey); H*Ii+1
&movdqa ($Xhn,$Xn);
&pxor ($Xhi,$T1); # "Ii+Xi", consume early
&movdqa ($T1,$Xi); #&reduction_alg9($Xhi,$Xi); 1st phase
&psllq ($Xi,1);
&pxor ($Xi,$T1); #
&psllq ($Xi,5); #
&pxor ($Xi,$T1); #
&pclmulqdq ($Xn,$Hkey,0x00); #######
&psllq ($Xi,57); #
&movdqa ($T2,$Xi); #
&pslldq ($Xi,8);
&psrldq ($T2,8); #
&pxor ($Xi,$T1);
&pshufd ($T1,$T3,0b01001110);
&pxor ($Xhi,$T2); #
&pxor ($T1,$T3);
&pshufd ($T3,$Hkey,0b01001110);
&pxor ($T3,$Hkey); #
&pclmulqdq ($Xhn,$Hkey,0x11); #######
&movdqa ($T2,$Xi); # 2nd phase
&psrlq ($Xi,5);
&pxor ($Xi,$T2); #
&psrlq ($Xi,1); #
&pxor ($Xi,$T2); #
&pxor ($T2,$Xhi);
&psrlq ($Xi,1); #
&pxor ($Xi,$T2); #
&pclmulqdq ($T1,$T3,0x00); #######
&movups ($Hkey,&QWP(16,$Htbl)); # load H^2
&xorps ($T1,$Xn); #
&xorps ($T1,$Xhn); #
&movdqa ($T3,$T1); #
&psrldq ($T1,8);
&pslldq ($T3,8); #
&pxor ($Xhn,$T1);
&pxor ($Xn,$T3); #
&movdqa ($T3,&QWP(0,$const));
&lea ($inp,&DWP(32,$inp));
&sub ($len,0x20);
&ja (&label("mod_loop"));
&set_label("even_tail");
&clmul64x64_T2 ($Xhi,$Xi,$Hkey); # H^2*(Ii+Xi)
&pxor ($Xi,$Xn); # (H*Ii+1) + H^2*(Ii+Xi)
&pxor ($Xhi,$Xhn);
&reduction_alg9 ($Xhi,$Xi);
&test ($len,$len);
&jnz (&label("done"));
&movups ($Hkey,&QWP(0,$Htbl)); # load H
&set_label("odd_tail");
&movdqu ($T1,&QWP(0,$inp)); # Ii
&pshufb ($T1,$T3);
&pxor ($Xi,$T1); # Ii+Xi
&clmul64x64_T2 ($Xhi,$Xi,$Hkey); # H*(Ii+Xi)
&reduction_alg9 ($Xhi,$Xi);
&set_label("done");
&pshufb ($Xi,$T3);
&movdqu (&QWP(0,$Xip),$Xi);
&function_end("gcm_ghash_clmul");
} else { # Algorith 5. Kept for reference purposes.
sub reduction_alg5 { # 19/16 times faster than Intel version
my ($Xhi,$Xi)=@_;
# <<1
&movdqa ($T1,$Xi); #
&movdqa ($T2,$Xhi);
&pslld ($Xi,1);
&pslld ($Xhi,1); #
&psrld ($T1,31);
&psrld ($T2,31); #
&movdqa ($T3,$T1);
&pslldq ($T1,4);
&psrldq ($T3,12); #
&pslldq ($T2,4);
&por ($Xhi,$T3); #
&por ($Xi,$T1);
&por ($Xhi,$T2); #
# 1st phase
&movdqa ($T1,$Xi);
&movdqa ($T2,$Xi);
&movdqa ($T3,$Xi); #
&pslld ($T1,31);
&pslld ($T2,30);
&pslld ($Xi,25); #
&pxor ($T1,$T2);
&pxor ($T1,$Xi); #
&movdqa ($T2,$T1); #
&pslldq ($T1,12);
&psrldq ($T2,4); #
&pxor ($T3,$T1);
# 2nd phase
&pxor ($Xhi,$T3); #
&movdqa ($Xi,$T3);
&movdqa ($T1,$T3);
&psrld ($Xi,1); #
&psrld ($T1,2);
&psrld ($T3,7); #
&pxor ($Xi,$T1);
&pxor ($Xhi,$T2);
&pxor ($Xi,$T3); #
&pxor ($Xi,$Xhi); #
}
&function_begin_B("gcm_init_clmul");
&mov ($Htbl,&wparam(0));
&mov ($Xip,&wparam(1));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Hkey,&QWP(0,$Xip));
&pshufd ($Hkey,$Hkey,0b01001110);# dword swap
# calculate H^2
&movdqa ($Xi,$Hkey);
&clmul64x64_T3 ($Xhi,$Xi,$Hkey);
&reduction_alg5 ($Xhi,$Xi);
&movdqu (&QWP(0,$Htbl),$Hkey); # save H
&movdqu (&QWP(16,$Htbl),$Xi); # save H^2
&ret ();
&function_end_B("gcm_init_clmul");
&function_begin_B("gcm_gmult_clmul");
&mov ($Xip,&wparam(0));
&mov ($Htbl,&wparam(1));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Xi,&QWP(0,$Xip));
&movdqa ($Xn,&QWP(0,$const));
&movdqu ($Hkey,&QWP(0,$Htbl));
&pshufb ($Xi,$Xn);
&clmul64x64_T3 ($Xhi,$Xi,$Hkey);
&reduction_alg5 ($Xhi,$Xi);
&pshufb ($Xi,$Xn);
&movdqu (&QWP(0,$Xip),$Xi);
&ret ();
&function_end_B("gcm_gmult_clmul");
&function_begin("gcm_ghash_clmul");
&mov ($Xip,&wparam(0));
&mov ($Htbl,&wparam(1));
&mov ($inp,&wparam(2));
&mov ($len,&wparam(3));
&call (&label("pic"));
&set_label("pic");
&blindpop ($const);
&lea ($const,&DWP(&label("bswap")."-".&label("pic"),$const));
&movdqu ($Xi,&QWP(0,$Xip));
&movdqa ($T3,&QWP(0,$const));
&movdqu ($Hkey,&QWP(0,$Htbl));
&pshufb ($Xi,$T3);
&sub ($len,0x10);
&jz (&label("odd_tail"));
#######
# Xi+2 =[H*(Ii+1 + Xi+1)] mod P =
# [(H*Ii+1) + (H*Xi+1)] mod P =
# [(H*Ii+1) + H^2*(Ii+Xi)] mod P
#
&movdqu ($T1,&QWP(0,$inp)); # Ii
&movdqu ($Xn,&QWP(16,$inp)); # Ii+1
&pshufb ($T1,$T3);
&pshufb ($Xn,$T3);
&pxor ($Xi,$T1); # Ii+Xi
&clmul64x64_T3 ($Xhn,$Xn,$Hkey); # H*Ii+1
&movdqu ($Hkey,&QWP(16,$Htbl)); # load H^2
&sub ($len,0x20);
&lea ($inp,&DWP(32,$inp)); # i+=2
&jbe (&label("even_tail"));
&set_label("mod_loop");
&clmul64x64_T3 ($Xhi,$Xi,$Hkey); # H^2*(Ii+Xi)
&movdqu ($Hkey,&QWP(0,$Htbl)); # load H
&pxor ($Xi,$Xn); # (H*Ii+1) + H^2*(Ii+Xi)
&pxor ($Xhi,$Xhn);
&reduction_alg5 ($Xhi,$Xi);
#######
&movdqa ($T3,&QWP(0,$const));
&movdqu ($T1,&QWP(0,$inp)); # Ii
&movdqu ($Xn,&QWP(16,$inp)); # Ii+1
&pshufb ($T1,$T3);
&pshufb ($Xn,$T3);
&pxor ($Xi,$T1); # Ii+Xi
&clmul64x64_T3 ($Xhn,$Xn,$Hkey); # H*Ii+1
&movdqu ($Hkey,&QWP(16,$Htbl)); # load H^2
&sub ($len,0x20);
&lea ($inp,&DWP(32,$inp));
&ja (&label("mod_loop"));
&set_label("even_tail");
&clmul64x64_T3 ($Xhi,$Xi,$Hkey); # H^2*(Ii+Xi)
&pxor ($Xi,$Xn); # (H*Ii+1) + H^2*(Ii+Xi)
&pxor ($Xhi,$Xhn);
&reduction_alg5 ($Xhi,$Xi);
&movdqa ($T3,&QWP(0,$const));
&test ($len,$len);
&jnz (&label("done"));
&movdqu ($Hkey,&QWP(0,$Htbl)); # load H
&set_label("odd_tail");
&movdqu ($T1,&QWP(0,$inp)); # Ii
&pshufb ($T1,$T3);
&pxor ($Xi,$T1); # Ii+Xi
&clmul64x64_T3 ($Xhi,$Xi,$Hkey); # H*(Ii+Xi)
&reduction_alg5 ($Xhi,$Xi);
&movdqa ($T3,&QWP(0,$const));
&set_label("done");
&pshufb ($Xi,$T3);
&movdqu (&QWP(0,$Xip),$Xi);
&function_end("gcm_ghash_clmul");
}
&set_label("bswap",64);
&data_byte(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0);
&data_byte(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xc2); # 0x1c2_polynomial
}} # $sse2
&set_label("rem_4bit",64);
&data_word(0,0x0000<<$S,0,0x1C20<<$S,0,0x3840<<$S,0,0x2460<<$S);
&data_word(0,0x7080<<$S,0,0x6CA0<<$S,0,0x48C0<<$S,0,0x54E0<<$S);
&data_word(0,0xE100<<$S,0,0xFD20<<$S,0,0xD940<<$S,0,0xC560<<$S);
&data_word(0,0x9180<<$S,0,0x8DA0<<$S,0,0xA9C0<<$S,0,0xB5E0<<$S);
&set_label("rem_8bit",64);
&data_short(0x0000,0x01C2,0x0384,0x0246,0x0708,0x06CA,0x048C,0x054E);
&data_short(0x0E10,0x0FD2,0x0D94,0x0C56,0x0918,0x08DA,0x0A9C,0x0B5E);
&data_short(0x1C20,0x1DE2,0x1FA4,0x1E66,0x1B28,0x1AEA,0x18AC,0x196E);
&data_short(0x1230,0x13F2,0x11B4,0x1076,0x1538,0x14FA,0x16BC,0x177E);
&data_short(0x3840,0x3982,0x3BC4,0x3A06,0x3F48,0x3E8A,0x3CCC,0x3D0E);
&data_short(0x3650,0x3792,0x35D4,0x3416,0x3158,0x309A,0x32DC,0x331E);
&data_short(0x2460,0x25A2,0x27E4,0x2626,0x2368,0x22AA,0x20EC,0x212E);
&data_short(0x2A70,0x2BB2,0x29F4,0x2836,0x2D78,0x2CBA,0x2EFC,0x2F3E);
&data_short(0x7080,0x7142,0x7304,0x72C6,0x7788,0x764A,0x740C,0x75CE);
&data_short(0x7E90,0x7F52,0x7D14,0x7CD6,0x7998,0x785A,0x7A1C,0x7BDE);
&data_short(0x6CA0,0x6D62,0x6F24,0x6EE6,0x6BA8,0x6A6A,0x682C,0x69EE);
&data_short(0x62B0,0x6372,0x6134,0x60F6,0x65B8,0x647A,0x663C,0x67FE);
&data_short(0x48C0,0x4902,0x4B44,0x4A86,0x4FC8,0x4E0A,0x4C4C,0x4D8E);
&data_short(0x46D0,0x4712,0x4554,0x4496,0x41D8,0x401A,0x425C,0x439E);
&data_short(0x54E0,0x5522,0x5764,0x56A6,0x53E8,0x522A,0x506C,0x51AE);
&data_short(0x5AF0,0x5B32,0x5974,0x58B6,0x5DF8,0x5C3A,0x5E7C,0x5FBE);
&data_short(0xE100,0xE0C2,0xE284,0xE346,0xE608,0xE7CA,0xE58C,0xE44E);
&data_short(0xEF10,0xEED2,0xEC94,0xED56,0xE818,0xE9DA,0xEB9C,0xEA5E);
&data_short(0xFD20,0xFCE2,0xFEA4,0xFF66,0xFA28,0xFBEA,0xF9AC,0xF86E);
&data_short(0xF330,0xF2F2,0xF0B4,0xF176,0xF438,0xF5FA,0xF7BC,0xF67E);
&data_short(0xD940,0xD882,0xDAC4,0xDB06,0xDE48,0xDF8A,0xDDCC,0xDC0E);
&data_short(0xD750,0xD692,0xD4D4,0xD516,0xD058,0xD19A,0xD3DC,0xD21E);
&data_short(0xC560,0xC4A2,0xC6E4,0xC726,0xC268,0xC3AA,0xC1EC,0xC02E);
&data_short(0xCB70,0xCAB2,0xC8F4,0xC936,0xCC78,0xCDBA,0xCFFC,0xCE3E);
&data_short(0x9180,0x9042,0x9204,0x93C6,0x9688,0x974A,0x950C,0x94CE);
&data_short(0x9F90,0x9E52,0x9C14,0x9DD6,0x9898,0x995A,0x9B1C,0x9ADE);
&data_short(0x8DA0,0x8C62,0x8E24,0x8FE6,0x8AA8,0x8B6A,0x892C,0x88EE);
&data_short(0x83B0,0x8272,0x8034,0x81F6,0x84B8,0x857A,0x873C,0x86FE);
&data_short(0xA9C0,0xA802,0xAA44,0xAB86,0xAEC8,0xAF0A,0xAD4C,0xAC8E);
&data_short(0xA7D0,0xA612,0xA454,0xA596,0xA0D8,0xA11A,0xA35C,0xA29E);
&data_short(0xB5E0,0xB422,0xB664,0xB7A6,0xB2E8,0xB32A,0xB16C,0xB0AE);
&data_short(0xBBF0,0xBA32,0xB874,0xB9B6,0xBCF8,0xBD3A,0xBF7C,0xBEBE);
}}} # !$x86only
&asciz("GHASH for x86, CRYPTOGAMS by <appro\@openssl.org>");
&asm_finish();
# A question was risen about choice of vanilla MMX. Or rather why wasn't
# SSE2 chosen instead? In addition to the fact that MMX runs on legacy
# CPUs such as PIII, "4-bit" MMX version was observed to provide better
# performance than *corresponding* SSE2 one even on contemporary CPUs.
# SSE2 results were provided by Peter-Michael Hager. He maintains SSE2
# implementation featuring full range of lookup-table sizes, but with
# per-invocation lookup table setup. Latter means that table size is
# chosen depending on how much data is to be hashed in every given call,
# more data - larger table. Best reported result for Core2 is ~4 cycles
# per processed byte out of 64KB block. This number accounts even for
# 64KB table setup overhead. As discussed in gcm128.c we choose to be
# more conservative in respect to lookup table sizes, but how do the
# results compare? Minimalistic "256B" MMX version delivers ~11 cycles
# on same platform. As also discussed in gcm128.c, next in line "8-bit
# Shoup's" or "4KB" method should deliver twice the performance of
# "256B" one, in other words not worse than ~6 cycles per byte. It
# should be also be noted that in SSE2 case improvement can be "super-
# linear," i.e. more than twice, mostly because >>8 maps to single
# instruction on SSE2 register. This is unlike "4-bit" case when >>4
# maps to same amount of instructions in both MMX and SSE2 cases.
# Bottom line is that switch to SSE2 is considered to be justifiable
# only in case we choose to implement "8-bit" method...
|
teeple/pns_server
|
work/install/node-v0.10.25/deps/openssl/openssl/crypto/modes/asm/ghash-x86.pl
|
Perl
|
gpl-2.0
| 39,585
|
<!doctype html>
006-1
<script>
onpagehide = function() {
onpagehide = null;
setTimeout(function() {
parent.t.done()
}, 1000);
}
onload = function() {
if (!parent.loaded) {
parent.loaded = true;
setTimeout(parent.t.step_func(
function() {
location="006-2.html?" + Math.random();
}
), 100);
}
}
</script>
|
youtube/cobalt
|
third_party/web_platform_tests/html/browsers/browsing-the-web/unloading-documents/unload/006-1.html
|
HTML
|
bsd-3-clause
| 374
|
CC = $(CROSS_COMPILE)gcc
BUILD_FLAGS = -DKTEST
CFLAGS += -O3 -Wl,-no-as-needed -Wall $(BUILD_FLAGS)
LDFLAGS += -lrt -lpthread
# these are all "safe" tests that don't modify
# system time or require escalated privledges
TEST_PROGS = posix_timers nanosleep nsleep-lat set-timer-lat mqueue-lat \
inconsistency-check raw_skew threadtest rtctest
TEST_PROGS_EXTENDED = alarmtimer-suspend valid-adjtimex adjtick change_skew \
skew_consistency clocksource-switch leap-a-day \
leapcrash set-tai set-2038 set-tz
bins = $(TEST_PROGS) $(TEST_PROGS_EXTENDED)
all: ${bins}
include ../lib.mk
# these tests require escalated privledges
# and may modify the system time or trigger
# other behavior like suspend
run_destructive_tests: run_tests
./alarmtimer-suspend
./valid-adjtimex
./adjtick
./change_skew
./skew_consistency
./clocksource-switch
./leap-a-day -s -i 10
./leapcrash
./set-tz
./set-tai
./set-2038
clean:
rm -f ${bins}
|
jumpnow/linux
|
tools/testing/selftests/timers/Makefile
|
Makefile
|
gpl-2.0
| 955
|
/*
* Copyright (C) 2007
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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
*/
/*
* This file is originally a part of the GCC testsuite.
*/
#include <common.h>
#include <post.h>
GNU_FPOST_ATTR
#if CONFIG_POST & CONFIG_SYS_POST_FPU
int fpu_post_test_math4 (void)
{
volatile float reale = 1.0f;
volatile float oneplus;
int i;
if (sizeof (float) != 4)
return 0;
for (i = 0; ; i++)
{
oneplus = 1.0f + reale;
if (oneplus == 1.0f)
break;
reale = reale / 2.0f;
}
/* Assumes ieee754 accurate arithmetic above. */
if (i != 24) {
post_log ("Error in FPU math4 test\n");
return -1;
}
return 0;
}
#endif /* CONFIG_POST & CONFIG_SYS_POST_FPU */
|
lxl1140989/dmsdk
|
uboot/u-boot-dm6291/post/lib_powerpc/fpu/980619-1.c
|
C
|
gpl-2.0
| 1,471
|
/*--------------------------------------------------------------------------*/
/* FileName : Tcc353x_pal_tccspi.c */
/* Description : Interface Function */
/*--------------------------------------------------------------------------*/
/* */
/* TCC Version : 1.0.0 */
/* Copyright (c) Telechips, Inc. */
/* ALL RIGHTS RESERVED */
/* */
/*--------------------------------------------------------------------------*/
#include "tcc353x_common.h"
#include "tcpal_os.h"
#include <linux/dma-mapping.h>
extern I32S Tcc353xAdaptSpiReadWrite(int moduleidx, I08U * pBufIn,
I08U * pBufOut, I32U Length,
I08U ReservedOption);
static I32S Tcc353xTccspiSingleRW(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _data,
I08U _writeFlag);
static I32S Tcc353xTccspiMultiRW(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _data,
I32S _size, I08U _writeFlag);
static I08U Tcc353xCheckCrc7(I08U * _data, I32U _len);
static I32S Tcc353xTccspiReset(I32S _moduleIndex, I32S _chipAddress);
/*
#define DMA_MAX_SIZE (2048)
#define DMA_MAX_SIZE (4096)
*/
//#define DMA_MAX_SIZE (188*40) // 07.34kb 7520 byte
//#define DMA_MAX_SIZE (188*64) // 11.75kb 12032
//#define DMA_MAX_SIZE (188*80) // 14.68kb 15040
#define DMA_MAX_SIZE (188*87) // 15.97kb 16356
/* for test code */
/*
#define _RW_AT_ONCE_
*/
#define SPICMD_BUFF_LEN 8
#define SPICMD_ACK 0x47
#define _WRITE_FLAG_ 1
#define _READ_FLAG_ 0
const I08U SdioCrc7Table[256] = {
0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f,
0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77,
0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26,
0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e,
0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d,
0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45,
0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14,
0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c,
0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b,
0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13,
0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42,
0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a,
0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69,
0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21,
0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70,
0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38,
0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e,
0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36,
0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67,
0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f,
0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c,
0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04,
0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55,
0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d,
0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a,
0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52,
0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03,
0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b,
0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28,
0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60,
0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31,
0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79
};
#ifdef _RW_AT_ONCE_
static I08U NullDatas[DMA_MAX_SIZE+(SPICMD_BUFF_LEN*2)+32] __cacheline_aligned;
static I08U DummyDatas[DMA_MAX_SIZE+(SPICMD_BUFF_LEN*2)+32] __cacheline_aligned;
static I08U BurstDatas[DMA_MAX_SIZE+(SPICMD_BUFF_LEN*2)+32] __cacheline_aligned;
#else
static I08U NullDatas[DMA_MAX_SIZE+32] __cacheline_aligned;
static I08U DummyDatas[DMA_MAX_SIZE+32] __cacheline_aligned;
static I08U BurstDatas[DMA_MAX_SIZE+32] __cacheline_aligned;
#endif
static I08U FFData[SPICMD_BUFF_LEN+32] __cacheline_aligned;
static I08U Buffout[SPICMD_BUFF_LEN+32] __cacheline_aligned;
static I08U Buffin[SPICMD_BUFF_LEN+32] __cacheline_aligned;
void Tcc353xTccspiInit(void)
{
TcpalMemset(&DummyDatas[0], 0x00, DMA_MAX_SIZE);
TcpalMemset(&NullDatas[0], 0x00, DMA_MAX_SIZE);
}
I32S Tcc353xTccspiRead(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _outData, I32S _size)
{
I32S ret = TCC353X_RETURN_FAIL;
I32S i;
if (_size == 1) {
ret =
Tcc353xTccspiSingleRW(_moduleIndex, _chipAddress,
_registerAddr, _outData,
_READ_FLAG_);
} else if ((_size % 4) != 0) {
for (i = 0; i < _size; i++) {
if (_registerAddr & 0x80)
ret =
Tcc353xTccspiSingleRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_outData[i],
_READ_FLAG_);
else
ret =
Tcc353xTccspiSingleRW(_moduleIndex,
_chipAddress,
(I08U)
(_registerAddr +
i),
&_outData[i],
_READ_FLAG_);
}
} else {
I32S result;
I32S cmax;
I32S cremain;
I32S i;
cmax = (_size / DMA_MAX_SIZE);
cremain = (_size % DMA_MAX_SIZE);
for (i = 0; i < cmax; i++) {
result =
Tcc353xTccspiMultiRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_outData[i *
DMA_MAX_SIZE],
DMA_MAX_SIZE - 1,
_READ_FLAG_);
if (result != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex,
_chipAddress);
return TCC353X_RETURN_FAIL;
}
}
if (cremain != 0) {
result =
Tcc353xTccspiMultiRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_outData[i *
DMA_MAX_SIZE],
cremain - 1, _READ_FLAG_);
if (result != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex,
_chipAddress);
return TCC353X_RETURN_FAIL;
}
}
ret = TCC353X_RETURN_SUCCESS;
}
if (ret != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex, _chipAddress);
return TCC353X_RETURN_FAIL;
}
return ret;
}
I32S Tcc353xTccspiWrite(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _inputData, I32S _size)
{
I32S ret = TCC353X_RETURN_FAIL;
I32S i;
if (_size == 1) {
ret =
Tcc353xTccspiSingleRW(_moduleIndex, _chipAddress,
_registerAddr, _inputData,
_WRITE_FLAG_);
} else if ((_size % 4) != 0) {
for (i = 0; i < _size; i++) {
if (_registerAddr & 0x80)
ret =
Tcc353xTccspiSingleRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_inputData[i],
_WRITE_FLAG_);
else
ret =
Tcc353xTccspiSingleRW(_moduleIndex,
_chipAddress,
(I08U)
(_registerAddr +
i),
&_inputData[i],
_WRITE_FLAG_);
}
} else {
I32S result;
I32S cmax;
I32S cremain;
I32S i;
cmax = (_size / DMA_MAX_SIZE);
cremain = (_size % DMA_MAX_SIZE);
for (i = 0; i < cmax; i++) {
result =
Tcc353xTccspiMultiRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_inputData[i *
DMA_MAX_SIZE],
DMA_MAX_SIZE - 1,
_WRITE_FLAG_);
if (result != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex,
_chipAddress);
return TCC353X_RETURN_FAIL;
}
}
if (cremain != 0) {
result =
Tcc353xTccspiMultiRW(_moduleIndex,
_chipAddress,
_registerAddr,
&_inputData[i *
DMA_MAX_SIZE],
cremain - 1,
_WRITE_FLAG_);
if (result != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex,
_chipAddress);
return TCC353X_RETURN_FAIL;
}
}
ret = TCC353X_RETURN_SUCCESS;
}
if (ret != TCC353X_RETURN_SUCCESS) {
Tcc353xTccspiReset(_moduleIndex, _chipAddress);
return TCC353X_RETURN_FAIL;
}
return ret;
}
static I08U Tcc353xCheckCrc7(I08U * _data, I32U _len)
{
#ifndef CRC_CHECK_BY_TABLE
I16U masking, carry;
I16U crc;
I32U i, loop, remain;
crc = 0x0000;
loop = _len / 8;
remain = _len - loop * 8;
for (i = 0; i < loop; i++) {
masking = 1 << 8;
while ((masking >>= 1)) {
carry = crc & 0x40;
crc <<= 1;
if ((!carry) ^ (!(*_data & masking)))
crc ^= 0x9;
crc &= 0x7f;
}
_data++;
}
masking = 1 << 8;
while (remain) {
carry = crc & 0x40;
crc <<= 1;
masking >>= 1;
if ((!carry) ^ (!(*_data & masking)))
crc ^= 0x9;
crc &= 0x7f;
remain--;
}
return (I08U) crc;
#else
I08U crc7_accum = 0;
I32U i;
for (i = 0; i < _len; i++) {
crc7_accum = SdioCrc7Table[(crc7_accum << 1) ^ _data[i]];
}
return crc7_accum;
#endif
}
I32S Tcc353xSpiRW(I32S _moduleIndex, I08U * _bufferIn, I08U * _bufferOut,
I32S _size, I08U _reservedOption)
{
/* for avoid const data confliction */
Tcc353xAdaptSpiReadWrite(_moduleIndex, _bufferIn, _bufferOut,
_size, _reservedOption);
return TCC353X_RETURN_SUCCESS;
}
static I32S Tcc353xTccspiReset(I32S _moduleIndex, I32S _chipAddress)
{
TcpalMemset(FFData, 0xFF, SPICMD_BUFF_LEN);
Tcc353xSpiRW(_moduleIndex, FFData, Buffout, SPICMD_BUFF_LEN, 0);
return TCC353X_RETURN_SUCCESS;
}
static I32S Tcc353xTccspiSingleRW(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _data,
I08U _writeFlag)
{
I08U crc;
Buffin[0] = (I08U) (_chipAddress); /* start bit(1) + chip_id(7) */
/* mode(1) + rw(1) + fix(1) + addr(5) */
Buffin[1] =
0 << 7 | _writeFlag << 6 | 1 << 5 | ((_registerAddr & 0x7c0) >>
6);
/* addr(6bit) + NULL(2bit) */
Buffin[2] = (_registerAddr & 0x03f) << 2 | 0x0;
if (_writeFlag) /* write */
Buffin[3] = _data[0];
else
Buffin[3] = 0x0; /* null(8) */
Buffin[4] = 0x00;
crc = Tcc353xCheckCrc7(Buffin, 36);
Buffin[4] = 0x00 | ((crc & 0x7f) >> 3); /* null(4) + crc(4) */
Buffin[5] = ((crc & 0x07) << 5) | 0x1f; /* crc(3) + end bit(5) */
Buffin[6] = 0xff;
Buffin[7] = 0xff;
Tcc353xSpiRW(_moduleIndex, Buffin, Buffout, SPICMD_BUFF_LEN, 1);
if (Buffout[7] != SPICMD_ACK) {
/* ack */
TcpalPrintErr((I08S *) "[TCC353X] Single %s ACK error\n",
_writeFlag ? "Write" : "Read");
TcpalPrintErr((I08S *)
"[TCC353X] [%02x][%02x][%02x][%02x] [%02x][%02x][%02x][%02x]//[%02x]\n",
Buffout[0], Buffout[1], Buffout[2], Buffout[3],
Buffout[4], Buffout[5], Buffout[6], Buffout[7],
crc);
return TCC353X_RETURN_FAIL;
}
if (_writeFlag == 0) {
_data[0] = Buffout[6];
}
return TCC353X_RETURN_SUCCESS;
}
#ifdef _RW_AT_ONCE_
static I32S Tcc353xTccspiMultiRW(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _data,
I32S _size, I08U _writeFlag)
{
I08U crc;
I08U fixedMode = 0;
if (_registerAddr & 0x80)
fixedMode = 1;
else
fixedMode = 0;
_registerAddr = (_registerAddr & 0x7F);
if (_size > DMA_MAX_SIZE)
return (-1);
/* MAX 16KB (Output buffer max size 7KB) (LENGTH + 1 Byte) */
/* start bit(1) + chip_id(7) */
Buffin[0] = (I08U) (_chipAddress); /* start bit(1) + chip_id(7) */
/* mode(1) + rw(1) + fix(1) + addr(5) */
Buffin[1] =
1 << 7 | _writeFlag << 6 | fixedMode << 5 |
((_registerAddr & 0x7c0) >> 6);
/* addr(6bit) + length(2bit) */
Buffin[2] =
(I08U) ((_registerAddr & 0x03f) << 2 |
((_size & 0x3000) >> 12));
/* length(8bit) */
Buffin[3] = (I08U) ((_size & 0xff0) >> 4);
Buffin[4] = (I08U) ((_size & 0xf) << 4);
crc = Tcc353xCheckCrc7(Buffin, 36);
/* length(4) + crc(4) */
Buffin[4] = (I08U) (((_size & 0xf) << 4) | ((crc & 0x7f) >> 3));
/* crc(3) + end bit(5) */
Buffin[5] = ((crc & 0x07) << 5) | 0x1f;
Buffin[6] = 0xff;
Buffin[7] = 0xff;
if (_writeFlag == 0) {
TcpalMemcpy(&DummyDatas[0], Buffin, SPICMD_BUFF_LEN);
TcpalMemset(&DummyDatas[SPICMD_BUFF_LEN], 0x00, _size + 1);
TcpalMemset(&DummyDatas[SPICMD_BUFF_LEN+_size+1], 0xFF, SPICMD_BUFF_LEN);
Tcc353xSpiRW(_moduleIndex, DummyDatas, BurstDatas, _size + 1 + (SPICMD_BUFF_LEN*2), 0);
TcpalMemcpy(_data, &BurstDatas[SPICMD_BUFF_LEN], _size+1);
if (BurstDatas[7] != SPICMD_ACK) { /* ack */
TcpalPrintErr((I08S *) "[TCC353X] Burst %s ACK error\n",
_writeFlag ? "Write" : "Read");
TcpalPrintErr((I08S *)
"[TCC353X] [%x][%x][%x][%x] [%x][%x][%x][%x]//[%x]\n",
BurstDatas[0], BurstDatas[1], BurstDatas[2],
BurstDatas[3], BurstDatas[4], BurstDatas[5],
BurstDatas[6], BurstDatas[7], crc);
return TCC353X_RETURN_FAIL;
}
} else {
TcpalMemcpy(&BurstDatas[0], Buffin, SPICMD_BUFF_LEN);
TcpalMemcpy(&BurstDatas[SPICMD_BUFF_LEN], _data, _size + 1);
TcpalMemset(&BurstDatas[SPICMD_BUFF_LEN+_size+1], 0xFF, SPICMD_BUFF_LEN);
Tcc353xSpiRW(_moduleIndex, BurstDatas, DummyDatas, _size + 1 + (SPICMD_BUFF_LEN*2), 0);
TcpalMemcpy(_data, &BurstDatas[SPICMD_BUFF_LEN], _size+1);
if (DummyDatas[7] != SPICMD_ACK) { /* ack */
TcpalPrintErr((I08S *) "[TCC353X] Burst %s ACK error\n",
_writeFlag ? "Write" : "Read");
TcpalPrintErr((I08S *)
"[TCC353X] [%x][%x][%x][%x] [%x][%x][%x][%x]//[%x]\n",
DummyDatas[0], DummyDatas[1], DummyDatas[2],
DummyDatas[3], DummyDatas[4], DummyDatas[5],
DummyDatas[6], DummyDatas[7], crc);
return TCC353X_RETURN_FAIL;
}
}
return TCC353X_RETURN_SUCCESS;
}
#else
static I32S Tcc353xTccspiMultiRW(I32S _moduleIndex, I32S _chipAddress,
I08U _registerAddr, I08U * _data,
I32S _size, I08U _writeFlag)
{
I08U crc;
I08U fixedMode = 0;
if (_registerAddr & 0x80)
fixedMode = 1;
else
fixedMode = 0;
_registerAddr = (_registerAddr & 0x7F);
if (_size > DMA_MAX_SIZE)
return (-1);
/* MAX 16KB (Output buffer max size 7KB) (LENGTH + 1 Byte) */
/* start bit(1) + chip_id(7) */
Buffin[0] = (I08U) (_chipAddress); /* start bit(1) + chip_id(7) */
/* mode(1) + rw(1) + fix(1) + addr(5) */
Buffin[1] =
1 << 7 | _writeFlag << 6 | fixedMode << 5 |
((_registerAddr & 0x7c0) >> 6);
/* addr(6bit) + length(2bit) */
Buffin[2] =
(I08U) ((_registerAddr & 0x03f) << 2 |
((_size & 0x3000) >> 12));
/* length(8bit) */
Buffin[3] = (I08U) ((_size & 0xff0) >> 4);
Buffin[4] = (I08U) ((_size & 0xf) << 4);
crc = Tcc353xCheckCrc7(Buffin, 36);
/* length(4) + crc(4) */
Buffin[4] = (I08U) (((_size & 0xf) << 4) | ((crc & 0x7f) >> 3));
/* crc(3) + end bit(5) */
Buffin[5] = ((crc & 0x07) << 5) | 0x1f;
Buffin[6] = 0xff;
Buffin[7] = 0xff;
Tcc353xSpiRW(_moduleIndex, Buffin, Buffout, SPICMD_BUFF_LEN, 1);
if (Buffout[7] != SPICMD_ACK) { /* ack */
TcpalPrintErr((I08S *) "[TCC353X] Burst %s ACK error\n",
_writeFlag ? "Write" : "Read");
TcpalPrintErr((I08S *)
"[TCC353X] [%x][%x][%x][%x] [%x][%x][%x][%x]//[%x]\n",
Buffout[0], Buffout[1], Buffout[2],
Buffout[3], Buffout[4], Buffout[5],
Buffout[6], Buffout[7], crc);
return TCC353X_RETURN_FAIL;
}
if (_writeFlag == 0) {
/* Receive Data */
Tcc353xSpiRW(_moduleIndex, NullDatas, BurstDatas, _size + 1, 0);
TcpalMemcpy(_data, BurstDatas, _size+1);
/* initialize tcc353x spi cmd interface and
* read crc for pData
*/
TcpalMemset(&FFData[0], 0xFF, SPICMD_BUFF_LEN);
Tcc353xSpiRW(_moduleIndex, FFData, Buffout,
SPICMD_BUFF_LEN, 0);
/*TODO check crc */
} else {
/* Send Data */
TcpalMemcpy(BurstDatas, _data, _size+1);
Tcc353xSpiRW(_moduleIndex, BurstDatas, DummyDatas,
_size + 1, 0);
/* initialize tcc353x spi cmd interface */
TcpalMemset(&FFData[0], 0xFF, SPICMD_BUFF_LEN);
Tcc353xSpiRW(_moduleIndex, FFData, Buffout,
SPICMD_BUFF_LEN, 0);
}
return TCC353X_RETURN_SUCCESS;
}
#endif
|
blastagator/LGG2_Kernel
|
drivers/broadcast/oneseg/tcc3530/Tcc353xDriver/PAL/tcc353x_pal_tccspi.c
|
C
|
gpl-2.0
| 15,946
|
import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
export default get;
|
MacroLin/practice
|
webpack+react(练习)/node_modules/.4.17.4@lodash-es/get.js
|
JavaScript
|
mit
| 882
|
<?php
/*
* ACF Attachment Form Class
*
* All the logic for adding fields to attachments
*
* @class acf_form_attachment
* @package ACF
* @subpackage Forms
*/
if( ! class_exists('acf_form_attachment') ) :
class acf_form_attachment {
/*
* __construct
*
* This function will setup the class functionality
*
* @type function
* @date 5/03/2014
* @since 5.0.0
*
* @param n/a
* @return n/a
*/
function __construct() {
// actions
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
// render
add_filter('attachment_fields_to_edit', array($this, 'edit_attachment'), 10, 2);
// save
add_filter('attachment_fields_to_save', array($this, 'save_attachment'), 10, 2);
}
/*
* validate_page
*
* This function will check if the current page is for a post/page edit form
*
* @type function
* @date 23/06/12
* @since 3.1.8
*
* @param n/a
* @return (boolean)
*/
function validate_page() {
// global
global $pagenow, $typenow, $wp_version;
// validate page
if( $pagenow === 'post.php' && $typenow === 'attachment' ) {
return true;
}
// validate page
if( $pagenow === 'upload.php' && version_compare($wp_version, '4.0', '>=') ) {
add_action('admin_footer', array($this, 'admin_footer'), 0);
return true;
}
// return
return false;
}
/*
* admin_enqueue_scripts
*
* This action is run after post query but before any admin script / head actions.
* It is a good place to register all actions.
*
* @type action (admin_enqueue_scripts)
* @date 26/01/13
* @since 3.6.0
*
* @param N/A
* @return N/A
*/
function admin_enqueue_scripts() {
// bail early if not valid page
if( !$this->validate_page() ) {
return;
}
// load acf scripts
acf_enqueue_scripts();
}
/*
* admin_footer
*
* This function will add acf_form_data to the WP 4.0 attachment grid
*
* @type action (admin_footer)
* @date 11/09/2014
* @since 5.0.0
*
* @param n/a
* @return n/a
*/
function admin_footer() {
// render post data
acf_form_data(array(
'post_id' => 0,
'nonce' => 'attachment',
'ajax' => 1
));
}
/*
* edit_attachment
*
* description
*
* @type function
* @date 8/10/13
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function edit_attachment( $form_fields, $post ) {
// vars
$el = 'tr';
$post_id = $post->ID;
$args = array(
'attachment' => 'All'
);
// $el
if( $this->validate_page() ) {
//$el = 'div';
}
// get field groups
$field_groups = acf_get_field_groups( $args );
// render
if( !empty($field_groups) ) {
// get acf_form_data
ob_start();
acf_form_data(array(
'post_id' => $post_id,
'nonce' => 'attachment',
));
if( $this->validate_page() ) {
echo '<style type="text/css">
.compat-attachment-fields,
.compat-attachment-fields > tbody,
.compat-attachment-fields > tbody > tr,
.compat-attachment-fields > tbody > tr > th,
.compat-attachment-fields > tbody > tr > td {
display: block;
}
tr.acf-field {
display: block;
margin: 0 0 13px;
}
tr.acf-field td.acf-label {
display: block;
margin: 0;
}
tr.acf-field td.acf-input {
display: block;
margin: 0;
}
</style>';
}
// $el
//if( $el == 'tr' ) {
echo '</td></tr>';
//}
foreach( $field_groups as $field_group ) {
$fields = acf_get_fields( $field_group );
acf_render_fields( $post_id, $fields, $el, 'field' );
}
// $el
//if( $el == 'tr' ) {
echo '<tr class="compat-field-acf-blank"><td>';
//}
$html = ob_get_contents();
ob_end_clean();
$form_fields[ 'acf-form-data' ] = array(
'label' => '',
'input' => 'html',
'html' => $html
);
}
// return
return $form_fields;
}
/*
* save_attachment
*
* description
*
* @type function
* @date 8/10/13
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function save_attachment( $post, $attachment ) {
// bail early if not valid nonce
if( ! acf_verify_nonce('attachment') ) {
return $post;
}
// validate and save
if( acf_validate_save_post(true) ) {
acf_save_post( $post['ID'] );
}
// return
return $post;
}
}
new acf_form_attachment();
endif;
?>
|
amirus2303/projet-test-gulp
|
wp-content/upgrade/Advanced.Custom.Fields.Pro_.v5.3.0/Advanced.Custom.Fields.Pro.v5.3.0/advanced-custom-fields-pro/forms/attachment.php
|
PHP
|
gpl-2.0
| 4,658
|
<?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/>.
/**
* Generic forms used for page selection
*
* @package mod_lesson
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
defined('MOODLE_INTERNAL') || die();
/**
* Question selection form
*
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
class lesson_add_page_form_selection extends lesson_add_page_form_base {
public $qtype = 'questiontype';
public $qtypestring = 'selectaqtype';
protected $standard = false;
protected $manager = null;
public function __construct($arg1, $arg2) {
$this->manager = lesson_page_type_manager::get($arg2['lesson']);
parent::__construct($arg1, $arg2);
}
public function custom_definition() {
$mform = $this->_form;
$types = $this->manager->get_page_type_strings(lesson_page::TYPE_QUESTION);
asort($types);
$mform->addElement('select', 'qtype', get_string('selectaqtype', 'lesson'), $types);
$mform->setDefault('qtype', LESSON_PAGE_MULTICHOICE); // preselect the most common type
}
}
/**
* Dummy class to represent an unknown question type and direct to the selection
* form.
*/
final class lesson_add_page_form_unknown extends lesson_add_page_form_base {}
|
rafaelperazzo/ufca-web
|
moodle/mod/lesson/editpage_form.php
|
PHP
|
gpl-3.0
| 1,997
|
/* drivers/misc/lowmemorykiller.c
*
* The lowmemorykiller driver lets user-space specify a set of memory thresholds
* where processes with a range of oom_score_adj values will get killed. Specify
* the minimum oom_score_adj values in
* /sys/module/lowmemorykiller/parameters/adj and the number of free pages in
* /sys/module/lowmemorykiller/parameters/minfree. Both files take a comma
* separated list of numbers in ascending order.
*
* For example, write "0,8" to /sys/module/lowmemorykiller/parameters/adj and
* "1024,4096" to /sys/module/lowmemorykiller/parameters/minfree to kill
* processes with a oom_score_adj value of 8 or higher when the free memory
* drops below 4096 pages and kill processes with a oom_score_adj value of 0 or
* higher when the free memory drops below 1024 pages.
*
* The driver considers memory used for caches to be free, but if a large
* percentage of the cached memory is locked this can be very inaccurate
* and processes may not get killed until the normal oom killer is triggered.
*
* Copyright (C) 2007-2008 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/oom.h>
#include <linux/sched.h>
#include <linux/rcupdate.h>
#include <linux/notifier.h>
static uint32_t lowmem_debug_level = 2;
static int lowmem_adj[6] = {
0,
1,
6,
12,
};
static int lowmem_adj_size = 4;
static int lowmem_minfree[6] = {
3 * 512, /* 6MB */
2 * 1024, /* 8MB */
4 * 1024, /* 16MB */
16 * 1024, /* 64MB */
};
static int lowmem_minfree_size = 4;
static unsigned long lowmem_deathpending_timeout;
#define lowmem_print(level, x...) \
do { \
if (lowmem_debug_level >= (level)) \
printk(x); \
} while (0)
static int lowmem_shrink(struct shrinker *s, struct shrink_control *sc)
{
struct task_struct *tsk;
struct task_struct *selected = NULL;
int rem = 0;
int tasksize;
int i;
int min_score_adj = OOM_SCORE_ADJ_MAX + 1;
int selected_tasksize = 0;
int selected_oom_score_adj;
int array_size = ARRAY_SIZE(lowmem_adj);
int other_free = global_page_state(NR_FREE_PAGES);
int other_file = global_page_state(NR_FILE_PAGES) -
global_page_state(NR_SHMEM);
if (lowmem_adj_size < array_size)
array_size = lowmem_adj_size;
if (lowmem_minfree_size < array_size)
array_size = lowmem_minfree_size;
for (i = 0; i < array_size; i++) {
if (other_free < lowmem_minfree[i] &&
other_file < lowmem_minfree[i]) {
min_score_adj = lowmem_adj[i];
break;
}
}
if (sc->nr_to_scan > 0)
lowmem_print(3, "lowmem_shrink %lu, %x, ofree %d %d, ma %d\n",
sc->nr_to_scan, sc->gfp_mask, other_free,
other_file, min_score_adj);
rem = global_page_state(NR_ACTIVE_ANON) +
global_page_state(NR_ACTIVE_FILE) +
global_page_state(NR_INACTIVE_ANON) +
global_page_state(NR_INACTIVE_FILE);
if (sc->nr_to_scan <= 0 || min_score_adj == OOM_SCORE_ADJ_MAX + 1) {
lowmem_print(5, "lowmem_shrink %lu, %x, return %d\n",
sc->nr_to_scan, sc->gfp_mask, rem);
return rem;
}
selected_oom_score_adj = min_score_adj;
rcu_read_lock();
for_each_process(tsk) {
struct task_struct *p;
int oom_score_adj;
if (tsk->flags & PF_KTHREAD)
continue;
p = find_lock_task_mm(tsk);
if (!p)
continue;
if (test_tsk_thread_flag(p, TIF_MEMDIE) &&
time_before_eq(jiffies, lowmem_deathpending_timeout)) {
task_unlock(p);
rcu_read_unlock();
return 0;
}
oom_score_adj = p->signal->oom_score_adj;
if (oom_score_adj < min_score_adj) {
task_unlock(p);
continue;
}
tasksize = get_mm_rss(p->mm);
task_unlock(p);
if (tasksize <= 0)
continue;
if (selected) {
if (oom_score_adj < selected_oom_score_adj)
continue;
if (oom_score_adj == selected_oom_score_adj &&
tasksize <= selected_tasksize)
continue;
}
selected = p;
selected_tasksize = tasksize;
selected_oom_score_adj = oom_score_adj;
lowmem_print(2, "select %d (%s), adj %d, size %d, to kill\n",
p->pid, p->comm, oom_score_adj, tasksize);
}
if (selected) {
lowmem_print(1, "send sigkill to %d (%s), adj %d, size %d\n",
selected->pid, selected->comm,
selected_oom_score_adj, selected_tasksize);
lowmem_deathpending_timeout = jiffies + HZ;
send_sig(SIGKILL, selected, 0);
set_tsk_thread_flag(selected, TIF_MEMDIE);
rem -= selected_tasksize;
}
lowmem_print(4, "lowmem_shrink %lu, %x, return %d\n",
sc->nr_to_scan, sc->gfp_mask, rem);
rcu_read_unlock();
return rem;
}
static struct shrinker lowmem_shrinker = {
.shrink = lowmem_shrink,
.seeks = DEFAULT_SEEKS * 16
};
static int __init lowmem_init(void)
{
register_shrinker(&lowmem_shrinker);
return 0;
}
static void __exit lowmem_exit(void)
{
unregister_shrinker(&lowmem_shrinker);
}
module_param_named(cost, lowmem_shrinker.seeks, int, S_IRUGO | S_IWUSR);
module_param_array_named(adj, lowmem_adj, int, &lowmem_adj_size,
S_IRUGO | S_IWUSR);
module_param_array_named(minfree, lowmem_minfree, uint, &lowmem_minfree_size,
S_IRUGO | S_IWUSR);
module_param_named(debug_level, lowmem_debug_level, uint, S_IRUGO | S_IWUSR);
module_init(lowmem_init);
module_exit(lowmem_exit);
MODULE_LICENSE("GPL");
|
sktjdgns1189/android_kernel_kttech_s220
|
drivers/staging/android/lowmemorykiller.c
|
C
|
gpl-2.0
| 5,605
|
/*
* Scalar fixed time AES core transform
*
* Copyright (C) 2017 Linaro Ltd <ard.biesheuvel@linaro.org>
*
* 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 <crypto/aes.h>
#include <linux/crypto.h>
#include <linux/module.h>
#include <asm/unaligned.h>
/*
* Emit the sbox as volatile const to prevent the compiler from doing
* constant folding on sbox references involving fixed indexes.
*/
static volatile const u8 __cacheline_aligned __aesti_sbox[] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
};
static volatile const u8 __cacheline_aligned __aesti_inv_sbox[] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38,
0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d,
0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2,
0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a,
0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea,
0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85,
0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20,
0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31,
0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0,
0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26,
0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
};
static u32 mul_by_x(u32 w)
{
u32 x = w & 0x7f7f7f7f;
u32 y = w & 0x80808080;
/* multiply by polynomial 'x' (0b10) in GF(2^8) */
return (x << 1) ^ (y >> 7) * 0x1b;
}
static u32 mul_by_x2(u32 w)
{
u32 x = w & 0x3f3f3f3f;
u32 y = w & 0x80808080;
u32 z = w & 0x40404040;
/* multiply by polynomial 'x^2' (0b100) in GF(2^8) */
return (x << 2) ^ (y >> 7) * 0x36 ^ (z >> 6) * 0x1b;
}
static u32 mix_columns(u32 x)
{
/*
* Perform the following matrix multiplication in GF(2^8)
*
* | 0x2 0x3 0x1 0x1 | | x[0] |
* | 0x1 0x2 0x3 0x1 | | x[1] |
* | 0x1 0x1 0x2 0x3 | x | x[2] |
* | 0x3 0x1 0x1 0x2 | | x[3] |
*/
u32 y = mul_by_x(x) ^ ror32(x, 16);
return y ^ ror32(x ^ y, 8);
}
static u32 inv_mix_columns(u32 x)
{
/*
* Perform the following matrix multiplication in GF(2^8)
*
* | 0xe 0xb 0xd 0x9 | | x[0] |
* | 0x9 0xe 0xb 0xd | | x[1] |
* | 0xd 0x9 0xe 0xb | x | x[2] |
* | 0xb 0xd 0x9 0xe | | x[3] |
*
* which can conveniently be reduced to
*
* | 0x2 0x3 0x1 0x1 | | 0x5 0x0 0x4 0x0 | | x[0] |
* | 0x1 0x2 0x3 0x1 | | 0x0 0x5 0x0 0x4 | | x[1] |
* | 0x1 0x1 0x2 0x3 | x | 0x4 0x0 0x5 0x0 | x | x[2] |
* | 0x3 0x1 0x1 0x2 | | 0x0 0x4 0x0 0x5 | | x[3] |
*/
u32 y = mul_by_x2(x);
return mix_columns(x ^ y ^ ror32(y, 16));
}
static __always_inline u32 subshift(u32 in[], int pos)
{
return (__aesti_sbox[in[pos] & 0xff]) ^
(__aesti_sbox[(in[(pos + 1) % 4] >> 8) & 0xff] << 8) ^
(__aesti_sbox[(in[(pos + 2) % 4] >> 16) & 0xff] << 16) ^
(__aesti_sbox[(in[(pos + 3) % 4] >> 24) & 0xff] << 24);
}
static __always_inline u32 inv_subshift(u32 in[], int pos)
{
return (__aesti_inv_sbox[in[pos] & 0xff]) ^
(__aesti_inv_sbox[(in[(pos + 3) % 4] >> 8) & 0xff] << 8) ^
(__aesti_inv_sbox[(in[(pos + 2) % 4] >> 16) & 0xff] << 16) ^
(__aesti_inv_sbox[(in[(pos + 1) % 4] >> 24) & 0xff] << 24);
}
static u32 subw(u32 in)
{
return (__aesti_sbox[in & 0xff]) ^
(__aesti_sbox[(in >> 8) & 0xff] << 8) ^
(__aesti_sbox[(in >> 16) & 0xff] << 16) ^
(__aesti_sbox[(in >> 24) & 0xff] << 24);
}
static int aesti_expand_key(struct crypto_aes_ctx *ctx, const u8 *in_key,
unsigned int key_len)
{
u32 kwords = key_len / sizeof(u32);
u32 rc, i, j;
if (key_len != AES_KEYSIZE_128 &&
key_len != AES_KEYSIZE_192 &&
key_len != AES_KEYSIZE_256)
return -EINVAL;
ctx->key_length = key_len;
for (i = 0; i < kwords; i++)
ctx->key_enc[i] = get_unaligned_le32(in_key + i * sizeof(u32));
for (i = 0, rc = 1; i < 10; i++, rc = mul_by_x(rc)) {
u32 *rki = ctx->key_enc + (i * kwords);
u32 *rko = rki + kwords;
rko[0] = ror32(subw(rki[kwords - 1]), 8) ^ rc ^ rki[0];
rko[1] = rko[0] ^ rki[1];
rko[2] = rko[1] ^ rki[2];
rko[3] = rko[2] ^ rki[3];
if (key_len == 24) {
if (i >= 7)
break;
rko[4] = rko[3] ^ rki[4];
rko[5] = rko[4] ^ rki[5];
} else if (key_len == 32) {
if (i >= 6)
break;
rko[4] = subw(rko[3]) ^ rki[4];
rko[5] = rko[4] ^ rki[5];
rko[6] = rko[5] ^ rki[6];
rko[7] = rko[6] ^ rki[7];
}
}
/*
* Generate the decryption keys for the Equivalent Inverse Cipher.
* This involves reversing the order of the round keys, and applying
* the Inverse Mix Columns transformation to all but the first and
* the last one.
*/
ctx->key_dec[0] = ctx->key_enc[key_len + 24];
ctx->key_dec[1] = ctx->key_enc[key_len + 25];
ctx->key_dec[2] = ctx->key_enc[key_len + 26];
ctx->key_dec[3] = ctx->key_enc[key_len + 27];
for (i = 4, j = key_len + 20; j > 0; i += 4, j -= 4) {
ctx->key_dec[i] = inv_mix_columns(ctx->key_enc[j]);
ctx->key_dec[i + 1] = inv_mix_columns(ctx->key_enc[j + 1]);
ctx->key_dec[i + 2] = inv_mix_columns(ctx->key_enc[j + 2]);
ctx->key_dec[i + 3] = inv_mix_columns(ctx->key_enc[j + 3]);
}
ctx->key_dec[i] = ctx->key_enc[0];
ctx->key_dec[i + 1] = ctx->key_enc[1];
ctx->key_dec[i + 2] = ctx->key_enc[2];
ctx->key_dec[i + 3] = ctx->key_enc[3];
return 0;
}
static int aesti_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct crypto_aes_ctx *ctx = crypto_tfm_ctx(tfm);
int err;
err = aesti_expand_key(ctx, in_key, key_len);
if (err)
return err;
/*
* In order to force the compiler to emit data independent Sbox lookups
* at the start of each block, xor the first round key with values at
* fixed indexes in the Sbox. This will need to be repeated each time
* the key is used, which will pull the entire Sbox into the D-cache
* before any data dependent Sbox lookups are performed.
*/
ctx->key_enc[0] ^= __aesti_sbox[ 0] ^ __aesti_sbox[128];
ctx->key_enc[1] ^= __aesti_sbox[32] ^ __aesti_sbox[160];
ctx->key_enc[2] ^= __aesti_sbox[64] ^ __aesti_sbox[192];
ctx->key_enc[3] ^= __aesti_sbox[96] ^ __aesti_sbox[224];
ctx->key_dec[0] ^= __aesti_inv_sbox[ 0] ^ __aesti_inv_sbox[128];
ctx->key_dec[1] ^= __aesti_inv_sbox[32] ^ __aesti_inv_sbox[160];
ctx->key_dec[2] ^= __aesti_inv_sbox[64] ^ __aesti_inv_sbox[192];
ctx->key_dec[3] ^= __aesti_inv_sbox[96] ^ __aesti_inv_sbox[224];
return 0;
}
static void aesti_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct crypto_aes_ctx *ctx = crypto_tfm_ctx(tfm);
const u32 *rkp = ctx->key_enc + 4;
int rounds = 6 + ctx->key_length / 4;
u32 st0[4], st1[4];
int round;
st0[0] = ctx->key_enc[0] ^ get_unaligned_le32(in);
st0[1] = ctx->key_enc[1] ^ get_unaligned_le32(in + 4);
st0[2] = ctx->key_enc[2] ^ get_unaligned_le32(in + 8);
st0[3] = ctx->key_enc[3] ^ get_unaligned_le32(in + 12);
st0[0] ^= __aesti_sbox[ 0] ^ __aesti_sbox[128];
st0[1] ^= __aesti_sbox[32] ^ __aesti_sbox[160];
st0[2] ^= __aesti_sbox[64] ^ __aesti_sbox[192];
st0[3] ^= __aesti_sbox[96] ^ __aesti_sbox[224];
for (round = 0;; round += 2, rkp += 8) {
st1[0] = mix_columns(subshift(st0, 0)) ^ rkp[0];
st1[1] = mix_columns(subshift(st0, 1)) ^ rkp[1];
st1[2] = mix_columns(subshift(st0, 2)) ^ rkp[2];
st1[3] = mix_columns(subshift(st0, 3)) ^ rkp[3];
if (round == rounds - 2)
break;
st0[0] = mix_columns(subshift(st1, 0)) ^ rkp[4];
st0[1] = mix_columns(subshift(st1, 1)) ^ rkp[5];
st0[2] = mix_columns(subshift(st1, 2)) ^ rkp[6];
st0[3] = mix_columns(subshift(st1, 3)) ^ rkp[7];
}
put_unaligned_le32(subshift(st1, 0) ^ rkp[4], out);
put_unaligned_le32(subshift(st1, 1) ^ rkp[5], out + 4);
put_unaligned_le32(subshift(st1, 2) ^ rkp[6], out + 8);
put_unaligned_le32(subshift(st1, 3) ^ rkp[7], out + 12);
}
static void aesti_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
const struct crypto_aes_ctx *ctx = crypto_tfm_ctx(tfm);
const u32 *rkp = ctx->key_dec + 4;
int rounds = 6 + ctx->key_length / 4;
u32 st0[4], st1[4];
int round;
st0[0] = ctx->key_dec[0] ^ get_unaligned_le32(in);
st0[1] = ctx->key_dec[1] ^ get_unaligned_le32(in + 4);
st0[2] = ctx->key_dec[2] ^ get_unaligned_le32(in + 8);
st0[3] = ctx->key_dec[3] ^ get_unaligned_le32(in + 12);
st0[0] ^= __aesti_inv_sbox[ 0] ^ __aesti_inv_sbox[128];
st0[1] ^= __aesti_inv_sbox[32] ^ __aesti_inv_sbox[160];
st0[2] ^= __aesti_inv_sbox[64] ^ __aesti_inv_sbox[192];
st0[3] ^= __aesti_inv_sbox[96] ^ __aesti_inv_sbox[224];
for (round = 0;; round += 2, rkp += 8) {
st1[0] = inv_mix_columns(inv_subshift(st0, 0)) ^ rkp[0];
st1[1] = inv_mix_columns(inv_subshift(st0, 1)) ^ rkp[1];
st1[2] = inv_mix_columns(inv_subshift(st0, 2)) ^ rkp[2];
st1[3] = inv_mix_columns(inv_subshift(st0, 3)) ^ rkp[3];
if (round == rounds - 2)
break;
st0[0] = inv_mix_columns(inv_subshift(st1, 0)) ^ rkp[4];
st0[1] = inv_mix_columns(inv_subshift(st1, 1)) ^ rkp[5];
st0[2] = inv_mix_columns(inv_subshift(st1, 2)) ^ rkp[6];
st0[3] = inv_mix_columns(inv_subshift(st1, 3)) ^ rkp[7];
}
put_unaligned_le32(inv_subshift(st1, 0) ^ rkp[4], out);
put_unaligned_le32(inv_subshift(st1, 1) ^ rkp[5], out + 4);
put_unaligned_le32(inv_subshift(st1, 2) ^ rkp[6], out + 8);
put_unaligned_le32(inv_subshift(st1, 3) ^ rkp[7], out + 12);
}
static struct crypto_alg aes_alg = {
.cra_name = "aes",
.cra_driver_name = "aes-fixed-time",
.cra_priority = 100 + 1,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct crypto_aes_ctx),
.cra_module = THIS_MODULE,
.cra_cipher.cia_min_keysize = AES_MIN_KEY_SIZE,
.cra_cipher.cia_max_keysize = AES_MAX_KEY_SIZE,
.cra_cipher.cia_setkey = aesti_set_key,
.cra_cipher.cia_encrypt = aesti_encrypt,
.cra_cipher.cia_decrypt = aesti_decrypt
};
static int __init aes_init(void)
{
return crypto_register_alg(&aes_alg);
}
static void __exit aes_fini(void)
{
crypto_unregister_alg(&aes_alg);
}
module_init(aes_init);
module_exit(aes_fini);
MODULE_DESCRIPTION("Generic fixed time AES");
MODULE_AUTHOR("Ard Biesheuvel <ard.biesheuvel@linaro.org>");
MODULE_LICENSE("GPL v2");
|
BPI-SINOVOIP/BPI-Mainline-kernel
|
linux-4.19/crypto/aes_ti.c
|
C
|
gpl-2.0
| 12,621
|
<?php
/**
* @package Joomla.Site
* @subpackage com_weblinks
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
$class = ' class="first"';
if (count($this->items[$this->parent->id]) > 0 && $this->maxLevelcat != 0) :
?>
<ul>
<?php foreach ($this->items[$this->parent->id] as $id => $item) : ?>
<?php
if ($this->params->get('show_empty_categories_cat') || $item->numitems || count($item->getChildren())) :
if (!isset($this->items[$this->parent->id][$id + 1]))
{
$class = ' class="last"';
}
?>
<li<?php echo $class; ?>>
<?php $class = ''; ?>
<span class="item-title"><a href="<?php echo JRoute::_(WeblinksHelperRoute::getCategoryRoute($item->id));?>">
<?php echo $this->escape($item->title); ?></a>
</span>
<?php if ($this->params->get('show_subcat_desc_cat') == 1) :?>
<?php if ($item->description) : ?>
<div class="category-desc">
<?php echo JHtml::_('content.prepare', $item->description, '', 'com_weblinks.categories'); ?>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if ($this->params->get('show_cat_num_links_cat') == 1) :?>
<dl class="weblink-count"><dt>
<?php echo JText::_('COM_WEBLINKS_NUM'); ?></dt>
<dd><?php echo $item->numitems; ?></dd>
</dl>
<?php endif; ?>
<?php if (count($item->getChildren()) > 0) :
$this->items[$item->id] = $item->getChildren();
$this->parent = $item;
$this->maxLevelcat--;
echo $this->loadTemplate('items');
$this->parent = $item->getParent();
$this->maxLevelcat++;
endif; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
|
laureduchemin/Tutorat-Informatique
|
tmp/td-okini-2/html/com_weblinks/categories/default_items.php
|
PHP
|
gpl-2.0
| 1,719
|
/* --------------------------------- SHS.CC ------------------------------- */
/*
* NIST proposed Secure Hash Standard.
*
* Written 2 September 1992, Peter C. Gutmann.
* This implementation placed in the public domain.
*
* Comments to pgut1@cs.aukuni.ac.nz
*/
// Force C++ compiler to use Java-style EH, so we don't have to link with
// libstdc++.
#pragma GCC java_exceptions
#include <string.h>
#include "shs.h"
/* The SHS f()-functions */
#define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) /* Rounds 0-19 */
#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */
#define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) /* Rounds 40-59 */
#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */
/* The SHS Mysterious Constants */
#define K1 0x5A827999L /* Rounds 0-19 */
#define K2 0x6ED9EBA1L /* Rounds 20-39 */
#define K3 0x8F1BBCDCL /* Rounds 40-59 */
#define K4 0xCA62C1D6L /* Rounds 60-79 */
/* SHS initial values */
#define h0init 0x67452301L
#define h1init 0xEFCDAB89L
#define h2init 0x98BADCFEL
#define h3init 0x10325476L
#define h4init 0xC3D2E1F0L
/* 32-bit rotate - kludged with shifts */
#define S(n,X) ((X << n) | (X >> (32 - n)))
/* The initial expanding function */
#define expand(count) W [count] = W [count - 3] ^ W [count - 8] ^ W [count - 14] ^ W [count - 16]
/* The four SHS sub-rounds */
#define subRound1(count) \
{ \
temp = S (5, A) + f1 (B, C, D) + E + W [count] + K1; \
E = D; \
D = C; \
C = S (30, B); \
B = A; \
A = temp; \
}
#define subRound2(count) \
{ \
temp = S (5, A) + f2 (B, C, D) + E + W [count] + K2; \
E = D; \
D = C; \
C = S (30, B); \
B = A; \
A = temp; \
}
#define subRound3(count) \
{ \
temp = S (5, A) + f3 (B, C, D) + E + W [count] + K3; \
E = D; \
D = C; \
C = S (30, B); \
B = A; \
A = temp; \
}
#define subRound4(count) \
{ \
temp = S (5, A) + f4 (B, C, D) + E + W [count] + K4; \
E = D; \
D = C; \
C = S (30, B); \
B = A; \
A = temp; \
}
/* The two buffers of 5 32-bit words */
uint32_t h0, h1, h2, h3, h4;
uint32_t A, B, C, D, E;
local void byteReverse OF((uint32_t *buffer, int byteCount));
void shsTransform OF((SHS_INFO *shsInfo));
/* Initialize the SHS values */
void shsInit (SHS_INFO *shsInfo)
{
/* Set the h-vars to their initial values */
shsInfo->digest [0] = h0init;
shsInfo->digest [1] = h1init;
shsInfo->digest [2] = h2init;
shsInfo->digest [3] = h3init;
shsInfo->digest [4] = h4init;
/* Initialise bit count */
shsInfo->countLo = shsInfo->countHi = 0L;
}
/*
* Perform the SHS transformation. Note that this code, like MD5, seems to
* break some optimizing compilers - it may be necessary to split it into
* sections, eg based on the four subrounds
*/
void shsTransform (SHS_INFO *shsInfo)
{
uint32_t W [80], temp;
int i;
/* Step A. Copy the data buffer into the local work buffer */
for (i = 0; i < 16; i++)
W [i] = shsInfo->data [i];
/* Step B. Expand the 16 words into 64 temporary data words */
expand (16); expand (17); expand (18); expand (19); expand (20);
expand (21); expand (22); expand (23); expand (24); expand (25);
expand (26); expand (27); expand (28); expand (29); expand (30);
expand (31); expand (32); expand (33); expand (34); expand (35);
expand (36); expand (37); expand (38); expand (39); expand (40);
expand (41); expand (42); expand (43); expand (44); expand (45);
expand (46); expand (47); expand (48); expand (49); expand (50);
expand (51); expand (52); expand (53); expand (54); expand (55);
expand (56); expand (57); expand (58); expand (59); expand (60);
expand (61); expand (62); expand (63); expand (64); expand (65);
expand (66); expand (67); expand (68); expand (69); expand (70);
expand (71); expand (72); expand (73); expand (74); expand (75);
expand (76); expand (77); expand (78); expand (79);
/* Step C. Set up first buffer */
A = shsInfo->digest [0];
B = shsInfo->digest [1];
C = shsInfo->digest [2];
D = shsInfo->digest [3];
E = shsInfo->digest [4];
/* Step D. Serious mangling, divided into four sub-rounds */
subRound1 (0); subRound1 (1); subRound1 (2); subRound1 (3);
subRound1 (4); subRound1 (5); subRound1 (6); subRound1 (7);
subRound1 (8); subRound1 (9); subRound1 (10); subRound1 (11);
subRound1 (12); subRound1 (13); subRound1 (14); subRound1 (15);
subRound1 (16); subRound1 (17); subRound1 (18); subRound1 (19);
subRound2 (20); subRound2 (21); subRound2 (22); subRound2 (23);
subRound2 (24); subRound2 (25); subRound2 (26); subRound2 (27);
subRound2 (28); subRound2 (29); subRound2 (30); subRound2 (31);
subRound2 (32); subRound2 (33); subRound2 (34); subRound2 (35);
subRound2 (36); subRound2 (37); subRound2 (38); subRound2 (39);
subRound3 (40); subRound3 (41); subRound3 (42); subRound3 (43);
subRound3 (44); subRound3 (45); subRound3 (46); subRound3 (47);
subRound3 (48); subRound3 (49); subRound3 (50); subRound3 (51);
subRound3 (52); subRound3 (53); subRound3 (54); subRound3 (55);
subRound3 (56); subRound3 (57); subRound3 (58); subRound3 (59);
subRound4 (60); subRound4 (61); subRound4 (62); subRound4 (63);
subRound4 (64); subRound4 (65); subRound4 (66); subRound4 (67);
subRound4 (68); subRound4 (69); subRound4 (70); subRound4 (71);
subRound4 (72); subRound4 (73); subRound4 (74); subRound4 (75);
subRound4 (76); subRound4 (77); subRound4 (78); subRound4 (79);
/* Step E. Build message digest */
shsInfo->digest [0] += A;
shsInfo->digest [1] += B;
shsInfo->digest [2] += C;
shsInfo->digest [3] += D;
shsInfo->digest [4] += E;
}
local void byteReverse (uint32_t *buffer, int byteCount)
{
uint32_t value;
int count;
/*
* Find out what the byte order is on this machine.
* Big endian is for machines that place the most significant byte
* first (eg. Sun SPARC). Little endian is for machines that place
* the least significant byte first (eg. VAX).
*
* We figure out the byte order by stuffing a 2 byte string into a
* short and examining the left byte. '@' = 0x40 and 'P' = 0x50
* If the left byte is the 'high' byte, then it is 'big endian'.
* If the left byte is the 'low' byte, then the machine is 'little
* endian'.
*
* -- Shawn A. Clifford (sac@eng.ufl.edu)
*/
/*
* Several bugs fixed -- Pat Myrto (pat@rwing.uucp)
*/
if ((*(unsigned short *) ("@P") >> 8) == '@')
return;
byteCount /= sizeof (uint32_t);
for (count = 0; count < byteCount; count++) {
value = (buffer [count] << 16) | (buffer [count] >> 16);
buffer [count] = ((value & 0xFF00FF00L) >> 8) | ((value & 0x00FF00FFL) << 8);
}
}
/*
* Update SHS for a block of data. This code assumes that the buffer size is
* a multiple of SHS_BLOCKSIZE bytes long, which makes the code a lot more
* efficient since it does away with the need to handle partial blocks
* between calls to shsUpdate()
*/
void shsUpdate (SHS_INFO *shsInfo, uint8_t *buffer, int count)
{
/* Update bitcount */
if ((shsInfo->countLo + ((uint32_t) count << 3)) < shsInfo->countLo)
shsInfo->countHi++; /* Carry from low to high bitCount */
shsInfo->countLo += ((uint32_t) count << 3);
shsInfo->countHi += ((uint32_t) count >> 29);
/* Process data in SHS_BLOCKSIZE chunks */
while (count >= SHS_BLOCKSIZE) {
memcpy (shsInfo->data, buffer, SHS_BLOCKSIZE);
byteReverse (shsInfo->data, SHS_BLOCKSIZE);
shsTransform (shsInfo);
buffer += SHS_BLOCKSIZE;
count -= SHS_BLOCKSIZE;
}
/*
* Handle any remaining bytes of data.
* This should only happen once on the final lot of data
*/
memcpy (shsInfo->data, buffer, count);
}
void shsFinal (SHS_INFO *shsInfo)
{
int count;
uint32_t lowBitcount = shsInfo->countLo, highBitcount = shsInfo->countHi;
/* Compute number of bytes mod 64 */
count = (int) ((shsInfo->countLo >> 3) & 0x3F);
/*
* Set the first char of padding to 0x80.
* This is safe since there is always at least one byte free
*/
((uint8_t *) shsInfo->data) [count++] = 0x80;
/* Pad out to 56 mod 64 */
if (count > 56) {
/* Two lots of padding: Pad the first block to 64 bytes */
memset ((uint8_t *) shsInfo->data + count, 0, 64 - count);
byteReverse (shsInfo->data, SHS_BLOCKSIZE);
shsTransform (shsInfo);
/* Now fill the next block with 56 bytes */
memset (shsInfo->data, 0, 56);
} else
/* Pad block to 56 bytes */
memset ((uint8_t *) shsInfo->data + count, 0, 56 - count);
byteReverse (shsInfo->data, SHS_BLOCKSIZE);
/* Append length in bits and transform */
shsInfo->data [14] = highBitcount;
shsInfo->data [15] = lowBitcount;
shsTransform (shsInfo);
byteReverse (shsInfo->data, SHS_DIGESTSIZE);
}
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/gcc/gcc-4.6.3/libjava/gnu/gcj/io/shs.cc
|
C++
|
gpl-2.0
| 8,681
|
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Add more helper methods to be used by all tests here...
end
|
ywjno/bootstrap-timepicker-rails-addon
|
testapp/rails5/test/test_helper.rb
|
Ruby
|
mit
| 212
|
/* bnx2x_sp.c: Broadcom Everest network driver.
*
* Copyright (c) 2011-2013 Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2, available
* at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a
* license other than the GPL, without Broadcom's express prior written
* consent.
*
* Maintained by: Ariel Elior <ariel.elior@qlogic.com>
* Written by: Vladislav Zolotarov
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/crc32.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/crc32c.h>
#include "bnx2x.h"
#include "bnx2x_cmn.h"
#include "bnx2x_sp.h"
#define BNX2X_MAX_EMUL_MULTI 16
/**** Exe Queue interfaces ****/
/**
* bnx2x_exe_queue_init - init the Exe Queue object
*
* @o: pointer to the object
* @exe_len: length
* @owner: pointer to the owner
* @validate: validate function pointer
* @optimize: optimize function pointer
* @exec: execute function pointer
* @get: get function pointer
*/
static inline void bnx2x_exe_queue_init(struct bnx2x *bp,
struct bnx2x_exe_queue_obj *o,
int exe_len,
union bnx2x_qable_obj *owner,
exe_q_validate validate,
exe_q_remove remove,
exe_q_optimize optimize,
exe_q_execute exec,
exe_q_get get)
{
memset(o, 0, sizeof(*o));
INIT_LIST_HEAD(&o->exe_queue);
INIT_LIST_HEAD(&o->pending_comp);
spin_lock_init(&o->lock);
o->exe_chunk_len = exe_len;
o->owner = owner;
/* Owner specific callbacks */
o->validate = validate;
o->remove = remove;
o->optimize = optimize;
o->execute = exec;
o->get = get;
DP(BNX2X_MSG_SP, "Setup the execution queue with the chunk length of %d\n",
exe_len);
}
static inline void bnx2x_exe_queue_free_elem(struct bnx2x *bp,
struct bnx2x_exeq_elem *elem)
{
DP(BNX2X_MSG_SP, "Deleting an exe_queue element\n");
kfree(elem);
}
static inline int bnx2x_exe_queue_length(struct bnx2x_exe_queue_obj *o)
{
struct bnx2x_exeq_elem *elem;
int cnt = 0;
spin_lock_bh(&o->lock);
list_for_each_entry(elem, &o->exe_queue, link)
cnt++;
spin_unlock_bh(&o->lock);
return cnt;
}
/**
* bnx2x_exe_queue_add - add a new element to the execution queue
*
* @bp: driver handle
* @o: queue
* @cmd: new command to add
* @restore: true - do not optimize the command
*
* If the element is optimized or is illegal, frees it.
*/
static inline int bnx2x_exe_queue_add(struct bnx2x *bp,
struct bnx2x_exe_queue_obj *o,
struct bnx2x_exeq_elem *elem,
bool restore)
{
int rc;
spin_lock_bh(&o->lock);
if (!restore) {
/* Try to cancel this element queue */
rc = o->optimize(bp, o->owner, elem);
if (rc)
goto free_and_exit;
/* Check if this request is ok */
rc = o->validate(bp, o->owner, elem);
if (rc) {
DP(BNX2X_MSG_SP, "Preamble failed: %d\n", rc);
goto free_and_exit;
}
}
/* If so, add it to the execution queue */
list_add_tail(&elem->link, &o->exe_queue);
spin_unlock_bh(&o->lock);
return 0;
free_and_exit:
bnx2x_exe_queue_free_elem(bp, elem);
spin_unlock_bh(&o->lock);
return rc;
}
static inline void __bnx2x_exe_queue_reset_pending(
struct bnx2x *bp,
struct bnx2x_exe_queue_obj *o)
{
struct bnx2x_exeq_elem *elem;
while (!list_empty(&o->pending_comp)) {
elem = list_first_entry(&o->pending_comp,
struct bnx2x_exeq_elem, link);
list_del(&elem->link);
bnx2x_exe_queue_free_elem(bp, elem);
}
}
/**
* bnx2x_exe_queue_step - execute one execution chunk atomically
*
* @bp: driver handle
* @o: queue
* @ramrod_flags: flags
*
* (Should be called while holding the exe_queue->lock).
*/
static inline int bnx2x_exe_queue_step(struct bnx2x *bp,
struct bnx2x_exe_queue_obj *o,
unsigned long *ramrod_flags)
{
struct bnx2x_exeq_elem *elem, spacer;
int cur_len = 0, rc;
memset(&spacer, 0, sizeof(spacer));
/* Next step should not be performed until the current is finished,
* unless a DRV_CLEAR_ONLY bit is set. In this case we just want to
* properly clear object internals without sending any command to the FW
* which also implies there won't be any completion to clear the
* 'pending' list.
*/
if (!list_empty(&o->pending_comp)) {
if (test_bit(RAMROD_DRV_CLR_ONLY, ramrod_flags)) {
DP(BNX2X_MSG_SP, "RAMROD_DRV_CLR_ONLY requested: resetting a pending_comp list\n");
__bnx2x_exe_queue_reset_pending(bp, o);
} else {
return 1;
}
}
/* Run through the pending commands list and create a next
* execution chunk.
*/
while (!list_empty(&o->exe_queue)) {
elem = list_first_entry(&o->exe_queue, struct bnx2x_exeq_elem,
link);
WARN_ON(!elem->cmd_len);
if (cur_len + elem->cmd_len <= o->exe_chunk_len) {
cur_len += elem->cmd_len;
/* Prevent from both lists being empty when moving an
* element. This will allow the call of
* bnx2x_exe_queue_empty() without locking.
*/
list_add_tail(&spacer.link, &o->pending_comp);
mb();
list_move_tail(&elem->link, &o->pending_comp);
list_del(&spacer.link);
} else
break;
}
/* Sanity check */
if (!cur_len)
return 0;
rc = o->execute(bp, o->owner, &o->pending_comp, ramrod_flags);
if (rc < 0)
/* In case of an error return the commands back to the queue
* and reset the pending_comp.
*/
list_splice_init(&o->pending_comp, &o->exe_queue);
else if (!rc)
/* If zero is returned, means there are no outstanding pending
* completions and we may dismiss the pending list.
*/
__bnx2x_exe_queue_reset_pending(bp, o);
return rc;
}
static inline bool bnx2x_exe_queue_empty(struct bnx2x_exe_queue_obj *o)
{
bool empty = list_empty(&o->exe_queue);
/* Don't reorder!!! */
mb();
return empty && list_empty(&o->pending_comp);
}
static inline struct bnx2x_exeq_elem *bnx2x_exe_queue_alloc_elem(
struct bnx2x *bp)
{
DP(BNX2X_MSG_SP, "Allocating a new exe_queue element\n");
return kzalloc(sizeof(struct bnx2x_exeq_elem), GFP_ATOMIC);
}
/************************ raw_obj functions ***********************************/
static bool bnx2x_raw_check_pending(struct bnx2x_raw_obj *o)
{
return !!test_bit(o->state, o->pstate);
}
static void bnx2x_raw_clear_pending(struct bnx2x_raw_obj *o)
{
smp_mb__before_atomic();
clear_bit(o->state, o->pstate);
smp_mb__after_atomic();
}
static void bnx2x_raw_set_pending(struct bnx2x_raw_obj *o)
{
smp_mb__before_atomic();
set_bit(o->state, o->pstate);
smp_mb__after_atomic();
}
/**
* bnx2x_state_wait - wait until the given bit(state) is cleared
*
* @bp: device handle
* @state: state which is to be cleared
* @state_p: state buffer
*
*/
static inline int bnx2x_state_wait(struct bnx2x *bp, int state,
unsigned long *pstate)
{
/* can take a while if any port is running */
int cnt = 5000;
if (CHIP_REV_IS_EMUL(bp))
cnt *= 20;
DP(BNX2X_MSG_SP, "waiting for state to become %d\n", state);
might_sleep();
while (cnt--) {
if (!test_bit(state, pstate)) {
#ifdef BNX2X_STOP_ON_ERROR
DP(BNX2X_MSG_SP, "exit (cnt %d)\n", 5000 - cnt);
#endif
return 0;
}
usleep_range(1000, 2000);
if (bp->panic)
return -EIO;
}
/* timeout! */
BNX2X_ERR("timeout waiting for state %d\n", state);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
return -EBUSY;
}
static int bnx2x_raw_wait(struct bnx2x *bp, struct bnx2x_raw_obj *raw)
{
return bnx2x_state_wait(bp, raw->state, raw->pstate);
}
/***************** Classification verbs: Set/Del MAC/VLAN/VLAN-MAC ************/
/* credit handling callbacks */
static bool bnx2x_get_cam_offset_mac(struct bnx2x_vlan_mac_obj *o, int *offset)
{
struct bnx2x_credit_pool_obj *mp = o->macs_pool;
WARN_ON(!mp);
return mp->get_entry(mp, offset);
}
static bool bnx2x_get_credit_mac(struct bnx2x_vlan_mac_obj *o)
{
struct bnx2x_credit_pool_obj *mp = o->macs_pool;
WARN_ON(!mp);
return mp->get(mp, 1);
}
static bool bnx2x_get_cam_offset_vlan(struct bnx2x_vlan_mac_obj *o, int *offset)
{
struct bnx2x_credit_pool_obj *vp = o->vlans_pool;
WARN_ON(!vp);
return vp->get_entry(vp, offset);
}
static bool bnx2x_get_credit_vlan(struct bnx2x_vlan_mac_obj *o)
{
struct bnx2x_credit_pool_obj *vp = o->vlans_pool;
WARN_ON(!vp);
return vp->get(vp, 1);
}
static bool bnx2x_put_cam_offset_mac(struct bnx2x_vlan_mac_obj *o, int offset)
{
struct bnx2x_credit_pool_obj *mp = o->macs_pool;
return mp->put_entry(mp, offset);
}
static bool bnx2x_put_credit_mac(struct bnx2x_vlan_mac_obj *o)
{
struct bnx2x_credit_pool_obj *mp = o->macs_pool;
return mp->put(mp, 1);
}
static bool bnx2x_put_cam_offset_vlan(struct bnx2x_vlan_mac_obj *o, int offset)
{
struct bnx2x_credit_pool_obj *vp = o->vlans_pool;
return vp->put_entry(vp, offset);
}
static bool bnx2x_put_credit_vlan(struct bnx2x_vlan_mac_obj *o)
{
struct bnx2x_credit_pool_obj *vp = o->vlans_pool;
return vp->put(vp, 1);
}
/**
* __bnx2x_vlan_mac_h_write_trylock - try getting the vlan mac writer lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details: Non-blocking implementation; should be called under execution
* queue lock.
*/
static int __bnx2x_vlan_mac_h_write_trylock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
if (o->head_reader) {
DP(BNX2X_MSG_SP, "vlan_mac_lock writer - There are readers; Busy\n");
return -EBUSY;
}
DP(BNX2X_MSG_SP, "vlan_mac_lock writer - Taken\n");
return 0;
}
/**
* __bnx2x_vlan_mac_h_exec_pending - execute step instead of a previous step
*
* @bp: device handle
* @o: vlan_mac object
*
* @details Should be called under execution queue lock; notice it might release
* and reclaim it during its run.
*/
static void __bnx2x_vlan_mac_h_exec_pending(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
int rc;
unsigned long ramrod_flags = o->saved_ramrod_flags;
DP(BNX2X_MSG_SP, "vlan_mac_lock execute pending command with ramrod flags %lu\n",
ramrod_flags);
o->head_exe_request = false;
o->saved_ramrod_flags = 0;
rc = bnx2x_exe_queue_step(bp, &o->exe_queue, &ramrod_flags);
if (rc != 0) {
BNX2X_ERR("execution of pending commands failed with rc %d\n",
rc);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
}
}
/**
* __bnx2x_vlan_mac_h_pend - Pend an execution step which couldn't run
*
* @bp: device handle
* @o: vlan_mac object
* @ramrod_flags: ramrod flags of missed execution
*
* @details Should be called under execution queue lock.
*/
static void __bnx2x_vlan_mac_h_pend(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
unsigned long ramrod_flags)
{
o->head_exe_request = true;
o->saved_ramrod_flags = ramrod_flags;
DP(BNX2X_MSG_SP, "Placing pending execution with ramrod flags %lu\n",
ramrod_flags);
}
/**
* __bnx2x_vlan_mac_h_write_unlock - unlock the vlan mac head list writer lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details Should be called under execution queue lock. Notice if a pending
* execution exists, it would perform it - possibly releasing and
* reclaiming the execution queue lock.
*/
static void __bnx2x_vlan_mac_h_write_unlock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
/* It's possible a new pending execution was added since this writer
* executed. If so, execute again. [Ad infinitum]
*/
while (o->head_exe_request) {
DP(BNX2X_MSG_SP, "vlan_mac_lock - writer release encountered a pending request\n");
__bnx2x_vlan_mac_h_exec_pending(bp, o);
}
}
/**
* __bnx2x_vlan_mac_h_read_lock - lock the vlan mac head list reader lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details Should be called under the execution queue lock. May sleep. May
* release and reclaim execution queue lock during its run.
*/
static int __bnx2x_vlan_mac_h_read_lock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
/* If we got here, we're holding lock --> no WRITER exists */
o->head_reader++;
DP(BNX2X_MSG_SP, "vlan_mac_lock - locked reader - number %d\n",
o->head_reader);
return 0;
}
/**
* bnx2x_vlan_mac_h_read_lock - lock the vlan mac head list reader lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details May sleep. Claims and releases execution queue lock during its run.
*/
int bnx2x_vlan_mac_h_read_lock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
int rc;
spin_lock_bh(&o->exe_queue.lock);
rc = __bnx2x_vlan_mac_h_read_lock(bp, o);
spin_unlock_bh(&o->exe_queue.lock);
return rc;
}
/**
* __bnx2x_vlan_mac_h_read_unlock - unlock the vlan mac head list reader lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details Should be called under execution queue lock. Notice if a pending
* execution exists, it would be performed if this was the last
* reader. possibly releasing and reclaiming the execution queue lock.
*/
static void __bnx2x_vlan_mac_h_read_unlock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
if (!o->head_reader) {
BNX2X_ERR("Need to release vlan mac reader lock, but lock isn't taken\n");
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
} else {
o->head_reader--;
DP(BNX2X_MSG_SP, "vlan_mac_lock - decreased readers to %d\n",
o->head_reader);
}
/* It's possible a new pending execution was added, and that this reader
* was last - if so we need to execute the command.
*/
if (!o->head_reader && o->head_exe_request) {
DP(BNX2X_MSG_SP, "vlan_mac_lock - reader release encountered a pending request\n");
/* Writer release will do the trick */
__bnx2x_vlan_mac_h_write_unlock(bp, o);
}
}
/**
* bnx2x_vlan_mac_h_read_unlock - unlock the vlan mac head list reader lock
*
* @bp: device handle
* @o: vlan_mac object
*
* @details Notice if a pending execution exists, it would be performed if this
* was the last reader. Claims and releases the execution queue lock
* during its run.
*/
void bnx2x_vlan_mac_h_read_unlock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
spin_lock_bh(&o->exe_queue.lock);
__bnx2x_vlan_mac_h_read_unlock(bp, o);
spin_unlock_bh(&o->exe_queue.lock);
}
static int bnx2x_get_n_elements(struct bnx2x *bp, struct bnx2x_vlan_mac_obj *o,
int n, u8 *base, u8 stride, u8 size)
{
struct bnx2x_vlan_mac_registry_elem *pos;
u8 *next = base;
int counter = 0;
int read_lock;
DP(BNX2X_MSG_SP, "get_n_elements - taking vlan_mac_lock (reader)\n");
read_lock = bnx2x_vlan_mac_h_read_lock(bp, o);
if (read_lock != 0)
BNX2X_ERR("get_n_elements failed to get vlan mac reader lock; Access without lock\n");
/* traverse list */
list_for_each_entry(pos, &o->head, link) {
if (counter < n) {
memcpy(next, &pos->u, size);
counter++;
DP(BNX2X_MSG_SP, "copied element number %d to address %p element was:\n",
counter, next);
next += stride + size;
}
}
if (read_lock == 0) {
DP(BNX2X_MSG_SP, "get_n_elements - releasing vlan_mac_lock (reader)\n");
bnx2x_vlan_mac_h_read_unlock(bp, o);
}
return counter * ETH_ALEN;
}
/* check_add() callbacks */
static int bnx2x_check_mac_add(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
union bnx2x_classification_ramrod_data *data)
{
struct bnx2x_vlan_mac_registry_elem *pos;
DP(BNX2X_MSG_SP, "Checking MAC %pM for ADD command\n", data->mac.mac);
if (!is_valid_ether_addr(data->mac.mac))
return -EINVAL;
/* Check if a requested MAC already exists */
list_for_each_entry(pos, &o->head, link)
if (ether_addr_equal(data->mac.mac, pos->u.mac.mac) &&
(data->mac.is_inner_mac == pos->u.mac.is_inner_mac))
return -EEXIST;
return 0;
}
static int bnx2x_check_vlan_add(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
union bnx2x_classification_ramrod_data *data)
{
struct bnx2x_vlan_mac_registry_elem *pos;
DP(BNX2X_MSG_SP, "Checking VLAN %d for ADD command\n", data->vlan.vlan);
list_for_each_entry(pos, &o->head, link)
if (data->vlan.vlan == pos->u.vlan.vlan)
return -EEXIST;
return 0;
}
/* check_del() callbacks */
static struct bnx2x_vlan_mac_registry_elem *
bnx2x_check_mac_del(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
union bnx2x_classification_ramrod_data *data)
{
struct bnx2x_vlan_mac_registry_elem *pos;
DP(BNX2X_MSG_SP, "Checking MAC %pM for DEL command\n", data->mac.mac);
list_for_each_entry(pos, &o->head, link)
if (ether_addr_equal(data->mac.mac, pos->u.mac.mac) &&
(data->mac.is_inner_mac == pos->u.mac.is_inner_mac))
return pos;
return NULL;
}
static struct bnx2x_vlan_mac_registry_elem *
bnx2x_check_vlan_del(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
union bnx2x_classification_ramrod_data *data)
{
struct bnx2x_vlan_mac_registry_elem *pos;
DP(BNX2X_MSG_SP, "Checking VLAN %d for DEL command\n", data->vlan.vlan);
list_for_each_entry(pos, &o->head, link)
if (data->vlan.vlan == pos->u.vlan.vlan)
return pos;
return NULL;
}
/* check_move() callback */
static bool bnx2x_check_move(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *src_o,
struct bnx2x_vlan_mac_obj *dst_o,
union bnx2x_classification_ramrod_data *data)
{
struct bnx2x_vlan_mac_registry_elem *pos;
int rc;
/* Check if we can delete the requested configuration from the first
* object.
*/
pos = src_o->check_del(bp, src_o, data);
/* check if configuration can be added */
rc = dst_o->check_add(bp, dst_o, data);
/* If this classification can not be added (is already set)
* or can't be deleted - return an error.
*/
if (rc || !pos)
return false;
return true;
}
static bool bnx2x_check_move_always_err(
struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *src_o,
struct bnx2x_vlan_mac_obj *dst_o,
union bnx2x_classification_ramrod_data *data)
{
return false;
}
static inline u8 bnx2x_vlan_mac_get_rx_tx_flag(struct bnx2x_vlan_mac_obj *o)
{
struct bnx2x_raw_obj *raw = &o->raw;
u8 rx_tx_flag = 0;
if ((raw->obj_type == BNX2X_OBJ_TYPE_TX) ||
(raw->obj_type == BNX2X_OBJ_TYPE_RX_TX))
rx_tx_flag |= ETH_CLASSIFY_CMD_HEADER_TX_CMD;
if ((raw->obj_type == BNX2X_OBJ_TYPE_RX) ||
(raw->obj_type == BNX2X_OBJ_TYPE_RX_TX))
rx_tx_flag |= ETH_CLASSIFY_CMD_HEADER_RX_CMD;
return rx_tx_flag;
}
static void bnx2x_set_mac_in_nig(struct bnx2x *bp,
bool add, unsigned char *dev_addr, int index)
{
u32 wb_data[2];
u32 reg_offset = BP_PORT(bp) ? NIG_REG_LLH1_FUNC_MEM :
NIG_REG_LLH0_FUNC_MEM;
if (!IS_MF_SI(bp) && !IS_MF_AFEX(bp))
return;
if (index > BNX2X_LLH_CAM_MAX_PF_LINE)
return;
DP(BNX2X_MSG_SP, "Going to %s LLH configuration at entry %d\n",
(add ? "ADD" : "DELETE"), index);
if (add) {
/* LLH_FUNC_MEM is a u64 WB register */
reg_offset += 8*index;
wb_data[0] = ((dev_addr[2] << 24) | (dev_addr[3] << 16) |
(dev_addr[4] << 8) | dev_addr[5]);
wb_data[1] = ((dev_addr[0] << 8) | dev_addr[1]);
REG_WR_DMAE(bp, reg_offset, wb_data, 2);
}
REG_WR(bp, (BP_PORT(bp) ? NIG_REG_LLH1_FUNC_MEM_ENABLE :
NIG_REG_LLH0_FUNC_MEM_ENABLE) + 4*index, add);
}
/**
* bnx2x_vlan_mac_set_cmd_hdr_e2 - set a header in a single classify ramrod
*
* @bp: device handle
* @o: queue for which we want to configure this rule
* @add: if true the command is an ADD command, DEL otherwise
* @opcode: CLASSIFY_RULE_OPCODE_XXX
* @hdr: pointer to a header to setup
*
*/
static inline void bnx2x_vlan_mac_set_cmd_hdr_e2(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o, bool add, int opcode,
struct eth_classify_cmd_header *hdr)
{
struct bnx2x_raw_obj *raw = &o->raw;
hdr->client_id = raw->cl_id;
hdr->func_id = raw->func_id;
/* Rx or/and Tx (internal switching) configuration ? */
hdr->cmd_general_data |=
bnx2x_vlan_mac_get_rx_tx_flag(o);
if (add)
hdr->cmd_general_data |= ETH_CLASSIFY_CMD_HEADER_IS_ADD;
hdr->cmd_general_data |=
(opcode << ETH_CLASSIFY_CMD_HEADER_OPCODE_SHIFT);
}
/**
* bnx2x_vlan_mac_set_rdata_hdr_e2 - set the classify ramrod data header
*
* @cid: connection id
* @type: BNX2X_FILTER_XXX_PENDING
* @hdr: pointer to header to setup
* @rule_cnt:
*
* currently we always configure one rule and echo field to contain a CID and an
* opcode type.
*/
static inline void bnx2x_vlan_mac_set_rdata_hdr_e2(u32 cid, int type,
struct eth_classify_header *hdr, int rule_cnt)
{
hdr->echo = cpu_to_le32((cid & BNX2X_SWCID_MASK) |
(type << BNX2X_SWCID_SHIFT));
hdr->rule_cnt = (u8)rule_cnt;
}
/* hw_config() callbacks */
static void bnx2x_set_one_mac_e2(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
struct bnx2x_exeq_elem *elem, int rule_idx,
int cam_offset)
{
struct bnx2x_raw_obj *raw = &o->raw;
struct eth_classify_rules_ramrod_data *data =
(struct eth_classify_rules_ramrod_data *)(raw->rdata);
int rule_cnt = rule_idx + 1, cmd = elem->cmd_data.vlan_mac.cmd;
union eth_classify_rule_cmd *rule_entry = &data->rules[rule_idx];
bool add = (cmd == BNX2X_VLAN_MAC_ADD) ? true : false;
unsigned long *vlan_mac_flags = &elem->cmd_data.vlan_mac.vlan_mac_flags;
u8 *mac = elem->cmd_data.vlan_mac.u.mac.mac;
/* Set LLH CAM entry: currently only iSCSI and ETH macs are
* relevant. In addition, current implementation is tuned for a
* single ETH MAC.
*
* When multiple unicast ETH MACs PF configuration in switch
* independent mode is required (NetQ, multiple netdev MACs,
* etc.), consider better utilisation of 8 per function MAC
* entries in the LLH register. There is also
* NIG_REG_P[01]_LLH_FUNC_MEM2 registers that complete the
* total number of CAM entries to 16.
*
* Currently we won't configure NIG for MACs other than a primary ETH
* MAC and iSCSI L2 MAC.
*
* If this MAC is moving from one Queue to another, no need to change
* NIG configuration.
*/
if (cmd != BNX2X_VLAN_MAC_MOVE) {
if (test_bit(BNX2X_ISCSI_ETH_MAC, vlan_mac_flags))
bnx2x_set_mac_in_nig(bp, add, mac,
BNX2X_LLH_CAM_ISCSI_ETH_LINE);
else if (test_bit(BNX2X_ETH_MAC, vlan_mac_flags))
bnx2x_set_mac_in_nig(bp, add, mac,
BNX2X_LLH_CAM_ETH_LINE);
}
/* Reset the ramrod data buffer for the first rule */
if (rule_idx == 0)
memset(data, 0, sizeof(*data));
/* Setup a command header */
bnx2x_vlan_mac_set_cmd_hdr_e2(bp, o, add, CLASSIFY_RULE_OPCODE_MAC,
&rule_entry->mac.header);
DP(BNX2X_MSG_SP, "About to %s MAC %pM for Queue %d\n",
(add ? "add" : "delete"), mac, raw->cl_id);
/* Set a MAC itself */
bnx2x_set_fw_mac_addr(&rule_entry->mac.mac_msb,
&rule_entry->mac.mac_mid,
&rule_entry->mac.mac_lsb, mac);
rule_entry->mac.inner_mac =
cpu_to_le16(elem->cmd_data.vlan_mac.u.mac.is_inner_mac);
/* MOVE: Add a rule that will add this MAC to the target Queue */
if (cmd == BNX2X_VLAN_MAC_MOVE) {
rule_entry++;
rule_cnt++;
/* Setup ramrod data */
bnx2x_vlan_mac_set_cmd_hdr_e2(bp,
elem->cmd_data.vlan_mac.target_obj,
true, CLASSIFY_RULE_OPCODE_MAC,
&rule_entry->mac.header);
/* Set a MAC itself */
bnx2x_set_fw_mac_addr(&rule_entry->mac.mac_msb,
&rule_entry->mac.mac_mid,
&rule_entry->mac.mac_lsb, mac);
rule_entry->mac.inner_mac =
cpu_to_le16(elem->cmd_data.vlan_mac.
u.mac.is_inner_mac);
}
/* Set the ramrod data header */
/* TODO: take this to the higher level in order to prevent multiple
writing */
bnx2x_vlan_mac_set_rdata_hdr_e2(raw->cid, raw->state, &data->header,
rule_cnt);
}
/**
* bnx2x_vlan_mac_set_rdata_hdr_e1x - set a header in a single classify ramrod
*
* @bp: device handle
* @o: queue
* @type:
* @cam_offset: offset in cam memory
* @hdr: pointer to a header to setup
*
* E1/E1H
*/
static inline void bnx2x_vlan_mac_set_rdata_hdr_e1x(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o, int type, int cam_offset,
struct mac_configuration_hdr *hdr)
{
struct bnx2x_raw_obj *r = &o->raw;
hdr->length = 1;
hdr->offset = (u8)cam_offset;
hdr->client_id = cpu_to_le16(0xff);
hdr->echo = cpu_to_le32((r->cid & BNX2X_SWCID_MASK) |
(type << BNX2X_SWCID_SHIFT));
}
static inline void bnx2x_vlan_mac_set_cfg_entry_e1x(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o, bool add, int opcode, u8 *mac,
u16 vlan_id, struct mac_configuration_entry *cfg_entry)
{
struct bnx2x_raw_obj *r = &o->raw;
u32 cl_bit_vec = (1 << r->cl_id);
cfg_entry->clients_bit_vector = cpu_to_le32(cl_bit_vec);
cfg_entry->pf_id = r->func_id;
cfg_entry->vlan_id = cpu_to_le16(vlan_id);
if (add) {
SET_FLAG(cfg_entry->flags, MAC_CONFIGURATION_ENTRY_ACTION_TYPE,
T_ETH_MAC_COMMAND_SET);
SET_FLAG(cfg_entry->flags,
MAC_CONFIGURATION_ENTRY_VLAN_FILTERING_MODE, opcode);
/* Set a MAC in a ramrod data */
bnx2x_set_fw_mac_addr(&cfg_entry->msb_mac_addr,
&cfg_entry->middle_mac_addr,
&cfg_entry->lsb_mac_addr, mac);
} else
SET_FLAG(cfg_entry->flags, MAC_CONFIGURATION_ENTRY_ACTION_TYPE,
T_ETH_MAC_COMMAND_INVALIDATE);
}
static inline void bnx2x_vlan_mac_set_rdata_e1x(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o, int type, int cam_offset, bool add,
u8 *mac, u16 vlan_id, int opcode, struct mac_configuration_cmd *config)
{
struct mac_configuration_entry *cfg_entry = &config->config_table[0];
struct bnx2x_raw_obj *raw = &o->raw;
bnx2x_vlan_mac_set_rdata_hdr_e1x(bp, o, type, cam_offset,
&config->hdr);
bnx2x_vlan_mac_set_cfg_entry_e1x(bp, o, add, opcode, mac, vlan_id,
cfg_entry);
DP(BNX2X_MSG_SP, "%s MAC %pM CLID %d CAM offset %d\n",
(add ? "setting" : "clearing"),
mac, raw->cl_id, cam_offset);
}
/**
* bnx2x_set_one_mac_e1x - fill a single MAC rule ramrod data
*
* @bp: device handle
* @o: bnx2x_vlan_mac_obj
* @elem: bnx2x_exeq_elem
* @rule_idx: rule_idx
* @cam_offset: cam_offset
*/
static void bnx2x_set_one_mac_e1x(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
struct bnx2x_exeq_elem *elem, int rule_idx,
int cam_offset)
{
struct bnx2x_raw_obj *raw = &o->raw;
struct mac_configuration_cmd *config =
(struct mac_configuration_cmd *)(raw->rdata);
/* 57710 and 57711 do not support MOVE command,
* so it's either ADD or DEL
*/
bool add = (elem->cmd_data.vlan_mac.cmd == BNX2X_VLAN_MAC_ADD) ?
true : false;
/* Reset the ramrod data buffer */
memset(config, 0, sizeof(*config));
bnx2x_vlan_mac_set_rdata_e1x(bp, o, raw->state,
cam_offset, add,
elem->cmd_data.vlan_mac.u.mac.mac, 0,
ETH_VLAN_FILTER_ANY_VLAN, config);
}
static void bnx2x_set_one_vlan_e2(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
struct bnx2x_exeq_elem *elem, int rule_idx,
int cam_offset)
{
struct bnx2x_raw_obj *raw = &o->raw;
struct eth_classify_rules_ramrod_data *data =
(struct eth_classify_rules_ramrod_data *)(raw->rdata);
int rule_cnt = rule_idx + 1;
union eth_classify_rule_cmd *rule_entry = &data->rules[rule_idx];
enum bnx2x_vlan_mac_cmd cmd = elem->cmd_data.vlan_mac.cmd;
bool add = (cmd == BNX2X_VLAN_MAC_ADD) ? true : false;
u16 vlan = elem->cmd_data.vlan_mac.u.vlan.vlan;
/* Reset the ramrod data buffer for the first rule */
if (rule_idx == 0)
memset(data, 0, sizeof(*data));
/* Set a rule header */
bnx2x_vlan_mac_set_cmd_hdr_e2(bp, o, add, CLASSIFY_RULE_OPCODE_VLAN,
&rule_entry->vlan.header);
DP(BNX2X_MSG_SP, "About to %s VLAN %d\n", (add ? "add" : "delete"),
vlan);
/* Set a VLAN itself */
rule_entry->vlan.vlan = cpu_to_le16(vlan);
/* MOVE: Add a rule that will add this MAC to the target Queue */
if (cmd == BNX2X_VLAN_MAC_MOVE) {
rule_entry++;
rule_cnt++;
/* Setup ramrod data */
bnx2x_vlan_mac_set_cmd_hdr_e2(bp,
elem->cmd_data.vlan_mac.target_obj,
true, CLASSIFY_RULE_OPCODE_VLAN,
&rule_entry->vlan.header);
/* Set a VLAN itself */
rule_entry->vlan.vlan = cpu_to_le16(vlan);
}
/* Set the ramrod data header */
/* TODO: take this to the higher level in order to prevent multiple
writing */
bnx2x_vlan_mac_set_rdata_hdr_e2(raw->cid, raw->state, &data->header,
rule_cnt);
}
/**
* bnx2x_vlan_mac_restore - reconfigure next MAC/VLAN/VLAN-MAC element
*
* @bp: device handle
* @p: command parameters
* @ppos: pointer to the cookie
*
* reconfigure next MAC/VLAN/VLAN-MAC element from the
* previously configured elements list.
*
* from command parameters only RAMROD_COMP_WAIT bit in ramrod_flags is taken
* into an account
*
* pointer to the cookie - that should be given back in the next call to make
* function handle the next element. If *ppos is set to NULL it will restart the
* iterator. If returned *ppos == NULL this means that the last element has been
* handled.
*
*/
static int bnx2x_vlan_mac_restore(struct bnx2x *bp,
struct bnx2x_vlan_mac_ramrod_params *p,
struct bnx2x_vlan_mac_registry_elem **ppos)
{
struct bnx2x_vlan_mac_registry_elem *pos;
struct bnx2x_vlan_mac_obj *o = p->vlan_mac_obj;
/* If list is empty - there is nothing to do here */
if (list_empty(&o->head)) {
*ppos = NULL;
return 0;
}
/* make a step... */
if (*ppos == NULL)
*ppos = list_first_entry(&o->head,
struct bnx2x_vlan_mac_registry_elem,
link);
else
*ppos = list_next_entry(*ppos, link);
pos = *ppos;
/* If it's the last step - return NULL */
if (list_is_last(&pos->link, &o->head))
*ppos = NULL;
/* Prepare a 'user_req' */
memcpy(&p->user_req.u, &pos->u, sizeof(pos->u));
/* Set the command */
p->user_req.cmd = BNX2X_VLAN_MAC_ADD;
/* Set vlan_mac_flags */
p->user_req.vlan_mac_flags = pos->vlan_mac_flags;
/* Set a restore bit */
__set_bit(RAMROD_RESTORE, &p->ramrod_flags);
return bnx2x_config_vlan_mac(bp, p);
}
/* bnx2x_exeq_get_mac/bnx2x_exeq_get_vlan/bnx2x_exeq_get_vlan_mac return a
* pointer to an element with a specific criteria and NULL if such an element
* hasn't been found.
*/
static struct bnx2x_exeq_elem *bnx2x_exeq_get_mac(
struct bnx2x_exe_queue_obj *o,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_exeq_elem *pos;
struct bnx2x_mac_ramrod_data *data = &elem->cmd_data.vlan_mac.u.mac;
/* Check pending for execution commands */
list_for_each_entry(pos, &o->exe_queue, link)
if (!memcmp(&pos->cmd_data.vlan_mac.u.mac, data,
sizeof(*data)) &&
(pos->cmd_data.vlan_mac.cmd == elem->cmd_data.vlan_mac.cmd))
return pos;
return NULL;
}
static struct bnx2x_exeq_elem *bnx2x_exeq_get_vlan(
struct bnx2x_exe_queue_obj *o,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_exeq_elem *pos;
struct bnx2x_vlan_ramrod_data *data = &elem->cmd_data.vlan_mac.u.vlan;
/* Check pending for execution commands */
list_for_each_entry(pos, &o->exe_queue, link)
if (!memcmp(&pos->cmd_data.vlan_mac.u.vlan, data,
sizeof(*data)) &&
(pos->cmd_data.vlan_mac.cmd == elem->cmd_data.vlan_mac.cmd))
return pos;
return NULL;
}
/**
* bnx2x_validate_vlan_mac_add - check if an ADD command can be executed
*
* @bp: device handle
* @qo: bnx2x_qable_obj
* @elem: bnx2x_exeq_elem
*
* Checks that the requested configuration can be added. If yes and if
* requested, consume CAM credit.
*
* The 'validate' is run after the 'optimize'.
*
*/
static inline int bnx2x_validate_vlan_mac_add(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_vlan_mac_obj *o = &qo->vlan_mac;
struct bnx2x_exe_queue_obj *exeq = &o->exe_queue;
int rc;
/* Check the registry */
rc = o->check_add(bp, o, &elem->cmd_data.vlan_mac.u);
if (rc) {
DP(BNX2X_MSG_SP, "ADD command is not allowed considering current registry state.\n");
return rc;
}
/* Check if there is a pending ADD command for this
* MAC/VLAN/VLAN-MAC. Return an error if there is.
*/
if (exeq->get(exeq, elem)) {
DP(BNX2X_MSG_SP, "There is a pending ADD command already\n");
return -EEXIST;
}
/* TODO: Check the pending MOVE from other objects where this
* object is a destination object.
*/
/* Consume the credit if not requested not to */
if (!(test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT,
&elem->cmd_data.vlan_mac.vlan_mac_flags) ||
o->get_credit(o)))
return -EINVAL;
return 0;
}
/**
* bnx2x_validate_vlan_mac_del - check if the DEL command can be executed
*
* @bp: device handle
* @qo: quable object to check
* @elem: element that needs to be deleted
*
* Checks that the requested configuration can be deleted. If yes and if
* requested, returns a CAM credit.
*
* The 'validate' is run after the 'optimize'.
*/
static inline int bnx2x_validate_vlan_mac_del(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_vlan_mac_obj *o = &qo->vlan_mac;
struct bnx2x_vlan_mac_registry_elem *pos;
struct bnx2x_exe_queue_obj *exeq = &o->exe_queue;
struct bnx2x_exeq_elem query_elem;
/* If this classification can not be deleted (doesn't exist)
* - return a BNX2X_EXIST.
*/
pos = o->check_del(bp, o, &elem->cmd_data.vlan_mac.u);
if (!pos) {
DP(BNX2X_MSG_SP, "DEL command is not allowed considering current registry state\n");
return -EEXIST;
}
/* Check if there are pending DEL or MOVE commands for this
* MAC/VLAN/VLAN-MAC. Return an error if so.
*/
memcpy(&query_elem, elem, sizeof(query_elem));
/* Check for MOVE commands */
query_elem.cmd_data.vlan_mac.cmd = BNX2X_VLAN_MAC_MOVE;
if (exeq->get(exeq, &query_elem)) {
BNX2X_ERR("There is a pending MOVE command already\n");
return -EINVAL;
}
/* Check for DEL commands */
if (exeq->get(exeq, elem)) {
DP(BNX2X_MSG_SP, "There is a pending DEL command already\n");
return -EEXIST;
}
/* Return the credit to the credit pool if not requested not to */
if (!(test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT,
&elem->cmd_data.vlan_mac.vlan_mac_flags) ||
o->put_credit(o))) {
BNX2X_ERR("Failed to return a credit\n");
return -EINVAL;
}
return 0;
}
/**
* bnx2x_validate_vlan_mac_move - check if the MOVE command can be executed
*
* @bp: device handle
* @qo: quable object to check (source)
* @elem: element that needs to be moved
*
* Checks that the requested configuration can be moved. If yes and if
* requested, returns a CAM credit.
*
* The 'validate' is run after the 'optimize'.
*/
static inline int bnx2x_validate_vlan_mac_move(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_vlan_mac_obj *src_o = &qo->vlan_mac;
struct bnx2x_vlan_mac_obj *dest_o = elem->cmd_data.vlan_mac.target_obj;
struct bnx2x_exeq_elem query_elem;
struct bnx2x_exe_queue_obj *src_exeq = &src_o->exe_queue;
struct bnx2x_exe_queue_obj *dest_exeq = &dest_o->exe_queue;
/* Check if we can perform this operation based on the current registry
* state.
*/
if (!src_o->check_move(bp, src_o, dest_o,
&elem->cmd_data.vlan_mac.u)) {
DP(BNX2X_MSG_SP, "MOVE command is not allowed considering current registry state\n");
return -EINVAL;
}
/* Check if there is an already pending DEL or MOVE command for the
* source object or ADD command for a destination object. Return an
* error if so.
*/
memcpy(&query_elem, elem, sizeof(query_elem));
/* Check DEL on source */
query_elem.cmd_data.vlan_mac.cmd = BNX2X_VLAN_MAC_DEL;
if (src_exeq->get(src_exeq, &query_elem)) {
BNX2X_ERR("There is a pending DEL command on the source queue already\n");
return -EINVAL;
}
/* Check MOVE on source */
if (src_exeq->get(src_exeq, elem)) {
DP(BNX2X_MSG_SP, "There is a pending MOVE command already\n");
return -EEXIST;
}
/* Check ADD on destination */
query_elem.cmd_data.vlan_mac.cmd = BNX2X_VLAN_MAC_ADD;
if (dest_exeq->get(dest_exeq, &query_elem)) {
BNX2X_ERR("There is a pending ADD command on the destination queue already\n");
return -EINVAL;
}
/* Consume the credit if not requested not to */
if (!(test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT_DEST,
&elem->cmd_data.vlan_mac.vlan_mac_flags) ||
dest_o->get_credit(dest_o)))
return -EINVAL;
if (!(test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT,
&elem->cmd_data.vlan_mac.vlan_mac_flags) ||
src_o->put_credit(src_o))) {
/* return the credit taken from dest... */
dest_o->put_credit(dest_o);
return -EINVAL;
}
return 0;
}
static int bnx2x_validate_vlan_mac(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
switch (elem->cmd_data.vlan_mac.cmd) {
case BNX2X_VLAN_MAC_ADD:
return bnx2x_validate_vlan_mac_add(bp, qo, elem);
case BNX2X_VLAN_MAC_DEL:
return bnx2x_validate_vlan_mac_del(bp, qo, elem);
case BNX2X_VLAN_MAC_MOVE:
return bnx2x_validate_vlan_mac_move(bp, qo, elem);
default:
return -EINVAL;
}
}
static int bnx2x_remove_vlan_mac(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
int rc = 0;
/* If consumption wasn't required, nothing to do */
if (test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT,
&elem->cmd_data.vlan_mac.vlan_mac_flags))
return 0;
switch (elem->cmd_data.vlan_mac.cmd) {
case BNX2X_VLAN_MAC_ADD:
case BNX2X_VLAN_MAC_MOVE:
rc = qo->vlan_mac.put_credit(&qo->vlan_mac);
break;
case BNX2X_VLAN_MAC_DEL:
rc = qo->vlan_mac.get_credit(&qo->vlan_mac);
break;
default:
return -EINVAL;
}
if (rc != true)
return -EINVAL;
return 0;
}
/**
* bnx2x_wait_vlan_mac - passively wait for 5 seconds until all work completes.
*
* @bp: device handle
* @o: bnx2x_vlan_mac_obj
*
*/
static int bnx2x_wait_vlan_mac(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
int cnt = 5000, rc;
struct bnx2x_exe_queue_obj *exeq = &o->exe_queue;
struct bnx2x_raw_obj *raw = &o->raw;
while (cnt--) {
/* Wait for the current command to complete */
rc = raw->wait_comp(bp, raw);
if (rc)
return rc;
/* Wait until there are no pending commands */
if (!bnx2x_exe_queue_empty(exeq))
usleep_range(1000, 2000);
else
return 0;
}
return -EBUSY;
}
static int __bnx2x_vlan_mac_execute_step(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
unsigned long *ramrod_flags)
{
int rc = 0;
spin_lock_bh(&o->exe_queue.lock);
DP(BNX2X_MSG_SP, "vlan_mac_execute_step - trying to take writer lock\n");
rc = __bnx2x_vlan_mac_h_write_trylock(bp, o);
if (rc != 0) {
__bnx2x_vlan_mac_h_pend(bp, o, *ramrod_flags);
/* Calling function should not diffrentiate between this case
* and the case in which there is already a pending ramrod
*/
rc = 1;
} else {
rc = bnx2x_exe_queue_step(bp, &o->exe_queue, ramrod_flags);
}
spin_unlock_bh(&o->exe_queue.lock);
return rc;
}
/**
* bnx2x_complete_vlan_mac - complete one VLAN-MAC ramrod
*
* @bp: device handle
* @o: bnx2x_vlan_mac_obj
* @cqe:
* @cont: if true schedule next execution chunk
*
*/
static int bnx2x_complete_vlan_mac(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
union event_ring_elem *cqe,
unsigned long *ramrod_flags)
{
struct bnx2x_raw_obj *r = &o->raw;
int rc;
/* Clearing the pending list & raw state should be made
* atomically (as execution flow assumes they represent the same).
*/
spin_lock_bh(&o->exe_queue.lock);
/* Reset pending list */
__bnx2x_exe_queue_reset_pending(bp, &o->exe_queue);
/* Clear pending */
r->clear_pending(r);
spin_unlock_bh(&o->exe_queue.lock);
/* If ramrod failed this is most likely a SW bug */
if (cqe->message.error)
return -EINVAL;
/* Run the next bulk of pending commands if requested */
if (test_bit(RAMROD_CONT, ramrod_flags)) {
rc = __bnx2x_vlan_mac_execute_step(bp, o, ramrod_flags);
if (rc < 0)
return rc;
}
/* If there is more work to do return PENDING */
if (!bnx2x_exe_queue_empty(&o->exe_queue))
return 1;
return 0;
}
/**
* bnx2x_optimize_vlan_mac - optimize ADD and DEL commands.
*
* @bp: device handle
* @o: bnx2x_qable_obj
* @elem: bnx2x_exeq_elem
*/
static int bnx2x_optimize_vlan_mac(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct bnx2x_exeq_elem *elem)
{
struct bnx2x_exeq_elem query, *pos;
struct bnx2x_vlan_mac_obj *o = &qo->vlan_mac;
struct bnx2x_exe_queue_obj *exeq = &o->exe_queue;
memcpy(&query, elem, sizeof(query));
switch (elem->cmd_data.vlan_mac.cmd) {
case BNX2X_VLAN_MAC_ADD:
query.cmd_data.vlan_mac.cmd = BNX2X_VLAN_MAC_DEL;
break;
case BNX2X_VLAN_MAC_DEL:
query.cmd_data.vlan_mac.cmd = BNX2X_VLAN_MAC_ADD;
break;
default:
/* Don't handle anything other than ADD or DEL */
return 0;
}
/* If we found the appropriate element - delete it */
pos = exeq->get(exeq, &query);
if (pos) {
/* Return the credit of the optimized command */
if (!test_bit(BNX2X_DONT_CONSUME_CAM_CREDIT,
&pos->cmd_data.vlan_mac.vlan_mac_flags)) {
if ((query.cmd_data.vlan_mac.cmd ==
BNX2X_VLAN_MAC_ADD) && !o->put_credit(o)) {
BNX2X_ERR("Failed to return the credit for the optimized ADD command\n");
return -EINVAL;
} else if (!o->get_credit(o)) { /* VLAN_MAC_DEL */
BNX2X_ERR("Failed to recover the credit from the optimized DEL command\n");
return -EINVAL;
}
}
DP(BNX2X_MSG_SP, "Optimizing %s command\n",
(elem->cmd_data.vlan_mac.cmd == BNX2X_VLAN_MAC_ADD) ?
"ADD" : "DEL");
list_del(&pos->link);
bnx2x_exe_queue_free_elem(bp, pos);
return 1;
}
return 0;
}
/**
* bnx2x_vlan_mac_get_registry_elem - prepare a registry element
*
* @bp: device handle
* @o:
* @elem:
* @restore:
* @re:
*
* prepare a registry element according to the current command request.
*/
static inline int bnx2x_vlan_mac_get_registry_elem(
struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
struct bnx2x_exeq_elem *elem,
bool restore,
struct bnx2x_vlan_mac_registry_elem **re)
{
enum bnx2x_vlan_mac_cmd cmd = elem->cmd_data.vlan_mac.cmd;
struct bnx2x_vlan_mac_registry_elem *reg_elem;
/* Allocate a new registry element if needed. */
if (!restore &&
((cmd == BNX2X_VLAN_MAC_ADD) || (cmd == BNX2X_VLAN_MAC_MOVE))) {
reg_elem = kzalloc(sizeof(*reg_elem), GFP_ATOMIC);
if (!reg_elem)
return -ENOMEM;
/* Get a new CAM offset */
if (!o->get_cam_offset(o, ®_elem->cam_offset)) {
/* This shall never happen, because we have checked the
* CAM availability in the 'validate'.
*/
WARN_ON(1);
kfree(reg_elem);
return -EINVAL;
}
DP(BNX2X_MSG_SP, "Got cam offset %d\n", reg_elem->cam_offset);
/* Set a VLAN-MAC data */
memcpy(®_elem->u, &elem->cmd_data.vlan_mac.u,
sizeof(reg_elem->u));
/* Copy the flags (needed for DEL and RESTORE flows) */
reg_elem->vlan_mac_flags =
elem->cmd_data.vlan_mac.vlan_mac_flags;
} else /* DEL, RESTORE */
reg_elem = o->check_del(bp, o, &elem->cmd_data.vlan_mac.u);
*re = reg_elem;
return 0;
}
/**
* bnx2x_execute_vlan_mac - execute vlan mac command
*
* @bp: device handle
* @qo:
* @exe_chunk:
* @ramrod_flags:
*
* go and send a ramrod!
*/
static int bnx2x_execute_vlan_mac(struct bnx2x *bp,
union bnx2x_qable_obj *qo,
struct list_head *exe_chunk,
unsigned long *ramrod_flags)
{
struct bnx2x_exeq_elem *elem;
struct bnx2x_vlan_mac_obj *o = &qo->vlan_mac, *cam_obj;
struct bnx2x_raw_obj *r = &o->raw;
int rc, idx = 0;
bool restore = test_bit(RAMROD_RESTORE, ramrod_flags);
bool drv_only = test_bit(RAMROD_DRV_CLR_ONLY, ramrod_flags);
struct bnx2x_vlan_mac_registry_elem *reg_elem;
enum bnx2x_vlan_mac_cmd cmd;
/* If DRIVER_ONLY execution is requested, cleanup a registry
* and exit. Otherwise send a ramrod to FW.
*/
if (!drv_only) {
WARN_ON(r->check_pending(r));
/* Set pending */
r->set_pending(r);
/* Fill the ramrod data */
list_for_each_entry(elem, exe_chunk, link) {
cmd = elem->cmd_data.vlan_mac.cmd;
/* We will add to the target object in MOVE command, so
* change the object for a CAM search.
*/
if (cmd == BNX2X_VLAN_MAC_MOVE)
cam_obj = elem->cmd_data.vlan_mac.target_obj;
else
cam_obj = o;
rc = bnx2x_vlan_mac_get_registry_elem(bp, cam_obj,
elem, restore,
®_elem);
if (rc)
goto error_exit;
WARN_ON(!reg_elem);
/* Push a new entry into the registry */
if (!restore &&
((cmd == BNX2X_VLAN_MAC_ADD) ||
(cmd == BNX2X_VLAN_MAC_MOVE)))
list_add(®_elem->link, &cam_obj->head);
/* Configure a single command in a ramrod data buffer */
o->set_one_rule(bp, o, elem, idx,
reg_elem->cam_offset);
/* MOVE command consumes 2 entries in the ramrod data */
if (cmd == BNX2X_VLAN_MAC_MOVE)
idx += 2;
else
idx++;
}
/* No need for an explicit memory barrier here as long we would
* need to ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read and we will have to put a full memory barrier there
* (inside bnx2x_sp_post()).
*/
rc = bnx2x_sp_post(bp, o->ramrod_cmd, r->cid,
U64_HI(r->rdata_mapping),
U64_LO(r->rdata_mapping),
ETH_CONNECTION_TYPE);
if (rc)
goto error_exit;
}
/* Now, when we are done with the ramrod - clean up the registry */
list_for_each_entry(elem, exe_chunk, link) {
cmd = elem->cmd_data.vlan_mac.cmd;
if ((cmd == BNX2X_VLAN_MAC_DEL) ||
(cmd == BNX2X_VLAN_MAC_MOVE)) {
reg_elem = o->check_del(bp, o,
&elem->cmd_data.vlan_mac.u);
WARN_ON(!reg_elem);
o->put_cam_offset(o, reg_elem->cam_offset);
list_del(®_elem->link);
kfree(reg_elem);
}
}
if (!drv_only)
return 1;
else
return 0;
error_exit:
r->clear_pending(r);
/* Cleanup a registry in case of a failure */
list_for_each_entry(elem, exe_chunk, link) {
cmd = elem->cmd_data.vlan_mac.cmd;
if (cmd == BNX2X_VLAN_MAC_MOVE)
cam_obj = elem->cmd_data.vlan_mac.target_obj;
else
cam_obj = o;
/* Delete all newly added above entries */
if (!restore &&
((cmd == BNX2X_VLAN_MAC_ADD) ||
(cmd == BNX2X_VLAN_MAC_MOVE))) {
reg_elem = o->check_del(bp, cam_obj,
&elem->cmd_data.vlan_mac.u);
if (reg_elem) {
list_del(®_elem->link);
kfree(reg_elem);
}
}
}
return rc;
}
static inline int bnx2x_vlan_mac_push_new_cmd(
struct bnx2x *bp,
struct bnx2x_vlan_mac_ramrod_params *p)
{
struct bnx2x_exeq_elem *elem;
struct bnx2x_vlan_mac_obj *o = p->vlan_mac_obj;
bool restore = test_bit(RAMROD_RESTORE, &p->ramrod_flags);
/* Allocate the execution queue element */
elem = bnx2x_exe_queue_alloc_elem(bp);
if (!elem)
return -ENOMEM;
/* Set the command 'length' */
switch (p->user_req.cmd) {
case BNX2X_VLAN_MAC_MOVE:
elem->cmd_len = 2;
break;
default:
elem->cmd_len = 1;
}
/* Fill the object specific info */
memcpy(&elem->cmd_data.vlan_mac, &p->user_req, sizeof(p->user_req));
/* Try to add a new command to the pending list */
return bnx2x_exe_queue_add(bp, &o->exe_queue, elem, restore);
}
/**
* bnx2x_config_vlan_mac - configure VLAN/MAC/VLAN_MAC filtering rules.
*
* @bp: device handle
* @p:
*
*/
int bnx2x_config_vlan_mac(struct bnx2x *bp,
struct bnx2x_vlan_mac_ramrod_params *p)
{
int rc = 0;
struct bnx2x_vlan_mac_obj *o = p->vlan_mac_obj;
unsigned long *ramrod_flags = &p->ramrod_flags;
bool cont = test_bit(RAMROD_CONT, ramrod_flags);
struct bnx2x_raw_obj *raw = &o->raw;
/*
* Add new elements to the execution list for commands that require it.
*/
if (!cont) {
rc = bnx2x_vlan_mac_push_new_cmd(bp, p);
if (rc)
return rc;
}
/* If nothing will be executed further in this iteration we want to
* return PENDING if there are pending commands
*/
if (!bnx2x_exe_queue_empty(&o->exe_queue))
rc = 1;
if (test_bit(RAMROD_DRV_CLR_ONLY, ramrod_flags)) {
DP(BNX2X_MSG_SP, "RAMROD_DRV_CLR_ONLY requested: clearing a pending bit.\n");
raw->clear_pending(raw);
}
/* Execute commands if required */
if (cont || test_bit(RAMROD_EXEC, ramrod_flags) ||
test_bit(RAMROD_COMP_WAIT, ramrod_flags)) {
rc = __bnx2x_vlan_mac_execute_step(bp, p->vlan_mac_obj,
&p->ramrod_flags);
if (rc < 0)
return rc;
}
/* RAMROD_COMP_WAIT is a superset of RAMROD_EXEC. If it was set
* then user want to wait until the last command is done.
*/
if (test_bit(RAMROD_COMP_WAIT, &p->ramrod_flags)) {
/* Wait maximum for the current exe_queue length iterations plus
* one (for the current pending command).
*/
int max_iterations = bnx2x_exe_queue_length(&o->exe_queue) + 1;
while (!bnx2x_exe_queue_empty(&o->exe_queue) &&
max_iterations--) {
/* Wait for the current command to complete */
rc = raw->wait_comp(bp, raw);
if (rc)
return rc;
/* Make a next step */
rc = __bnx2x_vlan_mac_execute_step(bp,
p->vlan_mac_obj,
&p->ramrod_flags);
if (rc < 0)
return rc;
}
return 0;
}
return rc;
}
/**
* bnx2x_vlan_mac_del_all - delete elements with given vlan_mac_flags spec
*
* @bp: device handle
* @o:
* @vlan_mac_flags:
* @ramrod_flags: execution flags to be used for this deletion
*
* if the last operation has completed successfully and there are no
* more elements left, positive value if the last operation has completed
* successfully and there are more previously configured elements, negative
* value is current operation has failed.
*/
static int bnx2x_vlan_mac_del_all(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o,
unsigned long *vlan_mac_flags,
unsigned long *ramrod_flags)
{
struct bnx2x_vlan_mac_registry_elem *pos = NULL;
struct bnx2x_vlan_mac_ramrod_params p;
struct bnx2x_exe_queue_obj *exeq = &o->exe_queue;
struct bnx2x_exeq_elem *exeq_pos, *exeq_pos_n;
unsigned long flags;
int read_lock;
int rc = 0;
/* Clear pending commands first */
spin_lock_bh(&exeq->lock);
list_for_each_entry_safe(exeq_pos, exeq_pos_n, &exeq->exe_queue, link) {
flags = exeq_pos->cmd_data.vlan_mac.vlan_mac_flags;
if (BNX2X_VLAN_MAC_CMP_FLAGS(flags) ==
BNX2X_VLAN_MAC_CMP_FLAGS(*vlan_mac_flags)) {
rc = exeq->remove(bp, exeq->owner, exeq_pos);
if (rc) {
BNX2X_ERR("Failed to remove command\n");
spin_unlock_bh(&exeq->lock);
return rc;
}
list_del(&exeq_pos->link);
bnx2x_exe_queue_free_elem(bp, exeq_pos);
}
}
spin_unlock_bh(&exeq->lock);
/* Prepare a command request */
memset(&p, 0, sizeof(p));
p.vlan_mac_obj = o;
p.ramrod_flags = *ramrod_flags;
p.user_req.cmd = BNX2X_VLAN_MAC_DEL;
/* Add all but the last VLAN-MAC to the execution queue without actually
* execution anything.
*/
__clear_bit(RAMROD_COMP_WAIT, &p.ramrod_flags);
__clear_bit(RAMROD_EXEC, &p.ramrod_flags);
__clear_bit(RAMROD_CONT, &p.ramrod_flags);
DP(BNX2X_MSG_SP, "vlan_mac_del_all -- taking vlan_mac_lock (reader)\n");
read_lock = bnx2x_vlan_mac_h_read_lock(bp, o);
if (read_lock != 0)
return read_lock;
list_for_each_entry(pos, &o->head, link) {
flags = pos->vlan_mac_flags;
if (BNX2X_VLAN_MAC_CMP_FLAGS(flags) ==
BNX2X_VLAN_MAC_CMP_FLAGS(*vlan_mac_flags)) {
p.user_req.vlan_mac_flags = pos->vlan_mac_flags;
memcpy(&p.user_req.u, &pos->u, sizeof(pos->u));
rc = bnx2x_config_vlan_mac(bp, &p);
if (rc < 0) {
BNX2X_ERR("Failed to add a new DEL command\n");
bnx2x_vlan_mac_h_read_unlock(bp, o);
return rc;
}
}
}
DP(BNX2X_MSG_SP, "vlan_mac_del_all -- releasing vlan_mac_lock (reader)\n");
bnx2x_vlan_mac_h_read_unlock(bp, o);
p.ramrod_flags = *ramrod_flags;
__set_bit(RAMROD_CONT, &p.ramrod_flags);
return bnx2x_config_vlan_mac(bp, &p);
}
static inline void bnx2x_init_raw_obj(struct bnx2x_raw_obj *raw, u8 cl_id,
u32 cid, u8 func_id, void *rdata, dma_addr_t rdata_mapping, int state,
unsigned long *pstate, bnx2x_obj_type type)
{
raw->func_id = func_id;
raw->cid = cid;
raw->cl_id = cl_id;
raw->rdata = rdata;
raw->rdata_mapping = rdata_mapping;
raw->state = state;
raw->pstate = pstate;
raw->obj_type = type;
raw->check_pending = bnx2x_raw_check_pending;
raw->clear_pending = bnx2x_raw_clear_pending;
raw->set_pending = bnx2x_raw_set_pending;
raw->wait_comp = bnx2x_raw_wait;
}
static inline void bnx2x_init_vlan_mac_common(struct bnx2x_vlan_mac_obj *o,
u8 cl_id, u32 cid, u8 func_id, void *rdata, dma_addr_t rdata_mapping,
int state, unsigned long *pstate, bnx2x_obj_type type,
struct bnx2x_credit_pool_obj *macs_pool,
struct bnx2x_credit_pool_obj *vlans_pool)
{
INIT_LIST_HEAD(&o->head);
o->head_reader = 0;
o->head_exe_request = false;
o->saved_ramrod_flags = 0;
o->macs_pool = macs_pool;
o->vlans_pool = vlans_pool;
o->delete_all = bnx2x_vlan_mac_del_all;
o->restore = bnx2x_vlan_mac_restore;
o->complete = bnx2x_complete_vlan_mac;
o->wait = bnx2x_wait_vlan_mac;
bnx2x_init_raw_obj(&o->raw, cl_id, cid, func_id, rdata, rdata_mapping,
state, pstate, type);
}
void bnx2x_init_mac_obj(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *mac_obj,
u8 cl_id, u32 cid, u8 func_id, void *rdata,
dma_addr_t rdata_mapping, int state,
unsigned long *pstate, bnx2x_obj_type type,
struct bnx2x_credit_pool_obj *macs_pool)
{
union bnx2x_qable_obj *qable_obj = (union bnx2x_qable_obj *)mac_obj;
bnx2x_init_vlan_mac_common(mac_obj, cl_id, cid, func_id, rdata,
rdata_mapping, state, pstate, type,
macs_pool, NULL);
/* CAM credit pool handling */
mac_obj->get_credit = bnx2x_get_credit_mac;
mac_obj->put_credit = bnx2x_put_credit_mac;
mac_obj->get_cam_offset = bnx2x_get_cam_offset_mac;
mac_obj->put_cam_offset = bnx2x_put_cam_offset_mac;
if (CHIP_IS_E1x(bp)) {
mac_obj->set_one_rule = bnx2x_set_one_mac_e1x;
mac_obj->check_del = bnx2x_check_mac_del;
mac_obj->check_add = bnx2x_check_mac_add;
mac_obj->check_move = bnx2x_check_move_always_err;
mac_obj->ramrod_cmd = RAMROD_CMD_ID_ETH_SET_MAC;
/* Exe Queue */
bnx2x_exe_queue_init(bp,
&mac_obj->exe_queue, 1, qable_obj,
bnx2x_validate_vlan_mac,
bnx2x_remove_vlan_mac,
bnx2x_optimize_vlan_mac,
bnx2x_execute_vlan_mac,
bnx2x_exeq_get_mac);
} else {
mac_obj->set_one_rule = bnx2x_set_one_mac_e2;
mac_obj->check_del = bnx2x_check_mac_del;
mac_obj->check_add = bnx2x_check_mac_add;
mac_obj->check_move = bnx2x_check_move;
mac_obj->ramrod_cmd =
RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES;
mac_obj->get_n_elements = bnx2x_get_n_elements;
/* Exe Queue */
bnx2x_exe_queue_init(bp,
&mac_obj->exe_queue, CLASSIFY_RULES_COUNT,
qable_obj, bnx2x_validate_vlan_mac,
bnx2x_remove_vlan_mac,
bnx2x_optimize_vlan_mac,
bnx2x_execute_vlan_mac,
bnx2x_exeq_get_mac);
}
}
void bnx2x_init_vlan_obj(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *vlan_obj,
u8 cl_id, u32 cid, u8 func_id, void *rdata,
dma_addr_t rdata_mapping, int state,
unsigned long *pstate, bnx2x_obj_type type,
struct bnx2x_credit_pool_obj *vlans_pool)
{
union bnx2x_qable_obj *qable_obj = (union bnx2x_qable_obj *)vlan_obj;
bnx2x_init_vlan_mac_common(vlan_obj, cl_id, cid, func_id, rdata,
rdata_mapping, state, pstate, type, NULL,
vlans_pool);
vlan_obj->get_credit = bnx2x_get_credit_vlan;
vlan_obj->put_credit = bnx2x_put_credit_vlan;
vlan_obj->get_cam_offset = bnx2x_get_cam_offset_vlan;
vlan_obj->put_cam_offset = bnx2x_put_cam_offset_vlan;
if (CHIP_IS_E1x(bp)) {
BNX2X_ERR("Do not support chips others than E2 and newer\n");
BUG();
} else {
vlan_obj->set_one_rule = bnx2x_set_one_vlan_e2;
vlan_obj->check_del = bnx2x_check_vlan_del;
vlan_obj->check_add = bnx2x_check_vlan_add;
vlan_obj->check_move = bnx2x_check_move;
vlan_obj->ramrod_cmd =
RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES;
vlan_obj->get_n_elements = bnx2x_get_n_elements;
/* Exe Queue */
bnx2x_exe_queue_init(bp,
&vlan_obj->exe_queue, CLASSIFY_RULES_COUNT,
qable_obj, bnx2x_validate_vlan_mac,
bnx2x_remove_vlan_mac,
bnx2x_optimize_vlan_mac,
bnx2x_execute_vlan_mac,
bnx2x_exeq_get_vlan);
}
}
/* RX_MODE verbs: DROP_ALL/ACCEPT_ALL/ACCEPT_ALL_MULTI/ACCEPT_ALL_VLAN/NORMAL */
static inline void __storm_memset_mac_filters(struct bnx2x *bp,
struct tstorm_eth_mac_filter_config *mac_filters,
u16 pf_id)
{
size_t size = sizeof(struct tstorm_eth_mac_filter_config);
u32 addr = BAR_TSTRORM_INTMEM +
TSTORM_MAC_FILTER_CONFIG_OFFSET(pf_id);
__storm_memset_struct(bp, addr, size, (u32 *)mac_filters);
}
static int bnx2x_set_rx_mode_e1x(struct bnx2x *bp,
struct bnx2x_rx_mode_ramrod_params *p)
{
/* update the bp MAC filter structure */
u32 mask = (1 << p->cl_id);
struct tstorm_eth_mac_filter_config *mac_filters =
(struct tstorm_eth_mac_filter_config *)p->rdata;
/* initial setting is drop-all */
u8 drop_all_ucast = 1, drop_all_mcast = 1;
u8 accp_all_ucast = 0, accp_all_bcast = 0, accp_all_mcast = 0;
u8 unmatched_unicast = 0;
/* In e1x there we only take into account rx accept flag since tx switching
* isn't enabled. */
if (test_bit(BNX2X_ACCEPT_UNICAST, &p->rx_accept_flags))
/* accept matched ucast */
drop_all_ucast = 0;
if (test_bit(BNX2X_ACCEPT_MULTICAST, &p->rx_accept_flags))
/* accept matched mcast */
drop_all_mcast = 0;
if (test_bit(BNX2X_ACCEPT_ALL_UNICAST, &p->rx_accept_flags)) {
/* accept all mcast */
drop_all_ucast = 0;
accp_all_ucast = 1;
}
if (test_bit(BNX2X_ACCEPT_ALL_MULTICAST, &p->rx_accept_flags)) {
/* accept all mcast */
drop_all_mcast = 0;
accp_all_mcast = 1;
}
if (test_bit(BNX2X_ACCEPT_BROADCAST, &p->rx_accept_flags))
/* accept (all) bcast */
accp_all_bcast = 1;
if (test_bit(BNX2X_ACCEPT_UNMATCHED, &p->rx_accept_flags))
/* accept unmatched unicasts */
unmatched_unicast = 1;
mac_filters->ucast_drop_all = drop_all_ucast ?
mac_filters->ucast_drop_all | mask :
mac_filters->ucast_drop_all & ~mask;
mac_filters->mcast_drop_all = drop_all_mcast ?
mac_filters->mcast_drop_all | mask :
mac_filters->mcast_drop_all & ~mask;
mac_filters->ucast_accept_all = accp_all_ucast ?
mac_filters->ucast_accept_all | mask :
mac_filters->ucast_accept_all & ~mask;
mac_filters->mcast_accept_all = accp_all_mcast ?
mac_filters->mcast_accept_all | mask :
mac_filters->mcast_accept_all & ~mask;
mac_filters->bcast_accept_all = accp_all_bcast ?
mac_filters->bcast_accept_all | mask :
mac_filters->bcast_accept_all & ~mask;
mac_filters->unmatched_unicast = unmatched_unicast ?
mac_filters->unmatched_unicast | mask :
mac_filters->unmatched_unicast & ~mask;
DP(BNX2X_MSG_SP, "drop_ucast 0x%x\ndrop_mcast 0x%x\n accp_ucast 0x%x\n"
"accp_mcast 0x%x\naccp_bcast 0x%x\n",
mac_filters->ucast_drop_all, mac_filters->mcast_drop_all,
mac_filters->ucast_accept_all, mac_filters->mcast_accept_all,
mac_filters->bcast_accept_all);
/* write the MAC filter structure*/
__storm_memset_mac_filters(bp, mac_filters, p->func_id);
/* The operation is completed */
clear_bit(p->state, p->pstate);
smp_mb__after_atomic();
return 0;
}
/* Setup ramrod data */
static inline void bnx2x_rx_mode_set_rdata_hdr_e2(u32 cid,
struct eth_classify_header *hdr,
u8 rule_cnt)
{
hdr->echo = cpu_to_le32(cid);
hdr->rule_cnt = rule_cnt;
}
static inline void bnx2x_rx_mode_set_cmd_state_e2(struct bnx2x *bp,
unsigned long *accept_flags,
struct eth_filter_rules_cmd *cmd,
bool clear_accept_all)
{
u16 state;
/* start with 'drop-all' */
state = ETH_FILTER_RULES_CMD_UCAST_DROP_ALL |
ETH_FILTER_RULES_CMD_MCAST_DROP_ALL;
if (test_bit(BNX2X_ACCEPT_UNICAST, accept_flags))
state &= ~ETH_FILTER_RULES_CMD_UCAST_DROP_ALL;
if (test_bit(BNX2X_ACCEPT_MULTICAST, accept_flags))
state &= ~ETH_FILTER_RULES_CMD_MCAST_DROP_ALL;
if (test_bit(BNX2X_ACCEPT_ALL_UNICAST, accept_flags)) {
state &= ~ETH_FILTER_RULES_CMD_UCAST_DROP_ALL;
state |= ETH_FILTER_RULES_CMD_UCAST_ACCEPT_ALL;
}
if (test_bit(BNX2X_ACCEPT_ALL_MULTICAST, accept_flags)) {
state |= ETH_FILTER_RULES_CMD_MCAST_ACCEPT_ALL;
state &= ~ETH_FILTER_RULES_CMD_MCAST_DROP_ALL;
}
if (test_bit(BNX2X_ACCEPT_BROADCAST, accept_flags))
state |= ETH_FILTER_RULES_CMD_BCAST_ACCEPT_ALL;
if (test_bit(BNX2X_ACCEPT_UNMATCHED, accept_flags)) {
state &= ~ETH_FILTER_RULES_CMD_UCAST_DROP_ALL;
state |= ETH_FILTER_RULES_CMD_UCAST_ACCEPT_UNMATCHED;
}
if (test_bit(BNX2X_ACCEPT_ANY_VLAN, accept_flags))
state |= ETH_FILTER_RULES_CMD_ACCEPT_ANY_VLAN;
/* Clear ACCEPT_ALL_XXX flags for FCoE L2 Queue */
if (clear_accept_all) {
state &= ~ETH_FILTER_RULES_CMD_MCAST_ACCEPT_ALL;
state &= ~ETH_FILTER_RULES_CMD_BCAST_ACCEPT_ALL;
state &= ~ETH_FILTER_RULES_CMD_UCAST_ACCEPT_ALL;
state &= ~ETH_FILTER_RULES_CMD_UCAST_ACCEPT_UNMATCHED;
}
cmd->state = cpu_to_le16(state);
}
static int bnx2x_set_rx_mode_e2(struct bnx2x *bp,
struct bnx2x_rx_mode_ramrod_params *p)
{
struct eth_filter_rules_ramrod_data *data = p->rdata;
int rc;
u8 rule_idx = 0;
/* Reset the ramrod data buffer */
memset(data, 0, sizeof(*data));
/* Setup ramrod data */
/* Tx (internal switching) */
if (test_bit(RAMROD_TX, &p->ramrod_flags)) {
data->rules[rule_idx].client_id = p->cl_id;
data->rules[rule_idx].func_id = p->func_id;
data->rules[rule_idx].cmd_general_data =
ETH_FILTER_RULES_CMD_TX_CMD;
bnx2x_rx_mode_set_cmd_state_e2(bp, &p->tx_accept_flags,
&(data->rules[rule_idx++]),
false);
}
/* Rx */
if (test_bit(RAMROD_RX, &p->ramrod_flags)) {
data->rules[rule_idx].client_id = p->cl_id;
data->rules[rule_idx].func_id = p->func_id;
data->rules[rule_idx].cmd_general_data =
ETH_FILTER_RULES_CMD_RX_CMD;
bnx2x_rx_mode_set_cmd_state_e2(bp, &p->rx_accept_flags,
&(data->rules[rule_idx++]),
false);
}
/* If FCoE Queue configuration has been requested configure the Rx and
* internal switching modes for this queue in separate rules.
*
* FCoE queue shell never be set to ACCEPT_ALL packets of any sort:
* MCAST_ALL, UCAST_ALL, BCAST_ALL and UNMATCHED.
*/
if (test_bit(BNX2X_RX_MODE_FCOE_ETH, &p->rx_mode_flags)) {
/* Tx (internal switching) */
if (test_bit(RAMROD_TX, &p->ramrod_flags)) {
data->rules[rule_idx].client_id = bnx2x_fcoe(bp, cl_id);
data->rules[rule_idx].func_id = p->func_id;
data->rules[rule_idx].cmd_general_data =
ETH_FILTER_RULES_CMD_TX_CMD;
bnx2x_rx_mode_set_cmd_state_e2(bp, &p->tx_accept_flags,
&(data->rules[rule_idx]),
true);
rule_idx++;
}
/* Rx */
if (test_bit(RAMROD_RX, &p->ramrod_flags)) {
data->rules[rule_idx].client_id = bnx2x_fcoe(bp, cl_id);
data->rules[rule_idx].func_id = p->func_id;
data->rules[rule_idx].cmd_general_data =
ETH_FILTER_RULES_CMD_RX_CMD;
bnx2x_rx_mode_set_cmd_state_e2(bp, &p->rx_accept_flags,
&(data->rules[rule_idx]),
true);
rule_idx++;
}
}
/* Set the ramrod header (most importantly - number of rules to
* configure).
*/
bnx2x_rx_mode_set_rdata_hdr_e2(p->cid, &data->header, rule_idx);
DP(BNX2X_MSG_SP, "About to configure %d rules, rx_accept_flags 0x%lx, tx_accept_flags 0x%lx\n",
data->header.rule_cnt, p->rx_accept_flags,
p->tx_accept_flags);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
/* Send a ramrod */
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_FILTER_RULES, p->cid,
U64_HI(p->rdata_mapping),
U64_LO(p->rdata_mapping),
ETH_CONNECTION_TYPE);
if (rc)
return rc;
/* Ramrod completion is pending */
return 1;
}
static int bnx2x_wait_rx_mode_comp_e2(struct bnx2x *bp,
struct bnx2x_rx_mode_ramrod_params *p)
{
return bnx2x_state_wait(bp, p->state, p->pstate);
}
static int bnx2x_empty_rx_mode_wait(struct bnx2x *bp,
struct bnx2x_rx_mode_ramrod_params *p)
{
/* Do nothing */
return 0;
}
int bnx2x_config_rx_mode(struct bnx2x *bp,
struct bnx2x_rx_mode_ramrod_params *p)
{
int rc;
/* Configure the new classification in the chip */
rc = p->rx_mode_obj->config_rx_mode(bp, p);
if (rc < 0)
return rc;
/* Wait for a ramrod completion if was requested */
if (test_bit(RAMROD_COMP_WAIT, &p->ramrod_flags)) {
rc = p->rx_mode_obj->wait_comp(bp, p);
if (rc)
return rc;
}
return rc;
}
void bnx2x_init_rx_mode_obj(struct bnx2x *bp,
struct bnx2x_rx_mode_obj *o)
{
if (CHIP_IS_E1x(bp)) {
o->wait_comp = bnx2x_empty_rx_mode_wait;
o->config_rx_mode = bnx2x_set_rx_mode_e1x;
} else {
o->wait_comp = bnx2x_wait_rx_mode_comp_e2;
o->config_rx_mode = bnx2x_set_rx_mode_e2;
}
}
/********************* Multicast verbs: SET, CLEAR ****************************/
static inline u8 bnx2x_mcast_bin_from_mac(u8 *mac)
{
return (crc32c_le(0, mac, ETH_ALEN) >> 24) & 0xff;
}
struct bnx2x_mcast_mac_elem {
struct list_head link;
u8 mac[ETH_ALEN];
u8 pad[2]; /* For a natural alignment of the following buffer */
};
struct bnx2x_pending_mcast_cmd {
struct list_head link;
int type; /* BNX2X_MCAST_CMD_X */
union {
struct list_head macs_head;
u32 macs_num; /* Needed for DEL command */
int next_bin; /* Needed for RESTORE flow with aprox match */
} data;
bool done; /* set to true, when the command has been handled,
* practically used in 57712 handling only, where one pending
* command may be handled in a few operations. As long as for
* other chips every operation handling is completed in a
* single ramrod, there is no need to utilize this field.
*/
};
static int bnx2x_mcast_wait(struct bnx2x *bp,
struct bnx2x_mcast_obj *o)
{
if (bnx2x_state_wait(bp, o->sched_state, o->raw.pstate) ||
o->raw.wait_comp(bp, &o->raw))
return -EBUSY;
return 0;
}
static int bnx2x_mcast_enqueue_cmd(struct bnx2x *bp,
struct bnx2x_mcast_obj *o,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
int total_sz;
struct bnx2x_pending_mcast_cmd *new_cmd;
struct bnx2x_mcast_mac_elem *cur_mac = NULL;
struct bnx2x_mcast_list_elem *pos;
int macs_list_len = ((cmd == BNX2X_MCAST_CMD_ADD) ?
p->mcast_list_len : 0);
/* If the command is empty ("handle pending commands only"), break */
if (!p->mcast_list_len)
return 0;
total_sz = sizeof(*new_cmd) +
macs_list_len * sizeof(struct bnx2x_mcast_mac_elem);
/* Add mcast is called under spin_lock, thus calling with GFP_ATOMIC */
new_cmd = kzalloc(total_sz, GFP_ATOMIC);
if (!new_cmd)
return -ENOMEM;
DP(BNX2X_MSG_SP, "About to enqueue a new %d command. macs_list_len=%d\n",
cmd, macs_list_len);
INIT_LIST_HEAD(&new_cmd->data.macs_head);
new_cmd->type = cmd;
new_cmd->done = false;
switch (cmd) {
case BNX2X_MCAST_CMD_ADD:
cur_mac = (struct bnx2x_mcast_mac_elem *)
((u8 *)new_cmd + sizeof(*new_cmd));
/* Push the MACs of the current command into the pending command
* MACs list: FIFO
*/
list_for_each_entry(pos, &p->mcast_list, link) {
memcpy(cur_mac->mac, pos->mac, ETH_ALEN);
list_add_tail(&cur_mac->link, &new_cmd->data.macs_head);
cur_mac++;
}
break;
case BNX2X_MCAST_CMD_DEL:
new_cmd->data.macs_num = p->mcast_list_len;
break;
case BNX2X_MCAST_CMD_RESTORE:
new_cmd->data.next_bin = 0;
break;
default:
kfree(new_cmd);
BNX2X_ERR("Unknown command: %d\n", cmd);
return -EINVAL;
}
/* Push the new pending command to the tail of the pending list: FIFO */
list_add_tail(&new_cmd->link, &o->pending_cmds_head);
o->set_sched(o);
return 1;
}
/**
* bnx2x_mcast_get_next_bin - get the next set bin (index)
*
* @o:
* @last: index to start looking from (including)
*
* returns the next found (set) bin or a negative value if none is found.
*/
static inline int bnx2x_mcast_get_next_bin(struct bnx2x_mcast_obj *o, int last)
{
int i, j, inner_start = last % BIT_VEC64_ELEM_SZ;
for (i = last / BIT_VEC64_ELEM_SZ; i < BNX2X_MCAST_VEC_SZ; i++) {
if (o->registry.aprox_match.vec[i])
for (j = inner_start; j < BIT_VEC64_ELEM_SZ; j++) {
int cur_bit = j + BIT_VEC64_ELEM_SZ * i;
if (BIT_VEC64_TEST_BIT(o->registry.aprox_match.
vec, cur_bit)) {
return cur_bit;
}
}
inner_start = 0;
}
/* None found */
return -1;
}
/**
* bnx2x_mcast_clear_first_bin - find the first set bin and clear it
*
* @o:
*
* returns the index of the found bin or -1 if none is found
*/
static inline int bnx2x_mcast_clear_first_bin(struct bnx2x_mcast_obj *o)
{
int cur_bit = bnx2x_mcast_get_next_bin(o, 0);
if (cur_bit >= 0)
BIT_VEC64_CLEAR_BIT(o->registry.aprox_match.vec, cur_bit);
return cur_bit;
}
static inline u8 bnx2x_mcast_get_rx_tx_flag(struct bnx2x_mcast_obj *o)
{
struct bnx2x_raw_obj *raw = &o->raw;
u8 rx_tx_flag = 0;
if ((raw->obj_type == BNX2X_OBJ_TYPE_TX) ||
(raw->obj_type == BNX2X_OBJ_TYPE_RX_TX))
rx_tx_flag |= ETH_MULTICAST_RULES_CMD_TX_CMD;
if ((raw->obj_type == BNX2X_OBJ_TYPE_RX) ||
(raw->obj_type == BNX2X_OBJ_TYPE_RX_TX))
rx_tx_flag |= ETH_MULTICAST_RULES_CMD_RX_CMD;
return rx_tx_flag;
}
static void bnx2x_mcast_set_one_rule_e2(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, int idx,
union bnx2x_mcast_config_data *cfg_data,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_raw_obj *r = &o->raw;
struct eth_multicast_rules_ramrod_data *data =
(struct eth_multicast_rules_ramrod_data *)(r->rdata);
u8 func_id = r->func_id;
u8 rx_tx_add_flag = bnx2x_mcast_get_rx_tx_flag(o);
int bin;
if ((cmd == BNX2X_MCAST_CMD_ADD) || (cmd == BNX2X_MCAST_CMD_RESTORE))
rx_tx_add_flag |= ETH_MULTICAST_RULES_CMD_IS_ADD;
data->rules[idx].cmd_general_data |= rx_tx_add_flag;
/* Get a bin and update a bins' vector */
switch (cmd) {
case BNX2X_MCAST_CMD_ADD:
bin = bnx2x_mcast_bin_from_mac(cfg_data->mac);
BIT_VEC64_SET_BIT(o->registry.aprox_match.vec, bin);
break;
case BNX2X_MCAST_CMD_DEL:
/* If there were no more bins to clear
* (bnx2x_mcast_clear_first_bin() returns -1) then we would
* clear any (0xff) bin.
* See bnx2x_mcast_validate_e2() for explanation when it may
* happen.
*/
bin = bnx2x_mcast_clear_first_bin(o);
break;
case BNX2X_MCAST_CMD_RESTORE:
bin = cfg_data->bin;
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd);
return;
}
DP(BNX2X_MSG_SP, "%s bin %d\n",
((rx_tx_add_flag & ETH_MULTICAST_RULES_CMD_IS_ADD) ?
"Setting" : "Clearing"), bin);
data->rules[idx].bin_id = (u8)bin;
data->rules[idx].func_id = func_id;
data->rules[idx].engine_id = o->engine_id;
}
/**
* bnx2x_mcast_handle_restore_cmd_e2 - restore configuration from the registry
*
* @bp: device handle
* @o:
* @start_bin: index in the registry to start from (including)
* @rdata_idx: index in the ramrod data to start from
*
* returns last handled bin index or -1 if all bins have been handled
*/
static inline int bnx2x_mcast_handle_restore_cmd_e2(
struct bnx2x *bp, struct bnx2x_mcast_obj *o , int start_bin,
int *rdata_idx)
{
int cur_bin, cnt = *rdata_idx;
union bnx2x_mcast_config_data cfg_data = {NULL};
/* go through the registry and configure the bins from it */
for (cur_bin = bnx2x_mcast_get_next_bin(o, start_bin); cur_bin >= 0;
cur_bin = bnx2x_mcast_get_next_bin(o, cur_bin + 1)) {
cfg_data.bin = (u8)cur_bin;
o->set_one_rule(bp, o, cnt, &cfg_data,
BNX2X_MCAST_CMD_RESTORE);
cnt++;
DP(BNX2X_MSG_SP, "About to configure a bin %d\n", cur_bin);
/* Break if we reached the maximum number
* of rules.
*/
if (cnt >= o->max_cmd_len)
break;
}
*rdata_idx = cnt;
return cur_bin;
}
static inline void bnx2x_mcast_hdl_pending_add_e2(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_pending_mcast_cmd *cmd_pos,
int *line_idx)
{
struct bnx2x_mcast_mac_elem *pmac_pos, *pmac_pos_n;
int cnt = *line_idx;
union bnx2x_mcast_config_data cfg_data = {NULL};
list_for_each_entry_safe(pmac_pos, pmac_pos_n, &cmd_pos->data.macs_head,
link) {
cfg_data.mac = &pmac_pos->mac[0];
o->set_one_rule(bp, o, cnt, &cfg_data, cmd_pos->type);
cnt++;
DP(BNX2X_MSG_SP, "About to configure %pM mcast MAC\n",
pmac_pos->mac);
list_del(&pmac_pos->link);
/* Break if we reached the maximum number
* of rules.
*/
if (cnt >= o->max_cmd_len)
break;
}
*line_idx = cnt;
/* if no more MACs to configure - we are done */
if (list_empty(&cmd_pos->data.macs_head))
cmd_pos->done = true;
}
static inline void bnx2x_mcast_hdl_pending_del_e2(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_pending_mcast_cmd *cmd_pos,
int *line_idx)
{
int cnt = *line_idx;
while (cmd_pos->data.macs_num) {
o->set_one_rule(bp, o, cnt, NULL, cmd_pos->type);
cnt++;
cmd_pos->data.macs_num--;
DP(BNX2X_MSG_SP, "Deleting MAC. %d left,cnt is %d\n",
cmd_pos->data.macs_num, cnt);
/* Break if we reached the maximum
* number of rules.
*/
if (cnt >= o->max_cmd_len)
break;
}
*line_idx = cnt;
/* If we cleared all bins - we are done */
if (!cmd_pos->data.macs_num)
cmd_pos->done = true;
}
static inline void bnx2x_mcast_hdl_pending_restore_e2(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_pending_mcast_cmd *cmd_pos,
int *line_idx)
{
cmd_pos->data.next_bin = o->hdl_restore(bp, o, cmd_pos->data.next_bin,
line_idx);
if (cmd_pos->data.next_bin < 0)
/* If o->set_restore returned -1 we are done */
cmd_pos->done = true;
else
/* Start from the next bin next time */
cmd_pos->data.next_bin++;
}
static inline int bnx2x_mcast_handle_pending_cmds_e2(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p)
{
struct bnx2x_pending_mcast_cmd *cmd_pos, *cmd_pos_n;
int cnt = 0;
struct bnx2x_mcast_obj *o = p->mcast_obj;
list_for_each_entry_safe(cmd_pos, cmd_pos_n, &o->pending_cmds_head,
link) {
switch (cmd_pos->type) {
case BNX2X_MCAST_CMD_ADD:
bnx2x_mcast_hdl_pending_add_e2(bp, o, cmd_pos, &cnt);
break;
case BNX2X_MCAST_CMD_DEL:
bnx2x_mcast_hdl_pending_del_e2(bp, o, cmd_pos, &cnt);
break;
case BNX2X_MCAST_CMD_RESTORE:
bnx2x_mcast_hdl_pending_restore_e2(bp, o, cmd_pos,
&cnt);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd_pos->type);
return -EINVAL;
}
/* If the command has been completed - remove it from the list
* and free the memory
*/
if (cmd_pos->done) {
list_del(&cmd_pos->link);
kfree(cmd_pos);
}
/* Break if we reached the maximum number of rules */
if (cnt >= o->max_cmd_len)
break;
}
return cnt;
}
static inline void bnx2x_mcast_hdl_add(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_mcast_ramrod_params *p,
int *line_idx)
{
struct bnx2x_mcast_list_elem *mlist_pos;
union bnx2x_mcast_config_data cfg_data = {NULL};
int cnt = *line_idx;
list_for_each_entry(mlist_pos, &p->mcast_list, link) {
cfg_data.mac = mlist_pos->mac;
o->set_one_rule(bp, o, cnt, &cfg_data, BNX2X_MCAST_CMD_ADD);
cnt++;
DP(BNX2X_MSG_SP, "About to configure %pM mcast MAC\n",
mlist_pos->mac);
}
*line_idx = cnt;
}
static inline void bnx2x_mcast_hdl_del(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_mcast_ramrod_params *p,
int *line_idx)
{
int cnt = *line_idx, i;
for (i = 0; i < p->mcast_list_len; i++) {
o->set_one_rule(bp, o, cnt, NULL, BNX2X_MCAST_CMD_DEL);
cnt++;
DP(BNX2X_MSG_SP, "Deleting MAC. %d left\n",
p->mcast_list_len - i - 1);
}
*line_idx = cnt;
}
/**
* bnx2x_mcast_handle_current_cmd -
*
* @bp: device handle
* @p:
* @cmd:
* @start_cnt: first line in the ramrod data that may be used
*
* This function is called iff there is enough place for the current command in
* the ramrod data.
* Returns number of lines filled in the ramrod data in total.
*/
static inline int bnx2x_mcast_handle_current_cmd(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd,
int start_cnt)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
int cnt = start_cnt;
DP(BNX2X_MSG_SP, "p->mcast_list_len=%d\n", p->mcast_list_len);
switch (cmd) {
case BNX2X_MCAST_CMD_ADD:
bnx2x_mcast_hdl_add(bp, o, p, &cnt);
break;
case BNX2X_MCAST_CMD_DEL:
bnx2x_mcast_hdl_del(bp, o, p, &cnt);
break;
case BNX2X_MCAST_CMD_RESTORE:
o->hdl_restore(bp, o, 0, &cnt);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd);
return -EINVAL;
}
/* The current command has been handled */
p->mcast_list_len = 0;
return cnt;
}
static int bnx2x_mcast_validate_e2(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
int reg_sz = o->get_registry_size(o);
switch (cmd) {
/* DEL command deletes all currently configured MACs */
case BNX2X_MCAST_CMD_DEL:
o->set_registry_size(o, 0);
/* Don't break */
/* RESTORE command will restore the entire multicast configuration */
case BNX2X_MCAST_CMD_RESTORE:
/* Here we set the approximate amount of work to do, which in
* fact may be only less as some MACs in postponed ADD
* command(s) scheduled before this command may fall into
* the same bin and the actual number of bins set in the
* registry would be less than we estimated here. See
* bnx2x_mcast_set_one_rule_e2() for further details.
*/
p->mcast_list_len = reg_sz;
break;
case BNX2X_MCAST_CMD_ADD:
case BNX2X_MCAST_CMD_CONT:
/* Here we assume that all new MACs will fall into new bins.
* However we will correct the real registry size after we
* handle all pending commands.
*/
o->set_registry_size(o, reg_sz + p->mcast_list_len);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd);
return -EINVAL;
}
/* Increase the total number of MACs pending to be configured */
o->total_pending_num += p->mcast_list_len;
return 0;
}
static void bnx2x_mcast_revert_e2(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
int old_num_bins)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
o->set_registry_size(o, old_num_bins);
o->total_pending_num -= p->mcast_list_len;
}
/**
* bnx2x_mcast_set_rdata_hdr_e2 - sets a header values
*
* @bp: device handle
* @p:
* @len: number of rules to handle
*/
static inline void bnx2x_mcast_set_rdata_hdr_e2(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
u8 len)
{
struct bnx2x_raw_obj *r = &p->mcast_obj->raw;
struct eth_multicast_rules_ramrod_data *data =
(struct eth_multicast_rules_ramrod_data *)(r->rdata);
data->header.echo = cpu_to_le32((r->cid & BNX2X_SWCID_MASK) |
(BNX2X_FILTER_MCAST_PENDING <<
BNX2X_SWCID_SHIFT));
data->header.rule_cnt = len;
}
/**
* bnx2x_mcast_refresh_registry_e2 - recalculate the actual number of set bins
*
* @bp: device handle
* @o:
*
* Recalculate the actual number of set bins in the registry using Brian
* Kernighan's algorithm: it's execution complexity is as a number of set bins.
*
* returns 0 for the compliance with bnx2x_mcast_refresh_registry_e1().
*/
static inline int bnx2x_mcast_refresh_registry_e2(struct bnx2x *bp,
struct bnx2x_mcast_obj *o)
{
int i, cnt = 0;
u64 elem;
for (i = 0; i < BNX2X_MCAST_VEC_SZ; i++) {
elem = o->registry.aprox_match.vec[i];
for (; elem; cnt++)
elem &= elem - 1;
}
o->set_registry_size(o, cnt);
return 0;
}
static int bnx2x_mcast_setup_e2(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_raw_obj *raw = &p->mcast_obj->raw;
struct bnx2x_mcast_obj *o = p->mcast_obj;
struct eth_multicast_rules_ramrod_data *data =
(struct eth_multicast_rules_ramrod_data *)(raw->rdata);
int cnt = 0, rc;
/* Reset the ramrod data buffer */
memset(data, 0, sizeof(*data));
cnt = bnx2x_mcast_handle_pending_cmds_e2(bp, p);
/* If there are no more pending commands - clear SCHEDULED state */
if (list_empty(&o->pending_cmds_head))
o->clear_sched(o);
/* The below may be true iff there was enough room in ramrod
* data for all pending commands and for the current
* command. Otherwise the current command would have been added
* to the pending commands and p->mcast_list_len would have been
* zeroed.
*/
if (p->mcast_list_len > 0)
cnt = bnx2x_mcast_handle_current_cmd(bp, p, cmd, cnt);
/* We've pulled out some MACs - update the total number of
* outstanding.
*/
o->total_pending_num -= cnt;
/* send a ramrod */
WARN_ON(o->total_pending_num < 0);
WARN_ON(cnt > o->max_cmd_len);
bnx2x_mcast_set_rdata_hdr_e2(bp, p, (u8)cnt);
/* Update a registry size if there are no more pending operations.
*
* We don't want to change the value of the registry size if there are
* pending operations because we want it to always be equal to the
* exact or the approximate number (see bnx2x_mcast_validate_e2()) of
* set bins after the last requested operation in order to properly
* evaluate the size of the next DEL/RESTORE operation.
*
* Note that we update the registry itself during command(s) handling
* - see bnx2x_mcast_set_one_rule_e2(). That's because for 57712 we
* aggregate multiple commands (ADD/DEL/RESTORE) into one ramrod but
* with a limited amount of update commands (per MAC/bin) and we don't
* know in this scope what the actual state of bins configuration is
* going to be after this ramrod.
*/
if (!o->total_pending_num)
bnx2x_mcast_refresh_registry_e2(bp, o);
/* If CLEAR_ONLY was requested - don't send a ramrod and clear
* RAMROD_PENDING status immediately.
*/
if (test_bit(RAMROD_DRV_CLR_ONLY, &p->ramrod_flags)) {
raw->clear_pending(raw);
return 0;
} else {
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
/* Send a ramrod */
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_MULTICAST_RULES,
raw->cid, U64_HI(raw->rdata_mapping),
U64_LO(raw->rdata_mapping),
ETH_CONNECTION_TYPE);
if (rc)
return rc;
/* Ramrod completion is pending */
return 1;
}
}
static int bnx2x_mcast_validate_e1h(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
/* Mark, that there is a work to do */
if ((cmd == BNX2X_MCAST_CMD_DEL) || (cmd == BNX2X_MCAST_CMD_RESTORE))
p->mcast_list_len = 1;
return 0;
}
static void bnx2x_mcast_revert_e1h(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
int old_num_bins)
{
/* Do nothing */
}
#define BNX2X_57711_SET_MC_FILTER(filter, bit) \
do { \
(filter)[(bit) >> 5] |= (1 << ((bit) & 0x1f)); \
} while (0)
static inline void bnx2x_mcast_hdl_add_e1h(struct bnx2x *bp,
struct bnx2x_mcast_obj *o,
struct bnx2x_mcast_ramrod_params *p,
u32 *mc_filter)
{
struct bnx2x_mcast_list_elem *mlist_pos;
int bit;
list_for_each_entry(mlist_pos, &p->mcast_list, link) {
bit = bnx2x_mcast_bin_from_mac(mlist_pos->mac);
BNX2X_57711_SET_MC_FILTER(mc_filter, bit);
DP(BNX2X_MSG_SP, "About to configure %pM mcast MAC, bin %d\n",
mlist_pos->mac, bit);
/* bookkeeping... */
BIT_VEC64_SET_BIT(o->registry.aprox_match.vec,
bit);
}
}
static inline void bnx2x_mcast_hdl_restore_e1h(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, struct bnx2x_mcast_ramrod_params *p,
u32 *mc_filter)
{
int bit;
for (bit = bnx2x_mcast_get_next_bin(o, 0);
bit >= 0;
bit = bnx2x_mcast_get_next_bin(o, bit + 1)) {
BNX2X_57711_SET_MC_FILTER(mc_filter, bit);
DP(BNX2X_MSG_SP, "About to set bin %d\n", bit);
}
}
/* On 57711 we write the multicast MACs' approximate match
* table by directly into the TSTORM's internal RAM. So we don't
* really need to handle any tricks to make it work.
*/
static int bnx2x_mcast_setup_e1h(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
int i;
struct bnx2x_mcast_obj *o = p->mcast_obj;
struct bnx2x_raw_obj *r = &o->raw;
/* If CLEAR_ONLY has been requested - clear the registry
* and clear a pending bit.
*/
if (!test_bit(RAMROD_DRV_CLR_ONLY, &p->ramrod_flags)) {
u32 mc_filter[MC_HASH_SIZE] = {0};
/* Set the multicast filter bits before writing it into
* the internal memory.
*/
switch (cmd) {
case BNX2X_MCAST_CMD_ADD:
bnx2x_mcast_hdl_add_e1h(bp, o, p, mc_filter);
break;
case BNX2X_MCAST_CMD_DEL:
DP(BNX2X_MSG_SP,
"Invalidating multicast MACs configuration\n");
/* clear the registry */
memset(o->registry.aprox_match.vec, 0,
sizeof(o->registry.aprox_match.vec));
break;
case BNX2X_MCAST_CMD_RESTORE:
bnx2x_mcast_hdl_restore_e1h(bp, o, p, mc_filter);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd);
return -EINVAL;
}
/* Set the mcast filter in the internal memory */
for (i = 0; i < MC_HASH_SIZE; i++)
REG_WR(bp, MC_HASH_OFFSET(bp, i), mc_filter[i]);
} else
/* clear the registry */
memset(o->registry.aprox_match.vec, 0,
sizeof(o->registry.aprox_match.vec));
/* We are done */
r->clear_pending(r);
return 0;
}
static int bnx2x_mcast_validate_e1(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
int reg_sz = o->get_registry_size(o);
switch (cmd) {
/* DEL command deletes all currently configured MACs */
case BNX2X_MCAST_CMD_DEL:
o->set_registry_size(o, 0);
/* Don't break */
/* RESTORE command will restore the entire multicast configuration */
case BNX2X_MCAST_CMD_RESTORE:
p->mcast_list_len = reg_sz;
DP(BNX2X_MSG_SP, "Command %d, p->mcast_list_len=%d\n",
cmd, p->mcast_list_len);
break;
case BNX2X_MCAST_CMD_ADD:
case BNX2X_MCAST_CMD_CONT:
/* Multicast MACs on 57710 are configured as unicast MACs and
* there is only a limited number of CAM entries for that
* matter.
*/
if (p->mcast_list_len > o->max_cmd_len) {
BNX2X_ERR("Can't configure more than %d multicast MACs on 57710\n",
o->max_cmd_len);
return -EINVAL;
}
/* Every configured MAC should be cleared if DEL command is
* called. Only the last ADD command is relevant as long as
* every ADD commands overrides the previous configuration.
*/
DP(BNX2X_MSG_SP, "p->mcast_list_len=%d\n", p->mcast_list_len);
if (p->mcast_list_len > 0)
o->set_registry_size(o, p->mcast_list_len);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd);
return -EINVAL;
}
/* We want to ensure that commands are executed one by one for 57710.
* Therefore each none-empty command will consume o->max_cmd_len.
*/
if (p->mcast_list_len)
o->total_pending_num += o->max_cmd_len;
return 0;
}
static void bnx2x_mcast_revert_e1(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
int old_num_macs)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
o->set_registry_size(o, old_num_macs);
/* If current command hasn't been handled yet and we are
* here means that it's meant to be dropped and we have to
* update the number of outstanding MACs accordingly.
*/
if (p->mcast_list_len)
o->total_pending_num -= o->max_cmd_len;
}
static void bnx2x_mcast_set_one_rule_e1(struct bnx2x *bp,
struct bnx2x_mcast_obj *o, int idx,
union bnx2x_mcast_config_data *cfg_data,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_raw_obj *r = &o->raw;
struct mac_configuration_cmd *data =
(struct mac_configuration_cmd *)(r->rdata);
/* copy mac */
if ((cmd == BNX2X_MCAST_CMD_ADD) || (cmd == BNX2X_MCAST_CMD_RESTORE)) {
bnx2x_set_fw_mac_addr(&data->config_table[idx].msb_mac_addr,
&data->config_table[idx].middle_mac_addr,
&data->config_table[idx].lsb_mac_addr,
cfg_data->mac);
data->config_table[idx].vlan_id = 0;
data->config_table[idx].pf_id = r->func_id;
data->config_table[idx].clients_bit_vector =
cpu_to_le32(1 << r->cl_id);
SET_FLAG(data->config_table[idx].flags,
MAC_CONFIGURATION_ENTRY_ACTION_TYPE,
T_ETH_MAC_COMMAND_SET);
}
}
/**
* bnx2x_mcast_set_rdata_hdr_e1 - set header values in mac_configuration_cmd
*
* @bp: device handle
* @p:
* @len: number of rules to handle
*/
static inline void bnx2x_mcast_set_rdata_hdr_e1(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
u8 len)
{
struct bnx2x_raw_obj *r = &p->mcast_obj->raw;
struct mac_configuration_cmd *data =
(struct mac_configuration_cmd *)(r->rdata);
u8 offset = (CHIP_REV_IS_SLOW(bp) ?
BNX2X_MAX_EMUL_MULTI*(1 + r->func_id) :
BNX2X_MAX_MULTICAST*(1 + r->func_id));
data->hdr.offset = offset;
data->hdr.client_id = cpu_to_le16(0xff);
data->hdr.echo = cpu_to_le32((r->cid & BNX2X_SWCID_MASK) |
(BNX2X_FILTER_MCAST_PENDING <<
BNX2X_SWCID_SHIFT));
data->hdr.length = len;
}
/**
* bnx2x_mcast_handle_restore_cmd_e1 - restore command for 57710
*
* @bp: device handle
* @o:
* @start_idx: index in the registry to start from
* @rdata_idx: index in the ramrod data to start from
*
* restore command for 57710 is like all other commands - always a stand alone
* command - start_idx and rdata_idx will always be 0. This function will always
* succeed.
* returns -1 to comply with 57712 variant.
*/
static inline int bnx2x_mcast_handle_restore_cmd_e1(
struct bnx2x *bp, struct bnx2x_mcast_obj *o , int start_idx,
int *rdata_idx)
{
struct bnx2x_mcast_mac_elem *elem;
int i = 0;
union bnx2x_mcast_config_data cfg_data = {NULL};
/* go through the registry and configure the MACs from it. */
list_for_each_entry(elem, &o->registry.exact_match.macs, link) {
cfg_data.mac = &elem->mac[0];
o->set_one_rule(bp, o, i, &cfg_data, BNX2X_MCAST_CMD_RESTORE);
i++;
DP(BNX2X_MSG_SP, "About to configure %pM mcast MAC\n",
cfg_data.mac);
}
*rdata_idx = i;
return -1;
}
static inline int bnx2x_mcast_handle_pending_cmds_e1(
struct bnx2x *bp, struct bnx2x_mcast_ramrod_params *p)
{
struct bnx2x_pending_mcast_cmd *cmd_pos;
struct bnx2x_mcast_mac_elem *pmac_pos;
struct bnx2x_mcast_obj *o = p->mcast_obj;
union bnx2x_mcast_config_data cfg_data = {NULL};
int cnt = 0;
/* If nothing to be done - return */
if (list_empty(&o->pending_cmds_head))
return 0;
/* Handle the first command */
cmd_pos = list_first_entry(&o->pending_cmds_head,
struct bnx2x_pending_mcast_cmd, link);
switch (cmd_pos->type) {
case BNX2X_MCAST_CMD_ADD:
list_for_each_entry(pmac_pos, &cmd_pos->data.macs_head, link) {
cfg_data.mac = &pmac_pos->mac[0];
o->set_one_rule(bp, o, cnt, &cfg_data, cmd_pos->type);
cnt++;
DP(BNX2X_MSG_SP, "About to configure %pM mcast MAC\n",
pmac_pos->mac);
}
break;
case BNX2X_MCAST_CMD_DEL:
cnt = cmd_pos->data.macs_num;
DP(BNX2X_MSG_SP, "About to delete %d multicast MACs\n", cnt);
break;
case BNX2X_MCAST_CMD_RESTORE:
o->hdl_restore(bp, o, 0, &cnt);
break;
default:
BNX2X_ERR("Unknown command: %d\n", cmd_pos->type);
return -EINVAL;
}
list_del(&cmd_pos->link);
kfree(cmd_pos);
return cnt;
}
/**
* bnx2x_get_fw_mac_addr - revert the bnx2x_set_fw_mac_addr().
*
* @fw_hi:
* @fw_mid:
* @fw_lo:
* @mac:
*/
static inline void bnx2x_get_fw_mac_addr(__le16 *fw_hi, __le16 *fw_mid,
__le16 *fw_lo, u8 *mac)
{
mac[1] = ((u8 *)fw_hi)[0];
mac[0] = ((u8 *)fw_hi)[1];
mac[3] = ((u8 *)fw_mid)[0];
mac[2] = ((u8 *)fw_mid)[1];
mac[5] = ((u8 *)fw_lo)[0];
mac[4] = ((u8 *)fw_lo)[1];
}
/**
* bnx2x_mcast_refresh_registry_e1 -
*
* @bp: device handle
* @cnt:
*
* Check the ramrod data first entry flag to see if it's a DELETE or ADD command
* and update the registry correspondingly: if ADD - allocate a memory and add
* the entries to the registry (list), if DELETE - clear the registry and free
* the memory.
*/
static inline int bnx2x_mcast_refresh_registry_e1(struct bnx2x *bp,
struct bnx2x_mcast_obj *o)
{
struct bnx2x_raw_obj *raw = &o->raw;
struct bnx2x_mcast_mac_elem *elem;
struct mac_configuration_cmd *data =
(struct mac_configuration_cmd *)(raw->rdata);
/* If first entry contains a SET bit - the command was ADD,
* otherwise - DEL_ALL
*/
if (GET_FLAG(data->config_table[0].flags,
MAC_CONFIGURATION_ENTRY_ACTION_TYPE)) {
int i, len = data->hdr.length;
/* Break if it was a RESTORE command */
if (!list_empty(&o->registry.exact_match.macs))
return 0;
elem = kcalloc(len, sizeof(*elem), GFP_ATOMIC);
if (!elem) {
BNX2X_ERR("Failed to allocate registry memory\n");
return -ENOMEM;
}
for (i = 0; i < len; i++, elem++) {
bnx2x_get_fw_mac_addr(
&data->config_table[i].msb_mac_addr,
&data->config_table[i].middle_mac_addr,
&data->config_table[i].lsb_mac_addr,
elem->mac);
DP(BNX2X_MSG_SP, "Adding registry entry for [%pM]\n",
elem->mac);
list_add_tail(&elem->link,
&o->registry.exact_match.macs);
}
} else {
elem = list_first_entry(&o->registry.exact_match.macs,
struct bnx2x_mcast_mac_elem, link);
DP(BNX2X_MSG_SP, "Deleting a registry\n");
kfree(elem);
INIT_LIST_HEAD(&o->registry.exact_match.macs);
}
return 0;
}
static int bnx2x_mcast_setup_e1(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
struct bnx2x_raw_obj *raw = &o->raw;
struct mac_configuration_cmd *data =
(struct mac_configuration_cmd *)(raw->rdata);
int cnt = 0, i, rc;
/* Reset the ramrod data buffer */
memset(data, 0, sizeof(*data));
/* First set all entries as invalid */
for (i = 0; i < o->max_cmd_len ; i++)
SET_FLAG(data->config_table[i].flags,
MAC_CONFIGURATION_ENTRY_ACTION_TYPE,
T_ETH_MAC_COMMAND_INVALIDATE);
/* Handle pending commands first */
cnt = bnx2x_mcast_handle_pending_cmds_e1(bp, p);
/* If there are no more pending commands - clear SCHEDULED state */
if (list_empty(&o->pending_cmds_head))
o->clear_sched(o);
/* The below may be true iff there were no pending commands */
if (!cnt)
cnt = bnx2x_mcast_handle_current_cmd(bp, p, cmd, 0);
/* For 57710 every command has o->max_cmd_len length to ensure that
* commands are done one at a time.
*/
o->total_pending_num -= o->max_cmd_len;
/* send a ramrod */
WARN_ON(cnt > o->max_cmd_len);
/* Set ramrod header (in particular, a number of entries to update) */
bnx2x_mcast_set_rdata_hdr_e1(bp, p, (u8)cnt);
/* update a registry: we need the registry contents to be always up
* to date in order to be able to execute a RESTORE opcode. Here
* we use the fact that for 57710 we sent one command at a time
* hence we may take the registry update out of the command handling
* and do it in a simpler way here.
*/
rc = bnx2x_mcast_refresh_registry_e1(bp, o);
if (rc)
return rc;
/* If CLEAR_ONLY was requested - don't send a ramrod and clear
* RAMROD_PENDING status immediately.
*/
if (test_bit(RAMROD_DRV_CLR_ONLY, &p->ramrod_flags)) {
raw->clear_pending(raw);
return 0;
} else {
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
/* Send a ramrod */
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, raw->cid,
U64_HI(raw->rdata_mapping),
U64_LO(raw->rdata_mapping),
ETH_CONNECTION_TYPE);
if (rc)
return rc;
/* Ramrod completion is pending */
return 1;
}
}
static int bnx2x_mcast_get_registry_size_exact(struct bnx2x_mcast_obj *o)
{
return o->registry.exact_match.num_macs_set;
}
static int bnx2x_mcast_get_registry_size_aprox(struct bnx2x_mcast_obj *o)
{
return o->registry.aprox_match.num_bins_set;
}
static void bnx2x_mcast_set_registry_size_exact(struct bnx2x_mcast_obj *o,
int n)
{
o->registry.exact_match.num_macs_set = n;
}
static void bnx2x_mcast_set_registry_size_aprox(struct bnx2x_mcast_obj *o,
int n)
{
o->registry.aprox_match.num_bins_set = n;
}
int bnx2x_config_mcast(struct bnx2x *bp,
struct bnx2x_mcast_ramrod_params *p,
enum bnx2x_mcast_cmd cmd)
{
struct bnx2x_mcast_obj *o = p->mcast_obj;
struct bnx2x_raw_obj *r = &o->raw;
int rc = 0, old_reg_size;
/* This is needed to recover number of currently configured mcast macs
* in case of failure.
*/
old_reg_size = o->get_registry_size(o);
/* Do some calculations and checks */
rc = o->validate(bp, p, cmd);
if (rc)
return rc;
/* Return if there is no work to do */
if ((!p->mcast_list_len) && (!o->check_sched(o)))
return 0;
DP(BNX2X_MSG_SP, "o->total_pending_num=%d p->mcast_list_len=%d o->max_cmd_len=%d\n",
o->total_pending_num, p->mcast_list_len, o->max_cmd_len);
/* Enqueue the current command to the pending list if we can't complete
* it in the current iteration
*/
if (r->check_pending(r) ||
((o->max_cmd_len > 0) && (o->total_pending_num > o->max_cmd_len))) {
rc = o->enqueue_cmd(bp, p->mcast_obj, p, cmd);
if (rc < 0)
goto error_exit1;
/* As long as the current command is in a command list we
* don't need to handle it separately.
*/
p->mcast_list_len = 0;
}
if (!r->check_pending(r)) {
/* Set 'pending' state */
r->set_pending(r);
/* Configure the new classification in the chip */
rc = o->config_mcast(bp, p, cmd);
if (rc < 0)
goto error_exit2;
/* Wait for a ramrod completion if was requested */
if (test_bit(RAMROD_COMP_WAIT, &p->ramrod_flags))
rc = o->wait_comp(bp, o);
}
return rc;
error_exit2:
r->clear_pending(r);
error_exit1:
o->revert(bp, p, old_reg_size);
return rc;
}
static void bnx2x_mcast_clear_sched(struct bnx2x_mcast_obj *o)
{
smp_mb__before_atomic();
clear_bit(o->sched_state, o->raw.pstate);
smp_mb__after_atomic();
}
static void bnx2x_mcast_set_sched(struct bnx2x_mcast_obj *o)
{
smp_mb__before_atomic();
set_bit(o->sched_state, o->raw.pstate);
smp_mb__after_atomic();
}
static bool bnx2x_mcast_check_sched(struct bnx2x_mcast_obj *o)
{
return !!test_bit(o->sched_state, o->raw.pstate);
}
static bool bnx2x_mcast_check_pending(struct bnx2x_mcast_obj *o)
{
return o->raw.check_pending(&o->raw) || o->check_sched(o);
}
void bnx2x_init_mcast_obj(struct bnx2x *bp,
struct bnx2x_mcast_obj *mcast_obj,
u8 mcast_cl_id, u32 mcast_cid, u8 func_id,
u8 engine_id, void *rdata, dma_addr_t rdata_mapping,
int state, unsigned long *pstate, bnx2x_obj_type type)
{
memset(mcast_obj, 0, sizeof(*mcast_obj));
bnx2x_init_raw_obj(&mcast_obj->raw, mcast_cl_id, mcast_cid, func_id,
rdata, rdata_mapping, state, pstate, type);
mcast_obj->engine_id = engine_id;
INIT_LIST_HEAD(&mcast_obj->pending_cmds_head);
mcast_obj->sched_state = BNX2X_FILTER_MCAST_SCHED;
mcast_obj->check_sched = bnx2x_mcast_check_sched;
mcast_obj->set_sched = bnx2x_mcast_set_sched;
mcast_obj->clear_sched = bnx2x_mcast_clear_sched;
if (CHIP_IS_E1(bp)) {
mcast_obj->config_mcast = bnx2x_mcast_setup_e1;
mcast_obj->enqueue_cmd = bnx2x_mcast_enqueue_cmd;
mcast_obj->hdl_restore =
bnx2x_mcast_handle_restore_cmd_e1;
mcast_obj->check_pending = bnx2x_mcast_check_pending;
if (CHIP_REV_IS_SLOW(bp))
mcast_obj->max_cmd_len = BNX2X_MAX_EMUL_MULTI;
else
mcast_obj->max_cmd_len = BNX2X_MAX_MULTICAST;
mcast_obj->wait_comp = bnx2x_mcast_wait;
mcast_obj->set_one_rule = bnx2x_mcast_set_one_rule_e1;
mcast_obj->validate = bnx2x_mcast_validate_e1;
mcast_obj->revert = bnx2x_mcast_revert_e1;
mcast_obj->get_registry_size =
bnx2x_mcast_get_registry_size_exact;
mcast_obj->set_registry_size =
bnx2x_mcast_set_registry_size_exact;
/* 57710 is the only chip that uses the exact match for mcast
* at the moment.
*/
INIT_LIST_HEAD(&mcast_obj->registry.exact_match.macs);
} else if (CHIP_IS_E1H(bp)) {
mcast_obj->config_mcast = bnx2x_mcast_setup_e1h;
mcast_obj->enqueue_cmd = NULL;
mcast_obj->hdl_restore = NULL;
mcast_obj->check_pending = bnx2x_mcast_check_pending;
/* 57711 doesn't send a ramrod, so it has unlimited credit
* for one command.
*/
mcast_obj->max_cmd_len = -1;
mcast_obj->wait_comp = bnx2x_mcast_wait;
mcast_obj->set_one_rule = NULL;
mcast_obj->validate = bnx2x_mcast_validate_e1h;
mcast_obj->revert = bnx2x_mcast_revert_e1h;
mcast_obj->get_registry_size =
bnx2x_mcast_get_registry_size_aprox;
mcast_obj->set_registry_size =
bnx2x_mcast_set_registry_size_aprox;
} else {
mcast_obj->config_mcast = bnx2x_mcast_setup_e2;
mcast_obj->enqueue_cmd = bnx2x_mcast_enqueue_cmd;
mcast_obj->hdl_restore =
bnx2x_mcast_handle_restore_cmd_e2;
mcast_obj->check_pending = bnx2x_mcast_check_pending;
/* TODO: There should be a proper HSI define for this number!!!
*/
mcast_obj->max_cmd_len = 16;
mcast_obj->wait_comp = bnx2x_mcast_wait;
mcast_obj->set_one_rule = bnx2x_mcast_set_one_rule_e2;
mcast_obj->validate = bnx2x_mcast_validate_e2;
mcast_obj->revert = bnx2x_mcast_revert_e2;
mcast_obj->get_registry_size =
bnx2x_mcast_get_registry_size_aprox;
mcast_obj->set_registry_size =
bnx2x_mcast_set_registry_size_aprox;
}
}
/*************************** Credit handling **********************************/
/**
* atomic_add_ifless - add if the result is less than a given value.
*
* @v: pointer of type atomic_t
* @a: the amount to add to v...
* @u: ...if (v + a) is less than u.
*
* returns true if (v + a) was less than u, and false otherwise.
*
*/
static inline bool __atomic_add_ifless(atomic_t *v, int a, int u)
{
int c, old;
c = atomic_read(v);
for (;;) {
if (unlikely(c + a >= u))
return false;
old = atomic_cmpxchg((v), c, c + a);
if (likely(old == c))
break;
c = old;
}
return true;
}
/**
* atomic_dec_ifmoe - dec if the result is more or equal than a given value.
*
* @v: pointer of type atomic_t
* @a: the amount to dec from v...
* @u: ...if (v - a) is more or equal than u.
*
* returns true if (v - a) was more or equal than u, and false
* otherwise.
*/
static inline bool __atomic_dec_ifmoe(atomic_t *v, int a, int u)
{
int c, old;
c = atomic_read(v);
for (;;) {
if (unlikely(c - a < u))
return false;
old = atomic_cmpxchg((v), c, c - a);
if (likely(old == c))
break;
c = old;
}
return true;
}
static bool bnx2x_credit_pool_get(struct bnx2x_credit_pool_obj *o, int cnt)
{
bool rc;
smp_mb();
rc = __atomic_dec_ifmoe(&o->credit, cnt, 0);
smp_mb();
return rc;
}
static bool bnx2x_credit_pool_put(struct bnx2x_credit_pool_obj *o, int cnt)
{
bool rc;
smp_mb();
/* Don't let to refill if credit + cnt > pool_sz */
rc = __atomic_add_ifless(&o->credit, cnt, o->pool_sz + 1);
smp_mb();
return rc;
}
static int bnx2x_credit_pool_check(struct bnx2x_credit_pool_obj *o)
{
int cur_credit;
smp_mb();
cur_credit = atomic_read(&o->credit);
return cur_credit;
}
static bool bnx2x_credit_pool_always_true(struct bnx2x_credit_pool_obj *o,
int cnt)
{
return true;
}
static bool bnx2x_credit_pool_get_entry(
struct bnx2x_credit_pool_obj *o,
int *offset)
{
int idx, vec, i;
*offset = -1;
/* Find "internal cam-offset" then add to base for this object... */
for (vec = 0; vec < BNX2X_POOL_VEC_SIZE; vec++) {
/* Skip the current vector if there are no free entries in it */
if (!o->pool_mirror[vec])
continue;
/* If we've got here we are going to find a free entry */
for (idx = vec * BIT_VEC64_ELEM_SZ, i = 0;
i < BIT_VEC64_ELEM_SZ; idx++, i++)
if (BIT_VEC64_TEST_BIT(o->pool_mirror, idx)) {
/* Got one!! */
BIT_VEC64_CLEAR_BIT(o->pool_mirror, idx);
*offset = o->base_pool_offset + idx;
return true;
}
}
return false;
}
static bool bnx2x_credit_pool_put_entry(
struct bnx2x_credit_pool_obj *o,
int offset)
{
if (offset < o->base_pool_offset)
return false;
offset -= o->base_pool_offset;
if (offset >= o->pool_sz)
return false;
/* Return the entry to the pool */
BIT_VEC64_SET_BIT(o->pool_mirror, offset);
return true;
}
static bool bnx2x_credit_pool_put_entry_always_true(
struct bnx2x_credit_pool_obj *o,
int offset)
{
return true;
}
static bool bnx2x_credit_pool_get_entry_always_true(
struct bnx2x_credit_pool_obj *o,
int *offset)
{
*offset = -1;
return true;
}
/**
* bnx2x_init_credit_pool - initialize credit pool internals.
*
* @p:
* @base: Base entry in the CAM to use.
* @credit: pool size.
*
* If base is negative no CAM entries handling will be performed.
* If credit is negative pool operations will always succeed (unlimited pool).
*
*/
static inline void bnx2x_init_credit_pool(struct bnx2x_credit_pool_obj *p,
int base, int credit)
{
/* Zero the object first */
memset(p, 0, sizeof(*p));
/* Set the table to all 1s */
memset(&p->pool_mirror, 0xff, sizeof(p->pool_mirror));
/* Init a pool as full */
atomic_set(&p->credit, credit);
/* The total poll size */
p->pool_sz = credit;
p->base_pool_offset = base;
/* Commit the change */
smp_mb();
p->check = bnx2x_credit_pool_check;
/* if pool credit is negative - disable the checks */
if (credit >= 0) {
p->put = bnx2x_credit_pool_put;
p->get = bnx2x_credit_pool_get;
p->put_entry = bnx2x_credit_pool_put_entry;
p->get_entry = bnx2x_credit_pool_get_entry;
} else {
p->put = bnx2x_credit_pool_always_true;
p->get = bnx2x_credit_pool_always_true;
p->put_entry = bnx2x_credit_pool_put_entry_always_true;
p->get_entry = bnx2x_credit_pool_get_entry_always_true;
}
/* If base is negative - disable entries handling */
if (base < 0) {
p->put_entry = bnx2x_credit_pool_put_entry_always_true;
p->get_entry = bnx2x_credit_pool_get_entry_always_true;
}
}
void bnx2x_init_mac_credit_pool(struct bnx2x *bp,
struct bnx2x_credit_pool_obj *p, u8 func_id,
u8 func_num)
{
/* TODO: this will be defined in consts as well... */
#define BNX2X_CAM_SIZE_EMUL 5
int cam_sz;
if (CHIP_IS_E1(bp)) {
/* In E1, Multicast is saved in cam... */
if (!CHIP_REV_IS_SLOW(bp))
cam_sz = (MAX_MAC_CREDIT_E1 / 2) - BNX2X_MAX_MULTICAST;
else
cam_sz = BNX2X_CAM_SIZE_EMUL - BNX2X_MAX_EMUL_MULTI;
bnx2x_init_credit_pool(p, func_id * cam_sz, cam_sz);
} else if (CHIP_IS_E1H(bp)) {
/* CAM credit is equaly divided between all active functions
* on the PORT!.
*/
if ((func_num > 0)) {
if (!CHIP_REV_IS_SLOW(bp))
cam_sz = (MAX_MAC_CREDIT_E1H / (2*func_num));
else
cam_sz = BNX2X_CAM_SIZE_EMUL;
bnx2x_init_credit_pool(p, func_id * cam_sz, cam_sz);
} else {
/* this should never happen! Block MAC operations. */
bnx2x_init_credit_pool(p, 0, 0);
}
} else {
/* CAM credit is equaly divided between all active functions
* on the PATH.
*/
if ((func_num > 0)) {
if (!CHIP_REV_IS_SLOW(bp))
cam_sz = (MAX_MAC_CREDIT_E2 / func_num);
else
cam_sz = BNX2X_CAM_SIZE_EMUL;
/* No need for CAM entries handling for 57712 and
* newer.
*/
bnx2x_init_credit_pool(p, -1, cam_sz);
} else {
/* this should never happen! Block MAC operations. */
bnx2x_init_credit_pool(p, 0, 0);
}
}
}
void bnx2x_init_vlan_credit_pool(struct bnx2x *bp,
struct bnx2x_credit_pool_obj *p,
u8 func_id,
u8 func_num)
{
if (CHIP_IS_E1x(bp)) {
/* There is no VLAN credit in HW on 57710 and 57711 only
* MAC / MAC-VLAN can be set
*/
bnx2x_init_credit_pool(p, 0, -1);
} else {
/* CAM credit is equally divided between all active functions
* on the PATH.
*/
if (func_num > 0) {
int credit = MAX_VLAN_CREDIT_E2 / func_num;
bnx2x_init_credit_pool(p, func_id * credit, credit);
} else
/* this should never happen! Block VLAN operations. */
bnx2x_init_credit_pool(p, 0, 0);
}
}
/****************** RSS Configuration ******************/
/**
* bnx2x_debug_print_ind_table - prints the indirection table configuration.
*
* @bp: driver handle
* @p: pointer to rss configuration
*
* Prints it when NETIF_MSG_IFUP debug level is configured.
*/
static inline void bnx2x_debug_print_ind_table(struct bnx2x *bp,
struct bnx2x_config_rss_params *p)
{
int i;
DP(BNX2X_MSG_SP, "Setting indirection table to:\n");
DP(BNX2X_MSG_SP, "0x0000: ");
for (i = 0; i < T_ETH_INDIRECTION_TABLE_SIZE; i++) {
DP_CONT(BNX2X_MSG_SP, "0x%02x ", p->ind_table[i]);
/* Print 4 bytes in a line */
if ((i + 1 < T_ETH_INDIRECTION_TABLE_SIZE) &&
(((i + 1) & 0x3) == 0)) {
DP_CONT(BNX2X_MSG_SP, "\n");
DP(BNX2X_MSG_SP, "0x%04x: ", i + 1);
}
}
DP_CONT(BNX2X_MSG_SP, "\n");
}
/**
* bnx2x_setup_rss - configure RSS
*
* @bp: device handle
* @p: rss configuration
*
* sends on UPDATE ramrod for that matter.
*/
static int bnx2x_setup_rss(struct bnx2x *bp,
struct bnx2x_config_rss_params *p)
{
struct bnx2x_rss_config_obj *o = p->rss_obj;
struct bnx2x_raw_obj *r = &o->raw;
struct eth_rss_update_ramrod_data *data =
(struct eth_rss_update_ramrod_data *)(r->rdata);
u16 caps = 0;
u8 rss_mode = 0;
int rc;
memset(data, 0, sizeof(*data));
DP(BNX2X_MSG_SP, "Configuring RSS\n");
/* Set an echo field */
data->echo = cpu_to_le32((r->cid & BNX2X_SWCID_MASK) |
(r->state << BNX2X_SWCID_SHIFT));
/* RSS mode */
if (test_bit(BNX2X_RSS_MODE_DISABLED, &p->rss_flags))
rss_mode = ETH_RSS_MODE_DISABLED;
else if (test_bit(BNX2X_RSS_MODE_REGULAR, &p->rss_flags))
rss_mode = ETH_RSS_MODE_REGULAR;
data->rss_mode = rss_mode;
DP(BNX2X_MSG_SP, "rss_mode=%d\n", rss_mode);
/* RSS capabilities */
if (test_bit(BNX2X_RSS_IPV4, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV4_CAPABILITY;
if (test_bit(BNX2X_RSS_IPV4_TCP, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV4_TCP_CAPABILITY;
if (test_bit(BNX2X_RSS_IPV4_UDP, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV4_UDP_CAPABILITY;
if (test_bit(BNX2X_RSS_IPV6, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV6_CAPABILITY;
if (test_bit(BNX2X_RSS_IPV6_TCP, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV6_TCP_CAPABILITY;
if (test_bit(BNX2X_RSS_IPV6_UDP, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_IPV6_UDP_CAPABILITY;
if (test_bit(BNX2X_RSS_GRE_INNER_HDRS, &p->rss_flags))
caps |= ETH_RSS_UPDATE_RAMROD_DATA_GRE_INNER_HDRS_CAPABILITY;
/* RSS keys */
if (test_bit(BNX2X_RSS_SET_SRCH, &p->rss_flags)) {
memcpy(&data->rss_key[0], &p->rss_key[0],
sizeof(data->rss_key));
caps |= ETH_RSS_UPDATE_RAMROD_DATA_UPDATE_RSS_KEY;
}
data->capabilities = cpu_to_le16(caps);
/* Hashing mask */
data->rss_result_mask = p->rss_result_mask;
/* RSS engine ID */
data->rss_engine_id = o->engine_id;
DP(BNX2X_MSG_SP, "rss_engine_id=%d\n", data->rss_engine_id);
/* Indirection table */
memcpy(data->indirection_table, p->ind_table,
T_ETH_INDIRECTION_TABLE_SIZE);
/* Remember the last configuration */
memcpy(o->ind_table, p->ind_table, T_ETH_INDIRECTION_TABLE_SIZE);
/* Print the indirection table */
if (netif_msg_ifup(bp))
bnx2x_debug_print_ind_table(bp, p);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
/* Send a ramrod */
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_RSS_UPDATE, r->cid,
U64_HI(r->rdata_mapping),
U64_LO(r->rdata_mapping),
ETH_CONNECTION_TYPE);
if (rc < 0)
return rc;
return 1;
}
void bnx2x_get_rss_ind_table(struct bnx2x_rss_config_obj *rss_obj,
u8 *ind_table)
{
memcpy(ind_table, rss_obj->ind_table, sizeof(rss_obj->ind_table));
}
int bnx2x_config_rss(struct bnx2x *bp,
struct bnx2x_config_rss_params *p)
{
int rc;
struct bnx2x_rss_config_obj *o = p->rss_obj;
struct bnx2x_raw_obj *r = &o->raw;
/* Do nothing if only driver cleanup was requested */
if (test_bit(RAMROD_DRV_CLR_ONLY, &p->ramrod_flags)) {
DP(BNX2X_MSG_SP, "Not configuring RSS ramrod_flags=%lx\n",
p->ramrod_flags);
return 0;
}
r->set_pending(r);
rc = o->config_rss(bp, p);
if (rc < 0) {
r->clear_pending(r);
return rc;
}
if (test_bit(RAMROD_COMP_WAIT, &p->ramrod_flags))
rc = r->wait_comp(bp, r);
return rc;
}
void bnx2x_init_rss_config_obj(struct bnx2x *bp,
struct bnx2x_rss_config_obj *rss_obj,
u8 cl_id, u32 cid, u8 func_id, u8 engine_id,
void *rdata, dma_addr_t rdata_mapping,
int state, unsigned long *pstate,
bnx2x_obj_type type)
{
bnx2x_init_raw_obj(&rss_obj->raw, cl_id, cid, func_id, rdata,
rdata_mapping, state, pstate, type);
rss_obj->engine_id = engine_id;
rss_obj->config_rss = bnx2x_setup_rss;
}
/********************** Queue state object ***********************************/
/**
* bnx2x_queue_state_change - perform Queue state change transition
*
* @bp: device handle
* @params: parameters to perform the transition
*
* returns 0 in case of successfully completed transition, negative error
* code in case of failure, positive (EBUSY) value if there is a completion
* to that is still pending (possible only if RAMROD_COMP_WAIT is
* not set in params->ramrod_flags for asynchronous commands).
*
*/
int bnx2x_queue_state_change(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
int rc, pending_bit;
unsigned long *pending = &o->pending;
/* Check that the requested transition is legal */
rc = o->check_transition(bp, o, params);
if (rc) {
BNX2X_ERR("check transition returned an error. rc %d\n", rc);
return -EINVAL;
}
/* Set "pending" bit */
DP(BNX2X_MSG_SP, "pending bit was=%lx\n", o->pending);
pending_bit = o->set_pending(o, params);
DP(BNX2X_MSG_SP, "pending bit now=%lx\n", o->pending);
/* Don't send a command if only driver cleanup was requested */
if (test_bit(RAMROD_DRV_CLR_ONLY, ¶ms->ramrod_flags))
o->complete_cmd(bp, o, pending_bit);
else {
/* Send a ramrod */
rc = o->send_cmd(bp, params);
if (rc) {
o->next_state = BNX2X_Q_STATE_MAX;
clear_bit(pending_bit, pending);
smp_mb__after_atomic();
return rc;
}
if (test_bit(RAMROD_COMP_WAIT, ¶ms->ramrod_flags)) {
rc = o->wait_comp(bp, o, pending_bit);
if (rc)
return rc;
return 0;
}
}
return !!test_bit(pending_bit, pending);
}
static int bnx2x_queue_set_pending(struct bnx2x_queue_sp_obj *obj,
struct bnx2x_queue_state_params *params)
{
enum bnx2x_queue_cmd cmd = params->cmd, bit;
/* ACTIVATE and DEACTIVATE commands are implemented on top of
* UPDATE command.
*/
if ((cmd == BNX2X_Q_CMD_ACTIVATE) ||
(cmd == BNX2X_Q_CMD_DEACTIVATE))
bit = BNX2X_Q_CMD_UPDATE;
else
bit = cmd;
set_bit(bit, &obj->pending);
return bit;
}
static int bnx2x_queue_wait_comp(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *o,
enum bnx2x_queue_cmd cmd)
{
return bnx2x_state_wait(bp, cmd, &o->pending);
}
/**
* bnx2x_queue_comp_cmd - complete the state change command.
*
* @bp: device handle
* @o:
* @cmd:
*
* Checks that the arrived completion is expected.
*/
static int bnx2x_queue_comp_cmd(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *o,
enum bnx2x_queue_cmd cmd)
{
unsigned long cur_pending = o->pending;
if (!test_and_clear_bit(cmd, &cur_pending)) {
BNX2X_ERR("Bad MC reply %d for queue %d in state %d pending 0x%lx, next_state %d\n",
cmd, o->cids[BNX2X_PRIMARY_CID_INDEX],
o->state, cur_pending, o->next_state);
return -EINVAL;
}
if (o->next_tx_only >= o->max_cos)
/* >= because tx only must always be smaller than cos since the
* primary connection supports COS 0
*/
BNX2X_ERR("illegal value for next tx_only: %d. max cos was %d",
o->next_tx_only, o->max_cos);
DP(BNX2X_MSG_SP,
"Completing command %d for queue %d, setting state to %d\n",
cmd, o->cids[BNX2X_PRIMARY_CID_INDEX], o->next_state);
if (o->next_tx_only) /* print num tx-only if any exist */
DP(BNX2X_MSG_SP, "primary cid %d: num tx-only cons %d\n",
o->cids[BNX2X_PRIMARY_CID_INDEX], o->next_tx_only);
o->state = o->next_state;
o->num_tx_only = o->next_tx_only;
o->next_state = BNX2X_Q_STATE_MAX;
/* It's important that o->state and o->next_state are
* updated before o->pending.
*/
wmb();
clear_bit(cmd, &o->pending);
smp_mb__after_atomic();
return 0;
}
static void bnx2x_q_fill_setup_data_e2(struct bnx2x *bp,
struct bnx2x_queue_state_params *cmd_params,
struct client_init_ramrod_data *data)
{
struct bnx2x_queue_setup_params *params = &cmd_params->params.setup;
/* Rx data */
/* IPv6 TPA supported for E2 and above only */
data->rx.tpa_en |= test_bit(BNX2X_Q_FLG_TPA_IPV6, ¶ms->flags) *
CLIENT_INIT_RX_DATA_TPA_EN_IPV6;
}
static void bnx2x_q_fill_init_general_data(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *o,
struct bnx2x_general_setup_params *params,
struct client_init_general_data *gen_data,
unsigned long *flags)
{
gen_data->client_id = o->cl_id;
if (test_bit(BNX2X_Q_FLG_STATS, flags)) {
gen_data->statistics_counter_id =
params->stat_id;
gen_data->statistics_en_flg = 1;
gen_data->statistics_zero_flg =
test_bit(BNX2X_Q_FLG_ZERO_STATS, flags);
} else
gen_data->statistics_counter_id =
DISABLE_STATISTIC_COUNTER_ID_VALUE;
gen_data->is_fcoe_flg = test_bit(BNX2X_Q_FLG_FCOE, flags);
gen_data->activate_flg = test_bit(BNX2X_Q_FLG_ACTIVE, flags);
gen_data->sp_client_id = params->spcl_id;
gen_data->mtu = cpu_to_le16(params->mtu);
gen_data->func_id = o->func_id;
gen_data->cos = params->cos;
gen_data->traffic_type =
test_bit(BNX2X_Q_FLG_FCOE, flags) ?
LLFC_TRAFFIC_TYPE_FCOE : LLFC_TRAFFIC_TYPE_NW;
gen_data->fp_hsi_ver = params->fp_hsi;
DP(BNX2X_MSG_SP, "flags: active %d, cos %d, stats en %d\n",
gen_data->activate_flg, gen_data->cos, gen_data->statistics_en_flg);
}
static void bnx2x_q_fill_init_tx_data(struct bnx2x_queue_sp_obj *o,
struct bnx2x_txq_setup_params *params,
struct client_init_tx_data *tx_data,
unsigned long *flags)
{
tx_data->enforce_security_flg =
test_bit(BNX2X_Q_FLG_TX_SEC, flags);
tx_data->default_vlan =
cpu_to_le16(params->default_vlan);
tx_data->default_vlan_flg =
test_bit(BNX2X_Q_FLG_DEF_VLAN, flags);
tx_data->tx_switching_flg =
test_bit(BNX2X_Q_FLG_TX_SWITCH, flags);
tx_data->anti_spoofing_flg =
test_bit(BNX2X_Q_FLG_ANTI_SPOOF, flags);
tx_data->force_default_pri_flg =
test_bit(BNX2X_Q_FLG_FORCE_DEFAULT_PRI, flags);
tx_data->refuse_outband_vlan_flg =
test_bit(BNX2X_Q_FLG_REFUSE_OUTBAND_VLAN, flags);
tx_data->tunnel_lso_inc_ip_id =
test_bit(BNX2X_Q_FLG_TUN_INC_INNER_IP_ID, flags);
tx_data->tunnel_non_lso_pcsum_location =
test_bit(BNX2X_Q_FLG_PCSUM_ON_PKT, flags) ? CSUM_ON_PKT :
CSUM_ON_BD;
tx_data->tx_status_block_id = params->fw_sb_id;
tx_data->tx_sb_index_number = params->sb_cq_index;
tx_data->tss_leading_client_id = params->tss_leading_cl_id;
tx_data->tx_bd_page_base.lo =
cpu_to_le32(U64_LO(params->dscr_map));
tx_data->tx_bd_page_base.hi =
cpu_to_le32(U64_HI(params->dscr_map));
/* Don't configure any Tx switching mode during queue SETUP */
tx_data->state = 0;
}
static void bnx2x_q_fill_init_pause_data(struct bnx2x_queue_sp_obj *o,
struct rxq_pause_params *params,
struct client_init_rx_data *rx_data)
{
/* flow control data */
rx_data->cqe_pause_thr_low = cpu_to_le16(params->rcq_th_lo);
rx_data->cqe_pause_thr_high = cpu_to_le16(params->rcq_th_hi);
rx_data->bd_pause_thr_low = cpu_to_le16(params->bd_th_lo);
rx_data->bd_pause_thr_high = cpu_to_le16(params->bd_th_hi);
rx_data->sge_pause_thr_low = cpu_to_le16(params->sge_th_lo);
rx_data->sge_pause_thr_high = cpu_to_le16(params->sge_th_hi);
rx_data->rx_cos_mask = cpu_to_le16(params->pri_map);
}
static void bnx2x_q_fill_init_rx_data(struct bnx2x_queue_sp_obj *o,
struct bnx2x_rxq_setup_params *params,
struct client_init_rx_data *rx_data,
unsigned long *flags)
{
rx_data->tpa_en = test_bit(BNX2X_Q_FLG_TPA, flags) *
CLIENT_INIT_RX_DATA_TPA_EN_IPV4;
rx_data->tpa_en |= test_bit(BNX2X_Q_FLG_TPA_GRO, flags) *
CLIENT_INIT_RX_DATA_TPA_MODE;
rx_data->vmqueue_mode_en_flg = 0;
rx_data->cache_line_alignment_log_size =
params->cache_line_log;
rx_data->enable_dynamic_hc =
test_bit(BNX2X_Q_FLG_DHC, flags);
rx_data->max_sges_for_packet = params->max_sges_pkt;
rx_data->client_qzone_id = params->cl_qzone_id;
rx_data->max_agg_size = cpu_to_le16(params->tpa_agg_sz);
/* Always start in DROP_ALL mode */
rx_data->state = cpu_to_le16(CLIENT_INIT_RX_DATA_UCAST_DROP_ALL |
CLIENT_INIT_RX_DATA_MCAST_DROP_ALL);
/* We don't set drop flags */
rx_data->drop_ip_cs_err_flg = 0;
rx_data->drop_tcp_cs_err_flg = 0;
rx_data->drop_ttl0_flg = 0;
rx_data->drop_udp_cs_err_flg = 0;
rx_data->inner_vlan_removal_enable_flg =
test_bit(BNX2X_Q_FLG_VLAN, flags);
rx_data->outer_vlan_removal_enable_flg =
test_bit(BNX2X_Q_FLG_OV, flags);
rx_data->status_block_id = params->fw_sb_id;
rx_data->rx_sb_index_number = params->sb_cq_index;
rx_data->max_tpa_queues = params->max_tpa_queues;
rx_data->max_bytes_on_bd = cpu_to_le16(params->buf_sz);
rx_data->sge_buff_size = cpu_to_le16(params->sge_buf_sz);
rx_data->bd_page_base.lo =
cpu_to_le32(U64_LO(params->dscr_map));
rx_data->bd_page_base.hi =
cpu_to_le32(U64_HI(params->dscr_map));
rx_data->sge_page_base.lo =
cpu_to_le32(U64_LO(params->sge_map));
rx_data->sge_page_base.hi =
cpu_to_le32(U64_HI(params->sge_map));
rx_data->cqe_page_base.lo =
cpu_to_le32(U64_LO(params->rcq_map));
rx_data->cqe_page_base.hi =
cpu_to_le32(U64_HI(params->rcq_map));
rx_data->is_leading_rss = test_bit(BNX2X_Q_FLG_LEADING_RSS, flags);
if (test_bit(BNX2X_Q_FLG_MCAST, flags)) {
rx_data->approx_mcast_engine_id = params->mcast_engine_id;
rx_data->is_approx_mcast = 1;
}
rx_data->rss_engine_id = params->rss_engine_id;
/* silent vlan removal */
rx_data->silent_vlan_removal_flg =
test_bit(BNX2X_Q_FLG_SILENT_VLAN_REM, flags);
rx_data->silent_vlan_value =
cpu_to_le16(params->silent_removal_value);
rx_data->silent_vlan_mask =
cpu_to_le16(params->silent_removal_mask);
}
/* initialize the general, tx and rx parts of a queue object */
static void bnx2x_q_fill_setup_data_cmn(struct bnx2x *bp,
struct bnx2x_queue_state_params *cmd_params,
struct client_init_ramrod_data *data)
{
bnx2x_q_fill_init_general_data(bp, cmd_params->q_obj,
&cmd_params->params.setup.gen_params,
&data->general,
&cmd_params->params.setup.flags);
bnx2x_q_fill_init_tx_data(cmd_params->q_obj,
&cmd_params->params.setup.txq_params,
&data->tx,
&cmd_params->params.setup.flags);
bnx2x_q_fill_init_rx_data(cmd_params->q_obj,
&cmd_params->params.setup.rxq_params,
&data->rx,
&cmd_params->params.setup.flags);
bnx2x_q_fill_init_pause_data(cmd_params->q_obj,
&cmd_params->params.setup.pause_params,
&data->rx);
}
/* initialize the general and tx parts of a tx-only queue object */
static void bnx2x_q_fill_setup_tx_only(struct bnx2x *bp,
struct bnx2x_queue_state_params *cmd_params,
struct tx_queue_init_ramrod_data *data)
{
bnx2x_q_fill_init_general_data(bp, cmd_params->q_obj,
&cmd_params->params.tx_only.gen_params,
&data->general,
&cmd_params->params.tx_only.flags);
bnx2x_q_fill_init_tx_data(cmd_params->q_obj,
&cmd_params->params.tx_only.txq_params,
&data->tx,
&cmd_params->params.tx_only.flags);
DP(BNX2X_MSG_SP, "cid %d, tx bd page lo %x hi %x",
cmd_params->q_obj->cids[0],
data->tx.tx_bd_page_base.lo,
data->tx.tx_bd_page_base.hi);
}
/**
* bnx2x_q_init - init HW/FW queue
*
* @bp: device handle
* @params:
*
* HW/FW initial Queue configuration:
* - HC: Rx and Tx
* - CDU context validation
*
*/
static inline int bnx2x_q_init(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct bnx2x_queue_init_params *init = ¶ms->params.init;
u16 hc_usec;
u8 cos;
/* Tx HC configuration */
if (test_bit(BNX2X_Q_TYPE_HAS_TX, &o->type) &&
test_bit(BNX2X_Q_FLG_HC, &init->tx.flags)) {
hc_usec = init->tx.hc_rate ? 1000000 / init->tx.hc_rate : 0;
bnx2x_update_coalesce_sb_index(bp, init->tx.fw_sb_id,
init->tx.sb_cq_index,
!test_bit(BNX2X_Q_FLG_HC_EN, &init->tx.flags),
hc_usec);
}
/* Rx HC configuration */
if (test_bit(BNX2X_Q_TYPE_HAS_RX, &o->type) &&
test_bit(BNX2X_Q_FLG_HC, &init->rx.flags)) {
hc_usec = init->rx.hc_rate ? 1000000 / init->rx.hc_rate : 0;
bnx2x_update_coalesce_sb_index(bp, init->rx.fw_sb_id,
init->rx.sb_cq_index,
!test_bit(BNX2X_Q_FLG_HC_EN, &init->rx.flags),
hc_usec);
}
/* Set CDU context validation values */
for (cos = 0; cos < o->max_cos; cos++) {
DP(BNX2X_MSG_SP, "setting context validation. cid %d, cos %d\n",
o->cids[cos], cos);
DP(BNX2X_MSG_SP, "context pointer %p\n", init->cxts[cos]);
bnx2x_set_ctx_validation(bp, init->cxts[cos], o->cids[cos]);
}
/* As no ramrod is sent, complete the command immediately */
o->complete_cmd(bp, o, BNX2X_Q_CMD_INIT);
mmiowb();
smp_mb();
return 0;
}
static inline int bnx2x_q_send_setup_e1x(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct client_init_ramrod_data *rdata =
(struct client_init_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
int ramrod = RAMROD_CMD_ID_ETH_CLIENT_SETUP;
/* Clear the ramrod data */
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data */
bnx2x_q_fill_setup_data_cmn(bp, params, rdata);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, ramrod, o->cids[BNX2X_PRIMARY_CID_INDEX],
U64_HI(data_mapping),
U64_LO(data_mapping), ETH_CONNECTION_TYPE);
}
static inline int bnx2x_q_send_setup_e2(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct client_init_ramrod_data *rdata =
(struct client_init_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
int ramrod = RAMROD_CMD_ID_ETH_CLIENT_SETUP;
/* Clear the ramrod data */
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data */
bnx2x_q_fill_setup_data_cmn(bp, params, rdata);
bnx2x_q_fill_setup_data_e2(bp, params, rdata);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, ramrod, o->cids[BNX2X_PRIMARY_CID_INDEX],
U64_HI(data_mapping),
U64_LO(data_mapping), ETH_CONNECTION_TYPE);
}
static inline int bnx2x_q_send_setup_tx_only(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct tx_queue_init_ramrod_data *rdata =
(struct tx_queue_init_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
int ramrod = RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP;
struct bnx2x_queue_setup_tx_only_params *tx_only_params =
¶ms->params.tx_only;
u8 cid_index = tx_only_params->cid_index;
if (cid_index >= o->max_cos) {
BNX2X_ERR("queue[%d]: cid_index (%d) is out of range\n",
o->cl_id, cid_index);
return -EINVAL;
}
DP(BNX2X_MSG_SP, "parameters received: cos: %d sp-id: %d\n",
tx_only_params->gen_params.cos,
tx_only_params->gen_params.spcl_id);
/* Clear the ramrod data */
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data */
bnx2x_q_fill_setup_tx_only(bp, params, rdata);
DP(BNX2X_MSG_SP, "sending tx-only ramrod: cid %d, client-id %d, sp-client id %d, cos %d\n",
o->cids[cid_index], rdata->general.client_id,
rdata->general.sp_client_id, rdata->general.cos);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, ramrod, o->cids[cid_index],
U64_HI(data_mapping),
U64_LO(data_mapping), ETH_CONNECTION_TYPE);
}
static void bnx2x_q_fill_update_data(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *obj,
struct bnx2x_queue_update_params *params,
struct client_update_ramrod_data *data)
{
/* Client ID of the client to update */
data->client_id = obj->cl_id;
/* Function ID of the client to update */
data->func_id = obj->func_id;
/* Default VLAN value */
data->default_vlan = cpu_to_le16(params->def_vlan);
/* Inner VLAN stripping */
data->inner_vlan_removal_enable_flg =
test_bit(BNX2X_Q_UPDATE_IN_VLAN_REM, ¶ms->update_flags);
data->inner_vlan_removal_change_flg =
test_bit(BNX2X_Q_UPDATE_IN_VLAN_REM_CHNG,
¶ms->update_flags);
/* Outer VLAN stripping */
data->outer_vlan_removal_enable_flg =
test_bit(BNX2X_Q_UPDATE_OUT_VLAN_REM, ¶ms->update_flags);
data->outer_vlan_removal_change_flg =
test_bit(BNX2X_Q_UPDATE_OUT_VLAN_REM_CHNG,
¶ms->update_flags);
/* Drop packets that have source MAC that doesn't belong to this
* Queue.
*/
data->anti_spoofing_enable_flg =
test_bit(BNX2X_Q_UPDATE_ANTI_SPOOF, ¶ms->update_flags);
data->anti_spoofing_change_flg =
test_bit(BNX2X_Q_UPDATE_ANTI_SPOOF_CHNG, ¶ms->update_flags);
/* Activate/Deactivate */
data->activate_flg =
test_bit(BNX2X_Q_UPDATE_ACTIVATE, ¶ms->update_flags);
data->activate_change_flg =
test_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG, ¶ms->update_flags);
/* Enable default VLAN */
data->default_vlan_enable_flg =
test_bit(BNX2X_Q_UPDATE_DEF_VLAN_EN, ¶ms->update_flags);
data->default_vlan_change_flg =
test_bit(BNX2X_Q_UPDATE_DEF_VLAN_EN_CHNG,
¶ms->update_flags);
/* silent vlan removal */
data->silent_vlan_change_flg =
test_bit(BNX2X_Q_UPDATE_SILENT_VLAN_REM_CHNG,
¶ms->update_flags);
data->silent_vlan_removal_flg =
test_bit(BNX2X_Q_UPDATE_SILENT_VLAN_REM, ¶ms->update_flags);
data->silent_vlan_value = cpu_to_le16(params->silent_removal_value);
data->silent_vlan_mask = cpu_to_le16(params->silent_removal_mask);
/* tx switching */
data->tx_switching_flg =
test_bit(BNX2X_Q_UPDATE_TX_SWITCHING, ¶ms->update_flags);
data->tx_switching_change_flg =
test_bit(BNX2X_Q_UPDATE_TX_SWITCHING_CHNG,
¶ms->update_flags);
/* PTP */
data->handle_ptp_pkts_flg =
test_bit(BNX2X_Q_UPDATE_PTP_PKTS, ¶ms->update_flags);
data->handle_ptp_pkts_change_flg =
test_bit(BNX2X_Q_UPDATE_PTP_PKTS_CHNG, ¶ms->update_flags);
}
static inline int bnx2x_q_send_update(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct client_update_ramrod_data *rdata =
(struct client_update_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_queue_update_params *update_params =
¶ms->params.update;
u8 cid_index = update_params->cid_index;
if (cid_index >= o->max_cos) {
BNX2X_ERR("queue[%d]: cid_index (%d) is out of range\n",
o->cl_id, cid_index);
return -EINVAL;
}
/* Clear the ramrod data */
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data */
bnx2x_q_fill_update_data(bp, o, update_params, rdata);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_CLIENT_UPDATE,
o->cids[cid_index], U64_HI(data_mapping),
U64_LO(data_mapping), ETH_CONNECTION_TYPE);
}
/**
* bnx2x_q_send_deactivate - send DEACTIVATE command
*
* @bp: device handle
* @params:
*
* implemented using the UPDATE command.
*/
static inline int bnx2x_q_send_deactivate(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_update_params *update = ¶ms->params.update;
memset(update, 0, sizeof(*update));
__set_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG, &update->update_flags);
return bnx2x_q_send_update(bp, params);
}
/**
* bnx2x_q_send_activate - send ACTIVATE command
*
* @bp: device handle
* @params:
*
* implemented using the UPDATE command.
*/
static inline int bnx2x_q_send_activate(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_update_params *update = ¶ms->params.update;
memset(update, 0, sizeof(*update));
__set_bit(BNX2X_Q_UPDATE_ACTIVATE, &update->update_flags);
__set_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG, &update->update_flags);
return bnx2x_q_send_update(bp, params);
}
static void bnx2x_q_fill_update_tpa_data(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *obj,
struct bnx2x_queue_update_tpa_params *params,
struct tpa_update_ramrod_data *data)
{
data->client_id = obj->cl_id;
data->complete_on_both_clients = params->complete_on_both_clients;
data->dont_verify_rings_pause_thr_flg =
params->dont_verify_thr;
data->max_agg_size = cpu_to_le16(params->max_agg_sz);
data->max_sges_for_packet = params->max_sges_pkt;
data->max_tpa_queues = params->max_tpa_queues;
data->sge_buff_size = cpu_to_le16(params->sge_buff_sz);
data->sge_page_base_hi = cpu_to_le32(U64_HI(params->sge_map));
data->sge_page_base_lo = cpu_to_le32(U64_LO(params->sge_map));
data->sge_pause_thr_high = cpu_to_le16(params->sge_pause_thr_high);
data->sge_pause_thr_low = cpu_to_le16(params->sge_pause_thr_low);
data->tpa_mode = params->tpa_mode;
data->update_ipv4 = params->update_ipv4;
data->update_ipv6 = params->update_ipv6;
}
static inline int bnx2x_q_send_update_tpa(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
struct tpa_update_ramrod_data *rdata =
(struct tpa_update_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_queue_update_tpa_params *update_tpa_params =
¶ms->params.update_tpa;
u16 type;
/* Clear the ramrod data */
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data */
bnx2x_q_fill_update_tpa_data(bp, o, update_tpa_params, rdata);
/* Add the function id inside the type, so that sp post function
* doesn't automatically add the PF func-id, this is required
* for operations done by PFs on behalf of their VFs
*/
type = ETH_CONNECTION_TYPE |
((o->func_id) << SPE_HDR_FUNCTION_ID_SHIFT);
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_TPA_UPDATE,
o->cids[BNX2X_PRIMARY_CID_INDEX],
U64_HI(data_mapping),
U64_LO(data_mapping), type);
}
static inline int bnx2x_q_send_halt(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
return bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_HALT,
o->cids[BNX2X_PRIMARY_CID_INDEX], 0, o->cl_id,
ETH_CONNECTION_TYPE);
}
static inline int bnx2x_q_send_cfc_del(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
u8 cid_idx = params->params.cfc_del.cid_index;
if (cid_idx >= o->max_cos) {
BNX2X_ERR("queue[%d]: cid_index (%d) is out of range\n",
o->cl_id, cid_idx);
return -EINVAL;
}
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_CFC_DEL,
o->cids[cid_idx], 0, 0, NONE_CONNECTION_TYPE);
}
static inline int bnx2x_q_send_terminate(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
u8 cid_index = params->params.terminate.cid_index;
if (cid_index >= o->max_cos) {
BNX2X_ERR("queue[%d]: cid_index (%d) is out of range\n",
o->cl_id, cid_index);
return -EINVAL;
}
return bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_TERMINATE,
o->cids[cid_index], 0, 0, ETH_CONNECTION_TYPE);
}
static inline int bnx2x_q_send_empty(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
struct bnx2x_queue_sp_obj *o = params->q_obj;
return bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_EMPTY,
o->cids[BNX2X_PRIMARY_CID_INDEX], 0, 0,
ETH_CONNECTION_TYPE);
}
static inline int bnx2x_queue_send_cmd_cmn(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
switch (params->cmd) {
case BNX2X_Q_CMD_INIT:
return bnx2x_q_init(bp, params);
case BNX2X_Q_CMD_SETUP_TX_ONLY:
return bnx2x_q_send_setup_tx_only(bp, params);
case BNX2X_Q_CMD_DEACTIVATE:
return bnx2x_q_send_deactivate(bp, params);
case BNX2X_Q_CMD_ACTIVATE:
return bnx2x_q_send_activate(bp, params);
case BNX2X_Q_CMD_UPDATE:
return bnx2x_q_send_update(bp, params);
case BNX2X_Q_CMD_UPDATE_TPA:
return bnx2x_q_send_update_tpa(bp, params);
case BNX2X_Q_CMD_HALT:
return bnx2x_q_send_halt(bp, params);
case BNX2X_Q_CMD_CFC_DEL:
return bnx2x_q_send_cfc_del(bp, params);
case BNX2X_Q_CMD_TERMINATE:
return bnx2x_q_send_terminate(bp, params);
case BNX2X_Q_CMD_EMPTY:
return bnx2x_q_send_empty(bp, params);
default:
BNX2X_ERR("Unknown command: %d\n", params->cmd);
return -EINVAL;
}
}
static int bnx2x_queue_send_cmd_e1x(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
switch (params->cmd) {
case BNX2X_Q_CMD_SETUP:
return bnx2x_q_send_setup_e1x(bp, params);
case BNX2X_Q_CMD_INIT:
case BNX2X_Q_CMD_SETUP_TX_ONLY:
case BNX2X_Q_CMD_DEACTIVATE:
case BNX2X_Q_CMD_ACTIVATE:
case BNX2X_Q_CMD_UPDATE:
case BNX2X_Q_CMD_UPDATE_TPA:
case BNX2X_Q_CMD_HALT:
case BNX2X_Q_CMD_CFC_DEL:
case BNX2X_Q_CMD_TERMINATE:
case BNX2X_Q_CMD_EMPTY:
return bnx2x_queue_send_cmd_cmn(bp, params);
default:
BNX2X_ERR("Unknown command: %d\n", params->cmd);
return -EINVAL;
}
}
static int bnx2x_queue_send_cmd_e2(struct bnx2x *bp,
struct bnx2x_queue_state_params *params)
{
switch (params->cmd) {
case BNX2X_Q_CMD_SETUP:
return bnx2x_q_send_setup_e2(bp, params);
case BNX2X_Q_CMD_INIT:
case BNX2X_Q_CMD_SETUP_TX_ONLY:
case BNX2X_Q_CMD_DEACTIVATE:
case BNX2X_Q_CMD_ACTIVATE:
case BNX2X_Q_CMD_UPDATE:
case BNX2X_Q_CMD_UPDATE_TPA:
case BNX2X_Q_CMD_HALT:
case BNX2X_Q_CMD_CFC_DEL:
case BNX2X_Q_CMD_TERMINATE:
case BNX2X_Q_CMD_EMPTY:
return bnx2x_queue_send_cmd_cmn(bp, params);
default:
BNX2X_ERR("Unknown command: %d\n", params->cmd);
return -EINVAL;
}
}
/**
* bnx2x_queue_chk_transition - check state machine of a regular Queue
*
* @bp: device handle
* @o:
* @params:
*
* (not Forwarding)
* It both checks if the requested command is legal in a current
* state and, if it's legal, sets a `next_state' in the object
* that will be used in the completion flow to set the `state'
* of the object.
*
* returns 0 if a requested command is a legal transition,
* -EINVAL otherwise.
*/
static int bnx2x_queue_chk_transition(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *o,
struct bnx2x_queue_state_params *params)
{
enum bnx2x_q_state state = o->state, next_state = BNX2X_Q_STATE_MAX;
enum bnx2x_queue_cmd cmd = params->cmd;
struct bnx2x_queue_update_params *update_params =
¶ms->params.update;
u8 next_tx_only = o->num_tx_only;
/* Forget all pending for completion commands if a driver only state
* transition has been requested.
*/
if (test_bit(RAMROD_DRV_CLR_ONLY, ¶ms->ramrod_flags)) {
o->pending = 0;
o->next_state = BNX2X_Q_STATE_MAX;
}
/* Don't allow a next state transition if we are in the middle of
* the previous one.
*/
if (o->pending) {
BNX2X_ERR("Blocking transition since pending was %lx\n",
o->pending);
return -EBUSY;
}
switch (state) {
case BNX2X_Q_STATE_RESET:
if (cmd == BNX2X_Q_CMD_INIT)
next_state = BNX2X_Q_STATE_INITIALIZED;
break;
case BNX2X_Q_STATE_INITIALIZED:
if (cmd == BNX2X_Q_CMD_SETUP) {
if (test_bit(BNX2X_Q_FLG_ACTIVE,
¶ms->params.setup.flags))
next_state = BNX2X_Q_STATE_ACTIVE;
else
next_state = BNX2X_Q_STATE_INACTIVE;
}
break;
case BNX2X_Q_STATE_ACTIVE:
if (cmd == BNX2X_Q_CMD_DEACTIVATE)
next_state = BNX2X_Q_STATE_INACTIVE;
else if ((cmd == BNX2X_Q_CMD_EMPTY) ||
(cmd == BNX2X_Q_CMD_UPDATE_TPA))
next_state = BNX2X_Q_STATE_ACTIVE;
else if (cmd == BNX2X_Q_CMD_SETUP_TX_ONLY) {
next_state = BNX2X_Q_STATE_MULTI_COS;
next_tx_only = 1;
}
else if (cmd == BNX2X_Q_CMD_HALT)
next_state = BNX2X_Q_STATE_STOPPED;
else if (cmd == BNX2X_Q_CMD_UPDATE) {
/* If "active" state change is requested, update the
* state accordingly.
*/
if (test_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG,
&update_params->update_flags) &&
!test_bit(BNX2X_Q_UPDATE_ACTIVATE,
&update_params->update_flags))
next_state = BNX2X_Q_STATE_INACTIVE;
else
next_state = BNX2X_Q_STATE_ACTIVE;
}
break;
case BNX2X_Q_STATE_MULTI_COS:
if (cmd == BNX2X_Q_CMD_TERMINATE)
next_state = BNX2X_Q_STATE_MCOS_TERMINATED;
else if (cmd == BNX2X_Q_CMD_SETUP_TX_ONLY) {
next_state = BNX2X_Q_STATE_MULTI_COS;
next_tx_only = o->num_tx_only + 1;
}
else if ((cmd == BNX2X_Q_CMD_EMPTY) ||
(cmd == BNX2X_Q_CMD_UPDATE_TPA))
next_state = BNX2X_Q_STATE_MULTI_COS;
else if (cmd == BNX2X_Q_CMD_UPDATE) {
/* If "active" state change is requested, update the
* state accordingly.
*/
if (test_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG,
&update_params->update_flags) &&
!test_bit(BNX2X_Q_UPDATE_ACTIVATE,
&update_params->update_flags))
next_state = BNX2X_Q_STATE_INACTIVE;
else
next_state = BNX2X_Q_STATE_MULTI_COS;
}
break;
case BNX2X_Q_STATE_MCOS_TERMINATED:
if (cmd == BNX2X_Q_CMD_CFC_DEL) {
next_tx_only = o->num_tx_only - 1;
if (next_tx_only == 0)
next_state = BNX2X_Q_STATE_ACTIVE;
else
next_state = BNX2X_Q_STATE_MULTI_COS;
}
break;
case BNX2X_Q_STATE_INACTIVE:
if (cmd == BNX2X_Q_CMD_ACTIVATE)
next_state = BNX2X_Q_STATE_ACTIVE;
else if ((cmd == BNX2X_Q_CMD_EMPTY) ||
(cmd == BNX2X_Q_CMD_UPDATE_TPA))
next_state = BNX2X_Q_STATE_INACTIVE;
else if (cmd == BNX2X_Q_CMD_HALT)
next_state = BNX2X_Q_STATE_STOPPED;
else if (cmd == BNX2X_Q_CMD_UPDATE) {
/* If "active" state change is requested, update the
* state accordingly.
*/
if (test_bit(BNX2X_Q_UPDATE_ACTIVATE_CHNG,
&update_params->update_flags) &&
test_bit(BNX2X_Q_UPDATE_ACTIVATE,
&update_params->update_flags)){
if (o->num_tx_only == 0)
next_state = BNX2X_Q_STATE_ACTIVE;
else /* tx only queues exist for this queue */
next_state = BNX2X_Q_STATE_MULTI_COS;
} else
next_state = BNX2X_Q_STATE_INACTIVE;
}
break;
case BNX2X_Q_STATE_STOPPED:
if (cmd == BNX2X_Q_CMD_TERMINATE)
next_state = BNX2X_Q_STATE_TERMINATED;
break;
case BNX2X_Q_STATE_TERMINATED:
if (cmd == BNX2X_Q_CMD_CFC_DEL)
next_state = BNX2X_Q_STATE_RESET;
break;
default:
BNX2X_ERR("Illegal state: %d\n", state);
}
/* Transition is assured */
if (next_state != BNX2X_Q_STATE_MAX) {
DP(BNX2X_MSG_SP, "Good state transition: %d(%d)->%d\n",
state, cmd, next_state);
o->next_state = next_state;
o->next_tx_only = next_tx_only;
return 0;
}
DP(BNX2X_MSG_SP, "Bad state transition request: %d %d\n", state, cmd);
return -EINVAL;
}
void bnx2x_init_queue_obj(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *obj,
u8 cl_id, u32 *cids, u8 cid_cnt, u8 func_id,
void *rdata,
dma_addr_t rdata_mapping, unsigned long type)
{
memset(obj, 0, sizeof(*obj));
/* We support only BNX2X_MULTI_TX_COS Tx CoS at the moment */
BUG_ON(BNX2X_MULTI_TX_COS < cid_cnt);
memcpy(obj->cids, cids, sizeof(obj->cids[0]) * cid_cnt);
obj->max_cos = cid_cnt;
obj->cl_id = cl_id;
obj->func_id = func_id;
obj->rdata = rdata;
obj->rdata_mapping = rdata_mapping;
obj->type = type;
obj->next_state = BNX2X_Q_STATE_MAX;
if (CHIP_IS_E1x(bp))
obj->send_cmd = bnx2x_queue_send_cmd_e1x;
else
obj->send_cmd = bnx2x_queue_send_cmd_e2;
obj->check_transition = bnx2x_queue_chk_transition;
obj->complete_cmd = bnx2x_queue_comp_cmd;
obj->wait_comp = bnx2x_queue_wait_comp;
obj->set_pending = bnx2x_queue_set_pending;
}
/* return a queue object's logical state*/
int bnx2x_get_q_logical_state(struct bnx2x *bp,
struct bnx2x_queue_sp_obj *obj)
{
switch (obj->state) {
case BNX2X_Q_STATE_ACTIVE:
case BNX2X_Q_STATE_MULTI_COS:
return BNX2X_Q_LOGICAL_STATE_ACTIVE;
case BNX2X_Q_STATE_RESET:
case BNX2X_Q_STATE_INITIALIZED:
case BNX2X_Q_STATE_MCOS_TERMINATED:
case BNX2X_Q_STATE_INACTIVE:
case BNX2X_Q_STATE_STOPPED:
case BNX2X_Q_STATE_TERMINATED:
case BNX2X_Q_STATE_FLRED:
return BNX2X_Q_LOGICAL_STATE_STOPPED;
default:
return -EINVAL;
}
}
/********************** Function state object *********************************/
enum bnx2x_func_state bnx2x_func_get_state(struct bnx2x *bp,
struct bnx2x_func_sp_obj *o)
{
/* in the middle of transaction - return INVALID state */
if (o->pending)
return BNX2X_F_STATE_MAX;
/* unsure the order of reading of o->pending and o->state
* o->pending should be read first
*/
rmb();
return o->state;
}
static int bnx2x_func_wait_comp(struct bnx2x *bp,
struct bnx2x_func_sp_obj *o,
enum bnx2x_func_cmd cmd)
{
return bnx2x_state_wait(bp, cmd, &o->pending);
}
/**
* bnx2x_func_state_change_comp - complete the state machine transition
*
* @bp: device handle
* @o:
* @cmd:
*
* Called on state change transition. Completes the state
* machine transition only - no HW interaction.
*/
static inline int bnx2x_func_state_change_comp(struct bnx2x *bp,
struct bnx2x_func_sp_obj *o,
enum bnx2x_func_cmd cmd)
{
unsigned long cur_pending = o->pending;
if (!test_and_clear_bit(cmd, &cur_pending)) {
BNX2X_ERR("Bad MC reply %d for func %d in state %d pending 0x%lx, next_state %d\n",
cmd, BP_FUNC(bp), o->state,
cur_pending, o->next_state);
return -EINVAL;
}
DP(BNX2X_MSG_SP,
"Completing command %d for func %d, setting state to %d\n",
cmd, BP_FUNC(bp), o->next_state);
o->state = o->next_state;
o->next_state = BNX2X_F_STATE_MAX;
/* It's important that o->state and o->next_state are
* updated before o->pending.
*/
wmb();
clear_bit(cmd, &o->pending);
smp_mb__after_atomic();
return 0;
}
/**
* bnx2x_func_comp_cmd - complete the state change command
*
* @bp: device handle
* @o:
* @cmd:
*
* Checks that the arrived completion is expected.
*/
static int bnx2x_func_comp_cmd(struct bnx2x *bp,
struct bnx2x_func_sp_obj *o,
enum bnx2x_func_cmd cmd)
{
/* Complete the state machine part first, check if it's a
* legal completion.
*/
int rc = bnx2x_func_state_change_comp(bp, o, cmd);
return rc;
}
/**
* bnx2x_func_chk_transition - perform function state machine transition
*
* @bp: device handle
* @o:
* @params:
*
* It both checks if the requested command is legal in a current
* state and, if it's legal, sets a `next_state' in the object
* that will be used in the completion flow to set the `state'
* of the object.
*
* returns 0 if a requested command is a legal transition,
* -EINVAL otherwise.
*/
static int bnx2x_func_chk_transition(struct bnx2x *bp,
struct bnx2x_func_sp_obj *o,
struct bnx2x_func_state_params *params)
{
enum bnx2x_func_state state = o->state, next_state = BNX2X_F_STATE_MAX;
enum bnx2x_func_cmd cmd = params->cmd;
/* Forget all pending for completion commands if a driver only state
* transition has been requested.
*/
if (test_bit(RAMROD_DRV_CLR_ONLY, ¶ms->ramrod_flags)) {
o->pending = 0;
o->next_state = BNX2X_F_STATE_MAX;
}
/* Don't allow a next state transition if we are in the middle of
* the previous one.
*/
if (o->pending)
return -EBUSY;
switch (state) {
case BNX2X_F_STATE_RESET:
if (cmd == BNX2X_F_CMD_HW_INIT)
next_state = BNX2X_F_STATE_INITIALIZED;
break;
case BNX2X_F_STATE_INITIALIZED:
if (cmd == BNX2X_F_CMD_START)
next_state = BNX2X_F_STATE_STARTED;
else if (cmd == BNX2X_F_CMD_HW_RESET)
next_state = BNX2X_F_STATE_RESET;
break;
case BNX2X_F_STATE_STARTED:
if (cmd == BNX2X_F_CMD_STOP)
next_state = BNX2X_F_STATE_INITIALIZED;
/* afex ramrods can be sent only in started mode, and only
* if not pending for function_stop ramrod completion
* for these events - next state remained STARTED.
*/
else if ((cmd == BNX2X_F_CMD_AFEX_UPDATE) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_STARTED;
else if ((cmd == BNX2X_F_CMD_AFEX_VIFLISTS) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_STARTED;
/* Switch_update ramrod can be sent in either started or
* tx_stopped state, and it doesn't change the state.
*/
else if ((cmd == BNX2X_F_CMD_SWITCH_UPDATE) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_STARTED;
else if ((cmd == BNX2X_F_CMD_SET_TIMESYNC) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_STARTED;
else if (cmd == BNX2X_F_CMD_TX_STOP)
next_state = BNX2X_F_STATE_TX_STOPPED;
break;
case BNX2X_F_STATE_TX_STOPPED:
if ((cmd == BNX2X_F_CMD_SWITCH_UPDATE) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_TX_STOPPED;
else if ((cmd == BNX2X_F_CMD_SET_TIMESYNC) &&
(!test_bit(BNX2X_F_CMD_STOP, &o->pending)))
next_state = BNX2X_F_STATE_TX_STOPPED;
else if (cmd == BNX2X_F_CMD_TX_START)
next_state = BNX2X_F_STATE_STARTED;
break;
default:
BNX2X_ERR("Unknown state: %d\n", state);
}
/* Transition is assured */
if (next_state != BNX2X_F_STATE_MAX) {
DP(BNX2X_MSG_SP, "Good function state transition: %d(%d)->%d\n",
state, cmd, next_state);
o->next_state = next_state;
return 0;
}
DP(BNX2X_MSG_SP, "Bad function state transition request: %d %d\n",
state, cmd);
return -EINVAL;
}
/**
* bnx2x_func_init_func - performs HW init at function stage
*
* @bp: device handle
* @drv:
*
* Init HW when the current phase is
* FW_MSG_CODE_DRV_LOAD_FUNCTION: initialize only FUNCTION-only
* HW blocks.
*/
static inline int bnx2x_func_init_func(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
return drv->init_hw_func(bp);
}
/**
* bnx2x_func_init_port - performs HW init at port stage
*
* @bp: device handle
* @drv:
*
* Init HW when the current phase is
* FW_MSG_CODE_DRV_LOAD_PORT: initialize PORT-only and
* FUNCTION-only HW blocks.
*
*/
static inline int bnx2x_func_init_port(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
int rc = drv->init_hw_port(bp);
if (rc)
return rc;
return bnx2x_func_init_func(bp, drv);
}
/**
* bnx2x_func_init_cmn_chip - performs HW init at chip-common stage
*
* @bp: device handle
* @drv:
*
* Init HW when the current phase is
* FW_MSG_CODE_DRV_LOAD_COMMON_CHIP: initialize COMMON_CHIP,
* PORT-only and FUNCTION-only HW blocks.
*/
static inline int bnx2x_func_init_cmn_chip(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
int rc = drv->init_hw_cmn_chip(bp);
if (rc)
return rc;
return bnx2x_func_init_port(bp, drv);
}
/**
* bnx2x_func_init_cmn - performs HW init at common stage
*
* @bp: device handle
* @drv:
*
* Init HW when the current phase is
* FW_MSG_CODE_DRV_LOAD_COMMON_CHIP: initialize COMMON,
* PORT-only and FUNCTION-only HW blocks.
*/
static inline int bnx2x_func_init_cmn(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
int rc = drv->init_hw_cmn(bp);
if (rc)
return rc;
return bnx2x_func_init_port(bp, drv);
}
static int bnx2x_func_hw_init(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
u32 load_code = params->params.hw_init.load_phase;
struct bnx2x_func_sp_obj *o = params->f_obj;
const struct bnx2x_func_sp_drv_ops *drv = o->drv;
int rc = 0;
DP(BNX2X_MSG_SP, "function %d load_code %x\n",
BP_ABS_FUNC(bp), load_code);
/* Prepare buffers for unzipping the FW */
rc = drv->gunzip_init(bp);
if (rc)
return rc;
/* Prepare FW */
rc = drv->init_fw(bp);
if (rc) {
BNX2X_ERR("Error loading firmware\n");
goto init_err;
}
/* Handle the beginning of COMMON_XXX pases separately... */
switch (load_code) {
case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
rc = bnx2x_func_init_cmn_chip(bp, drv);
if (rc)
goto init_err;
break;
case FW_MSG_CODE_DRV_LOAD_COMMON:
rc = bnx2x_func_init_cmn(bp, drv);
if (rc)
goto init_err;
break;
case FW_MSG_CODE_DRV_LOAD_PORT:
rc = bnx2x_func_init_port(bp, drv);
if (rc)
goto init_err;
break;
case FW_MSG_CODE_DRV_LOAD_FUNCTION:
rc = bnx2x_func_init_func(bp, drv);
if (rc)
goto init_err;
break;
default:
BNX2X_ERR("Unknown load_code (0x%x) from MCP\n", load_code);
rc = -EINVAL;
}
init_err:
drv->gunzip_end(bp);
/* In case of success, complete the command immediately: no ramrods
* have been sent.
*/
if (!rc)
o->complete_cmd(bp, o, BNX2X_F_CMD_HW_INIT);
return rc;
}
/**
* bnx2x_func_reset_func - reset HW at function stage
*
* @bp: device handle
* @drv:
*
* Reset HW at FW_MSG_CODE_DRV_UNLOAD_FUNCTION stage: reset only
* FUNCTION-only HW blocks.
*/
static inline void bnx2x_func_reset_func(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
drv->reset_hw_func(bp);
}
/**
* bnx2x_func_reset_port - reset HW at port stage
*
* @bp: device handle
* @drv:
*
* Reset HW at FW_MSG_CODE_DRV_UNLOAD_PORT stage: reset
* FUNCTION-only and PORT-only HW blocks.
*
* !!!IMPORTANT!!!
*
* It's important to call reset_port before reset_func() as the last thing
* reset_func does is pf_disable() thus disabling PGLUE_B, which
* makes impossible any DMAE transactions.
*/
static inline void bnx2x_func_reset_port(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
drv->reset_hw_port(bp);
bnx2x_func_reset_func(bp, drv);
}
/**
* bnx2x_func_reset_cmn - reset HW at common stage
*
* @bp: device handle
* @drv:
*
* Reset HW at FW_MSG_CODE_DRV_UNLOAD_COMMON and
* FW_MSG_CODE_DRV_UNLOAD_COMMON_CHIP stages: reset COMMON,
* COMMON_CHIP, FUNCTION-only and PORT-only HW blocks.
*/
static inline void bnx2x_func_reset_cmn(struct bnx2x *bp,
const struct bnx2x_func_sp_drv_ops *drv)
{
bnx2x_func_reset_port(bp, drv);
drv->reset_hw_cmn(bp);
}
static inline int bnx2x_func_hw_reset(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
u32 reset_phase = params->params.hw_reset.reset_phase;
struct bnx2x_func_sp_obj *o = params->f_obj;
const struct bnx2x_func_sp_drv_ops *drv = o->drv;
DP(BNX2X_MSG_SP, "function %d reset_phase %x\n", BP_ABS_FUNC(bp),
reset_phase);
switch (reset_phase) {
case FW_MSG_CODE_DRV_UNLOAD_COMMON:
bnx2x_func_reset_cmn(bp, drv);
break;
case FW_MSG_CODE_DRV_UNLOAD_PORT:
bnx2x_func_reset_port(bp, drv);
break;
case FW_MSG_CODE_DRV_UNLOAD_FUNCTION:
bnx2x_func_reset_func(bp, drv);
break;
default:
BNX2X_ERR("Unknown reset_phase (0x%x) from MCP\n",
reset_phase);
break;
}
/* Complete the command immediately: no ramrods have been sent. */
o->complete_cmd(bp, o, BNX2X_F_CMD_HW_RESET);
return 0;
}
static inline int bnx2x_func_send_start(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct function_start_data *rdata =
(struct function_start_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_func_start_params *start_params = ¶ms->params.start;
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data with provided parameters */
rdata->function_mode = (u8)start_params->mf_mode;
rdata->sd_vlan_tag = cpu_to_le16(start_params->sd_vlan_tag);
rdata->path_id = BP_PATH(bp);
rdata->network_cos_mode = start_params->network_cos_mode;
rdata->tunnel_mode = start_params->tunnel_mode;
rdata->gre_tunnel_type = start_params->gre_tunnel_type;
rdata->inner_gre_rss_en = start_params->inner_gre_rss_en;
rdata->vxlan_dst_port = cpu_to_le16(4789);
rdata->sd_accept_mf_clss_fail = start_params->class_fail;
if (start_params->class_fail_ethtype) {
rdata->sd_accept_mf_clss_fail_match_ethtype = 1;
rdata->sd_accept_mf_clss_fail_ethtype =
cpu_to_le16(start_params->class_fail_ethtype);
}
rdata->sd_vlan_force_pri_flg = start_params->sd_vlan_force_pri;
rdata->sd_vlan_force_pri_val = start_params->sd_vlan_force_pri_val;
if (start_params->sd_vlan_eth_type)
rdata->sd_vlan_eth_type =
cpu_to_le16(start_params->sd_vlan_eth_type);
else
rdata->sd_vlan_eth_type =
cpu_to_le16(0x8100);
rdata->no_added_tags = start_params->no_added_tags;
/* No need for an explicit memory barrier here as long we would
* need to ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read and we will have to put a full memory barrier there
* (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_FUNCTION_START, 0,
U64_HI(data_mapping),
U64_LO(data_mapping), NONE_CONNECTION_TYPE);
}
static inline int bnx2x_func_send_switch_update(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct function_update_data *rdata =
(struct function_update_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_func_switch_update_params *switch_update_params =
¶ms->params.switch_update;
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data with provided parameters */
if (test_bit(BNX2X_F_UPDATE_TX_SWITCH_SUSPEND_CHNG,
&switch_update_params->changes)) {
rdata->tx_switch_suspend_change_flg = 1;
rdata->tx_switch_suspend =
test_bit(BNX2X_F_UPDATE_TX_SWITCH_SUSPEND,
&switch_update_params->changes);
}
if (test_bit(BNX2X_F_UPDATE_SD_VLAN_TAG_CHNG,
&switch_update_params->changes)) {
rdata->sd_vlan_tag_change_flg = 1;
rdata->sd_vlan_tag =
cpu_to_le16(switch_update_params->vlan);
}
if (test_bit(BNX2X_F_UPDATE_SD_VLAN_ETH_TYPE_CHNG,
&switch_update_params->changes)) {
rdata->sd_vlan_eth_type_change_flg = 1;
rdata->sd_vlan_eth_type =
cpu_to_le16(switch_update_params->vlan_eth_type);
}
if (test_bit(BNX2X_F_UPDATE_VLAN_FORCE_PRIO_CHNG,
&switch_update_params->changes)) {
rdata->sd_vlan_force_pri_change_flg = 1;
if (test_bit(BNX2X_F_UPDATE_VLAN_FORCE_PRIO_FLAG,
&switch_update_params->changes))
rdata->sd_vlan_force_pri_flg = 1;
rdata->sd_vlan_force_pri_flg =
switch_update_params->vlan_force_prio;
}
if (test_bit(BNX2X_F_UPDATE_TUNNEL_CFG_CHNG,
&switch_update_params->changes)) {
rdata->update_tunn_cfg_flg = 1;
if (test_bit(BNX2X_F_UPDATE_TUNNEL_CLSS_EN,
&switch_update_params->changes))
rdata->tunn_clss_en = 1;
if (test_bit(BNX2X_F_UPDATE_TUNNEL_INNER_GRE_RSS_EN,
&switch_update_params->changes))
rdata->inner_gre_rss_en = 1;
rdata->tunnel_mode = switch_update_params->tunnel_mode;
rdata->gre_tunnel_type = switch_update_params->gre_tunnel_type;
rdata->vxlan_dst_port = cpu_to_le16(4789);
}
rdata->echo = SWITCH_UPDATE;
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_FUNCTION_UPDATE, 0,
U64_HI(data_mapping),
U64_LO(data_mapping), NONE_CONNECTION_TYPE);
}
static inline int bnx2x_func_send_afex_update(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct function_update_data *rdata =
(struct function_update_data *)o->afex_rdata;
dma_addr_t data_mapping = o->afex_rdata_mapping;
struct bnx2x_func_afex_update_params *afex_update_params =
¶ms->params.afex_update;
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data with provided parameters */
rdata->vif_id_change_flg = 1;
rdata->vif_id = cpu_to_le16(afex_update_params->vif_id);
rdata->afex_default_vlan_change_flg = 1;
rdata->afex_default_vlan =
cpu_to_le16(afex_update_params->afex_default_vlan);
rdata->allowed_priorities_change_flg = 1;
rdata->allowed_priorities = afex_update_params->allowed_priorities;
rdata->echo = AFEX_UPDATE;
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
DP(BNX2X_MSG_SP,
"afex: sending func_update vif_id 0x%x dvlan 0x%x prio 0x%x\n",
rdata->vif_id,
rdata->afex_default_vlan, rdata->allowed_priorities);
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_FUNCTION_UPDATE, 0,
U64_HI(data_mapping),
U64_LO(data_mapping), NONE_CONNECTION_TYPE);
}
static
inline int bnx2x_func_send_afex_viflists(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct afex_vif_list_ramrod_data *rdata =
(struct afex_vif_list_ramrod_data *)o->afex_rdata;
struct bnx2x_func_afex_viflists_params *afex_vif_params =
¶ms->params.afex_viflists;
u64 *p_rdata = (u64 *)rdata;
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data with provided parameters */
rdata->vif_list_index = cpu_to_le16(afex_vif_params->vif_list_index);
rdata->func_bit_map = afex_vif_params->func_bit_map;
rdata->afex_vif_list_command = afex_vif_params->afex_vif_list_command;
rdata->func_to_clear = afex_vif_params->func_to_clear;
/* send in echo type of sub command */
rdata->echo = afex_vif_params->afex_vif_list_command;
/* No need for an explicit memory barrier here as long we would
* need to ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read and we will have to put a full memory barrier there
* (inside bnx2x_sp_post()).
*/
DP(BNX2X_MSG_SP, "afex: ramrod lists, cmd 0x%x index 0x%x func_bit_map 0x%x func_to_clr 0x%x\n",
rdata->afex_vif_list_command, rdata->vif_list_index,
rdata->func_bit_map, rdata->func_to_clear);
/* this ramrod sends data directly and not through DMA mapping */
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_AFEX_VIF_LISTS, 0,
U64_HI(*p_rdata), U64_LO(*p_rdata),
NONE_CONNECTION_TYPE);
}
static inline int bnx2x_func_send_stop(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_FUNCTION_STOP, 0, 0, 0,
NONE_CONNECTION_TYPE);
}
static inline int bnx2x_func_send_tx_stop(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_STOP_TRAFFIC, 0, 0, 0,
NONE_CONNECTION_TYPE);
}
static inline int bnx2x_func_send_tx_start(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct flow_control_configuration *rdata =
(struct flow_control_configuration *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_func_tx_start_params *tx_start_params =
¶ms->params.tx_start;
int i;
memset(rdata, 0, sizeof(*rdata));
rdata->dcb_enabled = tx_start_params->dcb_enabled;
rdata->dcb_version = tx_start_params->dcb_version;
rdata->dont_add_pri_0_en = tx_start_params->dont_add_pri_0_en;
for (i = 0; i < ARRAY_SIZE(rdata->traffic_type_to_priority_cos); i++)
rdata->traffic_type_to_priority_cos[i] =
tx_start_params->traffic_type_to_priority_cos[i];
/* No need for an explicit memory barrier here as long as we
* ensure the ordering of writing to the SPQ element
* and updating of the SPQ producer which involves a memory
* read. If the memory read is removed we will have to put a
* full memory barrier there (inside bnx2x_sp_post()).
*/
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_START_TRAFFIC, 0,
U64_HI(data_mapping),
U64_LO(data_mapping), NONE_CONNECTION_TYPE);
}
static inline
int bnx2x_func_send_set_timesync(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
struct set_timesync_ramrod_data *rdata =
(struct set_timesync_ramrod_data *)o->rdata;
dma_addr_t data_mapping = o->rdata_mapping;
struct bnx2x_func_set_timesync_params *set_timesync_params =
¶ms->params.set_timesync;
memset(rdata, 0, sizeof(*rdata));
/* Fill the ramrod data with provided parameters */
rdata->drift_adjust_cmd = set_timesync_params->drift_adjust_cmd;
rdata->offset_cmd = set_timesync_params->offset_cmd;
rdata->add_sub_drift_adjust_value =
set_timesync_params->add_sub_drift_adjust_value;
rdata->drift_adjust_value = set_timesync_params->drift_adjust_value;
rdata->drift_adjust_period = set_timesync_params->drift_adjust_period;
rdata->offset_delta.lo =
cpu_to_le32(U64_LO(set_timesync_params->offset_delta));
rdata->offset_delta.hi =
cpu_to_le32(U64_HI(set_timesync_params->offset_delta));
DP(BNX2X_MSG_SP, "Set timesync command params: drift_cmd = %d, offset_cmd = %d, add_sub_drift = %d, drift_val = %d, drift_period = %d, offset_lo = %d, offset_hi = %d\n",
rdata->drift_adjust_cmd, rdata->offset_cmd,
rdata->add_sub_drift_adjust_value, rdata->drift_adjust_value,
rdata->drift_adjust_period, rdata->offset_delta.lo,
rdata->offset_delta.hi);
return bnx2x_sp_post(bp, RAMROD_CMD_ID_COMMON_SET_TIMESYNC, 0,
U64_HI(data_mapping),
U64_LO(data_mapping), NONE_CONNECTION_TYPE);
}
static int bnx2x_func_send_cmd(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
switch (params->cmd) {
case BNX2X_F_CMD_HW_INIT:
return bnx2x_func_hw_init(bp, params);
case BNX2X_F_CMD_START:
return bnx2x_func_send_start(bp, params);
case BNX2X_F_CMD_STOP:
return bnx2x_func_send_stop(bp, params);
case BNX2X_F_CMD_HW_RESET:
return bnx2x_func_hw_reset(bp, params);
case BNX2X_F_CMD_AFEX_UPDATE:
return bnx2x_func_send_afex_update(bp, params);
case BNX2X_F_CMD_AFEX_VIFLISTS:
return bnx2x_func_send_afex_viflists(bp, params);
case BNX2X_F_CMD_TX_STOP:
return bnx2x_func_send_tx_stop(bp, params);
case BNX2X_F_CMD_TX_START:
return bnx2x_func_send_tx_start(bp, params);
case BNX2X_F_CMD_SWITCH_UPDATE:
return bnx2x_func_send_switch_update(bp, params);
case BNX2X_F_CMD_SET_TIMESYNC:
return bnx2x_func_send_set_timesync(bp, params);
default:
BNX2X_ERR("Unknown command: %d\n", params->cmd);
return -EINVAL;
}
}
void bnx2x_init_func_obj(struct bnx2x *bp,
struct bnx2x_func_sp_obj *obj,
void *rdata, dma_addr_t rdata_mapping,
void *afex_rdata, dma_addr_t afex_rdata_mapping,
struct bnx2x_func_sp_drv_ops *drv_iface)
{
memset(obj, 0, sizeof(*obj));
mutex_init(&obj->one_pending_mutex);
obj->rdata = rdata;
obj->rdata_mapping = rdata_mapping;
obj->afex_rdata = afex_rdata;
obj->afex_rdata_mapping = afex_rdata_mapping;
obj->send_cmd = bnx2x_func_send_cmd;
obj->check_transition = bnx2x_func_chk_transition;
obj->complete_cmd = bnx2x_func_comp_cmd;
obj->wait_comp = bnx2x_func_wait_comp;
obj->drv = drv_iface;
}
/**
* bnx2x_func_state_change - perform Function state change transition
*
* @bp: device handle
* @params: parameters to perform the transaction
*
* returns 0 in case of successfully completed transition,
* negative error code in case of failure, positive
* (EBUSY) value if there is a completion to that is
* still pending (possible only if RAMROD_COMP_WAIT is
* not set in params->ramrod_flags for asynchronous
* commands).
*/
int bnx2x_func_state_change(struct bnx2x *bp,
struct bnx2x_func_state_params *params)
{
struct bnx2x_func_sp_obj *o = params->f_obj;
int rc, cnt = 300;
enum bnx2x_func_cmd cmd = params->cmd;
unsigned long *pending = &o->pending;
mutex_lock(&o->one_pending_mutex);
/* Check that the requested transition is legal */
rc = o->check_transition(bp, o, params);
if ((rc == -EBUSY) &&
(test_bit(RAMROD_RETRY, ¶ms->ramrod_flags))) {
while ((rc == -EBUSY) && (--cnt > 0)) {
mutex_unlock(&o->one_pending_mutex);
msleep(10);
mutex_lock(&o->one_pending_mutex);
rc = o->check_transition(bp, o, params);
}
if (rc == -EBUSY) {
mutex_unlock(&o->one_pending_mutex);
BNX2X_ERR("timeout waiting for previous ramrod completion\n");
return rc;
}
} else if (rc) {
mutex_unlock(&o->one_pending_mutex);
return rc;
}
/* Set "pending" bit */
set_bit(cmd, pending);
/* Don't send a command if only driver cleanup was requested */
if (test_bit(RAMROD_DRV_CLR_ONLY, ¶ms->ramrod_flags)) {
bnx2x_func_state_change_comp(bp, o, cmd);
mutex_unlock(&o->one_pending_mutex);
} else {
/* Send a ramrod */
rc = o->send_cmd(bp, params);
mutex_unlock(&o->one_pending_mutex);
if (rc) {
o->next_state = BNX2X_F_STATE_MAX;
clear_bit(cmd, pending);
smp_mb__after_atomic();
return rc;
}
if (test_bit(RAMROD_COMP_WAIT, ¶ms->ramrod_flags)) {
rc = o->wait_comp(bp, o, cmd);
if (rc)
return rc;
return 0;
}
}
return !!test_bit(cmd, pending);
}
|
systemdaemon/systemd
|
src/linux/drivers/net/ethernet/broadcom/bnx2x/bnx2x_sp.c
|
C
|
gpl-2.0
| 169,975
|
/* linux/arch/arm/mach-s5p64x0/include/mach/s5p64x0-clock.h
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Header file for s5p64x0 clock support
*
* 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.
*/
#ifndef __ASM_ARCH_CLOCK_H
#define __ASM_ARCH_CLOCK_H __FILE__
#include <linux/clk.h>
extern struct clksrc_clk clk_mout_apll;
extern struct clksrc_clk clk_mout_mpll;
extern struct clksrc_clk clk_mout_epll;
extern int s5p64x0_epll_enable(struct clk *clk, int enable);
extern unsigned long s5p64x0_epll_get_rate(struct clk *clk);
extern unsigned long s5p64x0_armclk_get_rate(struct clk *clk);
extern unsigned long s5p64x0_armclk_round_rate(struct clk *clk, unsigned long rate);
extern int s5p64x0_armclk_set_rate(struct clk *clk, unsigned long rate);
extern struct clk_ops s5p64x0_clkarm_ops;
extern struct clksrc_clk clk_armclk;
extern struct clksrc_clk clk_dout_mpll;
extern struct clk *clkset_hclk_low_list[];
extern struct clksrc_sources clkset_hclk_low;
extern int s5p64x0_pclk_ctrl(struct clk *clk, int enable);
extern int s5p64x0_hclk0_ctrl(struct clk *clk, int enable);
extern int s5p64x0_hclk1_ctrl(struct clk *clk, int enable);
extern int s5p64x0_sclk_ctrl(struct clk *clk, int enable);
extern int s5p64x0_sclk1_ctrl(struct clk *clk, int enable);
extern int s5p64x0_mem_ctrl(struct clk *clk, int enable);
extern int s5p64x0_clk48m_ctrl(struct clk *clk, int enable);
#endif /* __ASM_ARCH_CLOCK_H */
|
JijonHyuni/HyperKernel-JB
|
virt/arch/arm/mach-s5p64x0/include/mach/s5p64x0-clock.h
|
C
|
gpl-2.0
| 1,596
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var stdin = require('get-stdin');
var pkg = require('./package.json');
var stripIndent = require('./');
var argv = process.argv.slice(2);
var input = argv[0];
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Usage',
' strip-indent <file>',
' echo <string> | strip-indent',
'',
' Example',
' echo \'\\tunicorn\\n\\t\\tcake\' | strip-indent',
' unicorn',
' \tcake'
].join('\n'));
}
function init(data) {
console.log(stripIndent(data));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
if (process.stdin.isTTY) {
if (!input) {
help();
return;
}
init(fs.readFileSync(input, 'utf8'));
} else {
stdin(init);
}
|
yuyang545262477/Resume
|
项目三jQueryMobile/node_modules/strip-indent/cli.js
|
JavaScript
|
mit
| 823
|
/*
* Copyright 2008 Analog Devices Inc.
*
* Licensed under the GPL-2 or later
*/
#ifndef _BF518_IRQ_H_
#define _BF518_IRQ_H_
#include <mach-common/irq.h>
#define NR_PERI_INTS (2 * 32)
#define IRQ_PLL_WAKEUP BFIN_IRQ(0) /* PLL Wakeup Interrupt */
#define IRQ_DMA0_ERROR BFIN_IRQ(1) /* DMA Error 0 (generic) */
#define IRQ_DMAR0_BLK BFIN_IRQ(2) /* DMAR0 Block Interrupt */
#define IRQ_DMAR1_BLK BFIN_IRQ(3) /* DMAR1 Block Interrupt */
#define IRQ_DMAR0_OVR BFIN_IRQ(4) /* DMAR0 Overflow Error */
#define IRQ_DMAR1_OVR BFIN_IRQ(5) /* DMAR1 Overflow Error */
#define IRQ_PPI_ERROR BFIN_IRQ(6) /* PPI Error */
#define IRQ_MAC_ERROR BFIN_IRQ(7) /* MAC Status */
#define IRQ_SPORT0_ERROR BFIN_IRQ(8) /* SPORT0 Status */
#define IRQ_SPORT1_ERROR BFIN_IRQ(9) /* SPORT1 Status */
#define IRQ_PTP_ERROR BFIN_IRQ(10) /* PTP Error Interrupt */
#define IRQ_UART0_ERROR BFIN_IRQ(12) /* UART0 Status */
#define IRQ_UART1_ERROR BFIN_IRQ(13) /* UART1 Status */
#define IRQ_RTC BFIN_IRQ(14) /* RTC */
#define IRQ_PPI BFIN_IRQ(15) /* DMA Channel 0 (PPI) */
#define IRQ_SPORT0_RX BFIN_IRQ(16) /* DMA 3 Channel (SPORT0 RX) */
#define IRQ_SPORT0_TX BFIN_IRQ(17) /* DMA 4 Channel (SPORT0 TX) */
#define IRQ_RSI BFIN_IRQ(17) /* DMA 4 Channel (RSI) */
#define IRQ_SPORT1_RX BFIN_IRQ(18) /* DMA 5 Channel (SPORT1 RX/SPI) */
#define IRQ_SPI1 BFIN_IRQ(18) /* DMA 5 Channel (SPI1) */
#define IRQ_SPORT1_TX BFIN_IRQ(19) /* DMA 6 Channel (SPORT1 TX) */
#define IRQ_TWI BFIN_IRQ(20) /* TWI */
#define IRQ_SPI0 BFIN_IRQ(21) /* DMA 7 Channel (SPI0) */
#define IRQ_UART0_RX BFIN_IRQ(22) /* DMA8 Channel (UART0 RX) */
#define IRQ_UART0_TX BFIN_IRQ(23) /* DMA9 Channel (UART0 TX) */
#define IRQ_UART1_RX BFIN_IRQ(24) /* DMA10 Channel (UART1 RX) */
#define IRQ_UART1_TX BFIN_IRQ(25) /* DMA11 Channel (UART1 TX) */
#define IRQ_OPTSEC BFIN_IRQ(26) /* OTPSEC Interrupt */
#define IRQ_CNT BFIN_IRQ(27) /* GP Counter */
#define IRQ_MAC_RX BFIN_IRQ(28) /* DMA1 Channel (MAC RX) */
#define IRQ_PORTH_INTA BFIN_IRQ(29) /* Port H Interrupt A */
#define IRQ_MAC_TX BFIN_IRQ(30) /* DMA2 Channel (MAC TX) */
#define IRQ_PORTH_INTB BFIN_IRQ(31) /* Port H Interrupt B */
#define IRQ_TIMER0 BFIN_IRQ(32) /* Timer 0 */
#define IRQ_TIMER1 BFIN_IRQ(33) /* Timer 1 */
#define IRQ_TIMER2 BFIN_IRQ(34) /* Timer 2 */
#define IRQ_TIMER3 BFIN_IRQ(35) /* Timer 3 */
#define IRQ_TIMER4 BFIN_IRQ(36) /* Timer 4 */
#define IRQ_TIMER5 BFIN_IRQ(37) /* Timer 5 */
#define IRQ_TIMER6 BFIN_IRQ(38) /* Timer 6 */
#define IRQ_TIMER7 BFIN_IRQ(39) /* Timer 7 */
#define IRQ_PORTG_INTA BFIN_IRQ(40) /* Port G Interrupt A */
#define IRQ_PORTG_INTB BFIN_IRQ(41) /* Port G Interrupt B */
#define IRQ_MEM_DMA0 BFIN_IRQ(42) /* MDMA Stream 0 */
#define IRQ_MEM_DMA1 BFIN_IRQ(43) /* MDMA Stream 1 */
#define IRQ_WATCH BFIN_IRQ(44) /* Software Watchdog Timer */
#define IRQ_PORTF_INTA BFIN_IRQ(45) /* Port F Interrupt A */
#define IRQ_PORTF_INTB BFIN_IRQ(46) /* Port F Interrupt B */
#define IRQ_SPI0_ERROR BFIN_IRQ(47) /* SPI0 Status */
#define IRQ_SPI1_ERROR BFIN_IRQ(48) /* SPI1 Error */
#define IRQ_RSI_INT0 BFIN_IRQ(51) /* RSI Interrupt0 */
#define IRQ_RSI_INT1 BFIN_IRQ(52) /* RSI Interrupt1 */
#define IRQ_PWM_TRIP BFIN_IRQ(53) /* PWM Trip Interrupt */
#define IRQ_PWM_SYNC BFIN_IRQ(54) /* PWM Sync Interrupt */
#define IRQ_PTP_STAT BFIN_IRQ(55) /* PTP Stat Interrupt */
#define SYS_IRQS BFIN_IRQ(63) /* 70 */
#define IRQ_PF0 71
#define IRQ_PF1 72
#define IRQ_PF2 73
#define IRQ_PF3 74
#define IRQ_PF4 75
#define IRQ_PF5 76
#define IRQ_PF6 77
#define IRQ_PF7 78
#define IRQ_PF8 79
#define IRQ_PF9 80
#define IRQ_PF10 81
#define IRQ_PF11 82
#define IRQ_PF12 83
#define IRQ_PF13 84
#define IRQ_PF14 85
#define IRQ_PF15 86
#define IRQ_PG0 87
#define IRQ_PG1 88
#define IRQ_PG2 89
#define IRQ_PG3 90
#define IRQ_PG4 91
#define IRQ_PG5 92
#define IRQ_PG6 93
#define IRQ_PG7 94
#define IRQ_PG8 95
#define IRQ_PG9 96
#define IRQ_PG10 97
#define IRQ_PG11 98
#define IRQ_PG12 99
#define IRQ_PG13 100
#define IRQ_PG14 101
#define IRQ_PG15 102
#define IRQ_PH0 103
#define IRQ_PH1 104
#define IRQ_PH2 105
#define IRQ_PH3 106
#define IRQ_PH4 107
#define IRQ_PH5 108
#define IRQ_PH6 109
#define IRQ_PH7 110
#define IRQ_PH8 111
#define IRQ_PH9 112
#define IRQ_PH10 113
#define IRQ_PH11 114
#define IRQ_PH12 115
#define IRQ_PH13 116
#define IRQ_PH14 117
#define IRQ_PH15 118
#define GPIO_IRQ_BASE IRQ_PF0
#define IRQ_MAC_PHYINT 119 /* PHY_INT Interrupt */
#define IRQ_MAC_MMCINT 120 /* MMC Counter Interrupt */
#define IRQ_MAC_RXFSINT 121 /* RX Frame-Status Interrupt */
#define IRQ_MAC_TXFSINT 122 /* TX Frame-Status Interrupt */
#define IRQ_MAC_WAKEDET 123 /* Wake-Up Interrupt */
#define IRQ_MAC_RXDMAERR 124 /* RX DMA Direction Error Interrupt */
#define IRQ_MAC_TXDMAERR 125 /* TX DMA Direction Error Interrupt */
#define IRQ_MAC_STMDONE 126 /* Station Mgt. Transfer Done Interrupt */
#define NR_MACH_IRQS (IRQ_MAC_STMDONE + 1)
/* IAR0 BIT FIELDS */
#define IRQ_PLL_WAKEUP_POS 0
#define IRQ_DMA0_ERROR_POS 4
#define IRQ_DMAR0_BLK_POS 8
#define IRQ_DMAR1_BLK_POS 12
#define IRQ_DMAR0_OVR_POS 16
#define IRQ_DMAR1_OVR_POS 20
#define IRQ_PPI_ERROR_POS 24
#define IRQ_MAC_ERROR_POS 28
/* IAR1 BIT FIELDS */
#define IRQ_SPORT0_ERROR_POS 0
#define IRQ_SPORT1_ERROR_POS 4
#define IRQ_PTP_ERROR_POS 8
#define IRQ_UART0_ERROR_POS 16
#define IRQ_UART1_ERROR_POS 20
#define IRQ_RTC_POS 24
#define IRQ_PPI_POS 28
/* IAR2 BIT FIELDS */
#define IRQ_SPORT0_RX_POS 0
#define IRQ_SPORT0_TX_POS 4
#define IRQ_RSI_POS 4
#define IRQ_SPORT1_RX_POS 8
#define IRQ_SPI1_POS 8
#define IRQ_SPORT1_TX_POS 12
#define IRQ_TWI_POS 16
#define IRQ_SPI0_POS 20
#define IRQ_UART0_RX_POS 24
#define IRQ_UART0_TX_POS 28
/* IAR3 BIT FIELDS */
#define IRQ_UART1_RX_POS 0
#define IRQ_UART1_TX_POS 4
#define IRQ_OPTSEC_POS 8
#define IRQ_CNT_POS 12
#define IRQ_MAC_RX_POS 16
#define IRQ_PORTH_INTA_POS 20
#define IRQ_MAC_TX_POS 24
#define IRQ_PORTH_INTB_POS 28
/* IAR4 BIT FIELDS */
#define IRQ_TIMER0_POS 0
#define IRQ_TIMER1_POS 4
#define IRQ_TIMER2_POS 8
#define IRQ_TIMER3_POS 12
#define IRQ_TIMER4_POS 16
#define IRQ_TIMER5_POS 20
#define IRQ_TIMER6_POS 24
#define IRQ_TIMER7_POS 28
/* IAR5 BIT FIELDS */
#define IRQ_PORTG_INTA_POS 0
#define IRQ_PORTG_INTB_POS 4
#define IRQ_MEM_DMA0_POS 8
#define IRQ_MEM_DMA1_POS 12
#define IRQ_WATCH_POS 16
#define IRQ_PORTF_INTA_POS 20
#define IRQ_PORTF_INTB_POS 24
#define IRQ_SPI0_ERROR_POS 28
/* IAR6 BIT FIELDS */
#define IRQ_SPI1_ERROR_POS 0
#define IRQ_RSI_INT0_POS 12
#define IRQ_RSI_INT1_POS 16
#define IRQ_PWM_TRIP_POS 20
#define IRQ_PWM_SYNC_POS 24
#define IRQ_PTP_STAT_POS 28
#endif
|
AiJiaZone/linux-4.0
|
virt/arch/blackfin/mach-bf518/include/mach/irq.h
|
C
|
gpl-2.0
| 6,694
|
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: var_export.php,v 1.2 2005/11/21 10:57:23 ggiunta Exp $
/**
* Replace var_export()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.var_export
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.2 $
* @since PHP 4.2.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('var_export')) {
function var_export($array, $return = false, $lvl=0)
{
// Common output variables
$indent = ' ';
$doublearrow = ' => ';
$lineend = ",\n";
$stringdelim = '\'';
// Check the export isn't a simple string / int
if (is_string($array)) {
$out = $stringdelim . str_replace('\'', '\\\'', str_replace('\\', '\\\\', $array)) . $stringdelim;
} elseif (is_int($array) || is_float($array)) {
$out = (string)$array;
} elseif (is_bool($array)) {
$out = $array ? 'true' : 'false';
} elseif (is_null($array)) {
$out = 'NULL';
} elseif (is_resource($array)) {
$out = 'resource';
} else {
// Begin the array export
// Start the string
$out = "array (\n";
// Loop through each value in array
foreach ($array as $key => $value) {
// If the key is a string, delimit it
if (is_string($key)) {
$key = str_replace('\'', '\\\'', str_replace('\\', '\\\\', $key));
$key = $stringdelim . $key . $stringdelim;
}
$val = var_export($value, true, $lvl+1);
// Delimit value
/*if (is_array($value)) {
// We have an array, so do some recursion
// Do some basic recursion while increasing the indent
$recur_array = explode($newline, var_export($value, true));
$temp_array = array();
foreach ($recur_array as $recur_line) {
$temp_array[] = $indent . $recur_line;
}
$recur_array = implode($newline, $temp_array);
$value = $newline . $recur_array;
} elseif (is_null($value)) {
$value = 'NULL';
} else {
$value = str_replace($find, $replace, $value);
$value = $stringdelim . $value . $stringdelim;
}*/
// Piece together the line
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= $key . $doublearrow . $val . $lineend;
}
// End our string
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= ")";
}
// Decide method of output
if ($return === true) {
return $out;
} else {
echo $out;
return;
}
}
}
?>
|
heqiaoliu/Viral-Dark-Matter
|
tmp/install_4f209c9de9bf1/libraries/phpxmlrpc/compat/var_export.php
|
PHP
|
gpl-2.0
| 4,172
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.hadoop.hdfs.util;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import org.junit.Test;
public class TestCyclicIteration {
@Test
public void testCyclicIteration() throws Exception {
for(int n = 0; n < 5; n++) {
checkCyclicIteration(n);
}
}
private static void checkCyclicIteration(int numOfElements) {
//create a tree map
final NavigableMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
final Integer[] integers = new Integer[numOfElements];
for(int i = 0; i < integers.length; i++) {
integers[i] = 2*i;
map.put(integers[i], integers[i]);
}
System.out.println("\n\nintegers=" + Arrays.asList(integers));
System.out.println("map=" + map);
//try starting everywhere
for(int start = -1; start <= 2*integers.length - 1; start++) {
//get a cyclic iteration
final List<Integer> iteration = new ArrayList<Integer>();
for(Map.Entry<Integer, Integer> e : new CyclicIteration<Integer, Integer>(map, start)) {
iteration.add(e.getKey());
}
System.out.println("start=" + start + ", iteration=" + iteration);
//verify results
for(int i = 0; i < integers.length; i++) {
final int j = ((start+2)/2 + i)%integers.length;
assertEquals("i=" + i + ", j=" + j, iteration.get(i), integers[j]);
}
}
}
}
|
tseen/Federated-HDFS
|
tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/util/TestCyclicIteration.java
|
Java
|
apache-2.0
| 2,331
|
"""
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TaggedItem(models.Model):
"""A tag on an item."""
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
class Meta:
ordering = ["tag", "content_type__model"]
def __str__(self):
return self.tag
class ValuableTaggedItem(TaggedItem):
value = models.PositiveIntegerField()
class AbstractComparison(models.Model):
comparative = models.CharField(max_length=50)
content_type1 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative1_set")
object_id1 = models.PositiveIntegerField()
first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
@python_2_unicode_compatible
class Comparison(AbstractComparison):
"""
A model that tests having multiple GenericForeignKeys. One is defined
through an inherited abstract model and one defined directly on this class.
"""
content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set")
object_id2 = models.PositiveIntegerField()
other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
def __str__(self):
return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
@python_2_unicode_compatible
class Animal(models.Model):
common_name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
tags = GenericRelation(TaggedItem, related_query_name='animal')
comparisons = GenericRelation(Comparison,
object_id_field="object_id1",
content_type_field="content_type1")
def __str__(self):
return self.common_name
@python_2_unicode_compatible
class Vegetable(models.Model):
name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True)
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Mineral(models.Model):
name = models.CharField(max_length=150)
hardness = models.PositiveSmallIntegerField()
# note the lack of an explicit GenericRelation here...
def __str__(self):
return self.name
class GeckoManager(models.Manager):
def get_queryset(self):
return super(GeckoManager, self).get_queryset().filter(has_tail=True)
class Gecko(models.Model):
has_tail = models.BooleanField(default=False)
objects = GeckoManager()
# To test fix for #11263
class Rock(Mineral):
tags = GenericRelation(TaggedItem)
class ManualPK(models.Model):
id = models.IntegerField(primary_key=True)
tags = GenericRelation(TaggedItem, related_query_name='manualpk')
class ForProxyModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey(for_concrete_model=False)
title = models.CharField(max_length=255, null=True)
class ForConcreteModelModel(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
obj = GenericForeignKey()
class ConcreteRelatedModel(models.Model):
bases = GenericRelation(ForProxyModelModel, for_concrete_model=False)
class ProxyRelatedModel(ConcreteRelatedModel):
class Meta:
proxy = True
# To test fix for #7551
class AllowsNullGFK(models.Model):
content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey()
|
megaumi/django
|
tests/generic_relations/models.py
|
Python
|
bsd-3-clause
| 4,327
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Tests\Loader;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
class AnnotationClassLoaderTest extends AbstractAnnotationLoaderTest
{
protected $loader;
protected function setUp()
{
parent::setUp();
$this->loader = $this->getClassLoader($this->getReader());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLoadMissingClass()
{
$this->loader->load('MissingClass');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testLoadAbstractClass()
{
$this->loader->load('Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\AbstractClass');
}
/**
* @covers Symfony\Component\Routing\Loader\AnnotationClassLoader::supports
* @dataProvider provideTestSupportsChecksResource
*/
public function testSupportsChecksResource($resource, $expectedSupports)
{
$this->assertSame($expectedSupports, $this->loader->supports($resource), '->supports() returns true if the resource is loadable');
}
public function provideTestSupportsChecksResource()
{
return array(
array('class', true),
array('\fully\qualified\class\name', true),
array('namespaced\class\without\leading\slash', true),
array('ÿClassWithLegalSpecialCharacters', true),
array('5', false),
array('foo.foo', false),
array(null, false),
);
}
/**
* @covers Symfony\Component\Routing\Loader\AnnotationClassLoader::supports
*/
public function testSupportsChecksTypeIfSpecified()
{
$this->assertTrue($this->loader->supports('class', 'annotation'), '->supports() checks the resource type if specified');
$this->assertFalse($this->loader->supports('class', 'foo'), '->supports() checks the resource type if specified');
}
}
|
savez/presence-detector
|
ws/vendor/symfony/routing/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.php
|
PHP
|
gpl-2.0
| 2,200
|
/*
* FancyBox - jQuery Plugin
* Simple and fancy lightbox alternative
*
* Examples and documentation at: http://fancybox.net
*
* Copyright (c) 2008 - 2010 Janis Skarnelis
* That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
*
* Version: 1.3.4 (11/11/2010)
* Requires: jQuery v1.3+
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right,
selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],
ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,
loadingTimer, loadingFrame = 1,
titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),
isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
/*
* Private methods
*/
_abort = function() {
loading.hide();
imgPreloader.onerror = imgPreloader.onload = null;
if (ajaxLoader) {
ajaxLoader.abort();
}
tmp.empty();
},
_error = function() {
if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) {
loading.hide();
busy = false;
return;
}
selectedOpts.titleShow = false;
selectedOpts.width = 'auto';
selectedOpts.height = 'auto';
tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' );
_process_inline();
},
_start = function() {
var obj = selectedArray[ selectedIndex ],
href,
type,
title,
str,
emb,
ret;
_abort();
selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts);
if (ret === false) {
busy = false;
return;
} else if (typeof ret == 'object') {
selectedOpts = $.extend(selectedOpts, ret);
}
title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || '';
if (obj.nodeName && !selectedOpts.orig) {
selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
}
if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) {
title = selectedOpts.orig.attr('alt');
}
href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null;
if ((/^(?:javascript)/i).test(href) || href == '#') {
href = null;
}
if (selectedOpts.type) {
type = selectedOpts.type;
if (!href) {
href = selectedOpts.content;
}
} else if (selectedOpts.content) {
type = 'html';
} else if (href) {
if (href.match(imgRegExp)) {
type = 'image';
} else if (href.match(swfRegExp)) {
type = 'swf';
} else if ($(obj).hasClass("iframe")) {
type = 'iframe';
} else if (href.indexOf("#") === 0) {
type = 'inline';
} else {
type = 'ajax';
}
}
if (!type) {
_error();
return;
}
if (type == 'inline') {
obj = href.substr(href.indexOf("#"));
type = $(obj).length > 0 ? 'inline' : 'ajax';
}
selectedOpts.type = type;
selectedOpts.href = href;
selectedOpts.title = title;
if (selectedOpts.autoDimensions) {
if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') {
selectedOpts.width = 'auto';
selectedOpts.height = 'auto';
} else {
selectedOpts.autoDimensions = false;
}
}
if (selectedOpts.modal) {
selectedOpts.overlayShow = true;
selectedOpts.hideOnOverlayClick = false;
selectedOpts.hideOnContentClick = false;
selectedOpts.enableEscapeButton = false;
selectedOpts.showCloseButton = false;
}
selectedOpts.padding = parseInt(selectedOpts.padding, 10);
selectedOpts.margin = parseInt(selectedOpts.margin, 10);
tmp.css('padding', (selectedOpts.padding + selectedOpts.margin));
$('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
$(this).replaceWith(content.children());
});
switch (type) {
case 'html' :
tmp.html( selectedOpts.content );
_process_inline();
break;
case 'inline' :
if ( $(obj).parent().is('#fancybox-content') === true) {
busy = false;
return;
}
$('<div class="fancybox-inline-tmp" />')
.hide()
.insertBefore( $(obj) )
.bind('fancybox-cleanup', function() {
$(this).replaceWith(content.children());
}).bind('fancybox-cancel', function() {
$(this).replaceWith(tmp.children());
});
$(obj).appendTo(tmp);
_process_inline();
break;
case 'image':
busy = false;
$.fancybox.showActivity();
imgPreloader = new Image();
imgPreloader.onerror = function() {
_error();
};
imgPreloader.onload = function() {
busy = true;
imgPreloader.onerror = imgPreloader.onload = null;
_process_image();
};
imgPreloader.src = href;
break;
case 'swf':
selectedOpts.scrolling = 'no';
str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
emb = '';
$.each(selectedOpts.swf, function(name, val) {
str += '<param name="' + name + '" value="' + val + '"></param>';
emb += ' ' + name + '="' + val + '"';
});
str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';
tmp.html(str);
_process_inline();
break;
case 'ajax':
busy = false;
$.fancybox.showActivity();
selectedOpts.ajax.win = selectedOpts.ajax.success;
ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, {
url : href,
data : selectedOpts.ajax.data || {},
error : function(XMLHttpRequest, textStatus, errorThrown) {
if ( XMLHttpRequest.status > 0 ) {
_error();
}
},
success : function(data, textStatus, XMLHttpRequest) {
var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader;
if (o.status == 200) {
if ( typeof selectedOpts.ajax.win == 'function' ) {
ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest);
if (ret === false) {
loading.hide();
return;
} else if (typeof ret == 'string' || typeof ret == 'object') {
data = ret;
}
}
tmp.html( data );
_process_inline();
}
}
}));
break;
case 'iframe':
_show();
break;
}
},
_process_inline = function() {
var
w = selectedOpts.width,
h = selectedOpts.height;
if (w.toString().indexOf('%') > -1) {
w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px';
} else {
w = w == 'auto' ? 'auto' : w + 'px';
}
if (h.toString().indexOf('%') > -1) {
h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px';
} else {
h = h == 'auto' ? 'auto' : h + 'px';
}
tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>');
selectedOpts.width = tmp.width();
selectedOpts.height = tmp.height();
_show();
},
_process_image = function() {
selectedOpts.width = imgPreloader.width;
selectedOpts.height = imgPreloader.height;
$("<img />").attr({
'id' : 'fancybox-img',
'src' : imgPreloader.src,
'alt' : selectedOpts.title
}).appendTo( tmp );
_show();
},
_show = function() {
var pos, equal;
loading.hide();
if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
$.event.trigger('fancybox-cancel');
busy = false;
return;
}
busy = true;
$(content.add( overlay )).unbind();
$(window).unbind("resize.fb scroll.fb");
$(document).unbind('keydown.fb');
if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') {
wrap.css('height', wrap.height());
}
currentArray = selectedArray;
currentIndex = selectedIndex;
currentOpts = selectedOpts;
if (currentOpts.overlayShow) {
overlay.css({
'background-color' : currentOpts.overlayColor,
'opacity' : currentOpts.overlayOpacity,
'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
'height' : $(document).height()
});
if (!overlay.is(':visible')) {
if (isIE6) {
$('select:not(#fancybox-tmp select)').filter(function() {
return this.style.visibility !== 'hidden';
}).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() {
this.style.visibility = 'inherit';
});
}
overlay.show();
}
} else {
overlay.hide();
}
final_pos = _get_zoom_to();
_process_title();
if (wrap.is(":visible")) {
$( close.add( nav_left ).add( nav_right ) ).hide();
pos = wrap.position(),
start_pos = {
top : pos.top,
left : pos.left,
width : wrap.width(),
height : wrap.height()
};
equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);
content.fadeTo(currentOpts.changeFade, 0.3, function() {
var finish_resizing = function() {
content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
};
$.event.trigger('fancybox-change');
content
.empty()
.removeAttr('filter')
.css({
'border-width' : currentOpts.padding,
'width' : final_pos.width - currentOpts.padding * 2,
'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
});
if (equal) {
finish_resizing();
} else {
fx.prop = 0;
$(fx).animate({prop: 1}, {
duration : currentOpts.changeSpeed,
easing : currentOpts.easingChange,
step : _draw,
complete : finish_resizing
});
}
});
return;
}
wrap.removeAttr("style");
content.css('border-width', currentOpts.padding);
if (currentOpts.transitionIn == 'elastic') {
start_pos = _get_zoom_from();
content.html( tmp.contents() );
wrap.show();
if (currentOpts.opacity) {
final_pos.opacity = 0;
}
fx.prop = 0;
$(fx).animate({prop: 1}, {
duration : currentOpts.speedIn,
easing : currentOpts.easingIn,
step : _draw,
complete : _finish
});
return;
}
if (currentOpts.titlePosition == 'inside' && titleHeight > 0) {
title.show();
}
content
.css({
'width' : final_pos.width - currentOpts.padding * 2,
'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
})
.html( tmp.contents() );
wrap
.css(final_pos)
.fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
},
_format_title = function(title) {
if (title && title.length) {
if (currentOpts.titlePosition == 'float') {
return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>';
}
return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>';
}
return false;
},
_process_title = function() {
titleStr = currentOpts.title || '';
titleHeight = 0;
title
.empty()
.removeAttr('style')
.removeClass();
if (currentOpts.titleShow === false) {
title.hide();
return;
}
titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr);
if (!titleStr || titleStr === '') {
title.hide();
return;
}
title
.addClass('fancybox-title-' + currentOpts.titlePosition)
.html( titleStr )
.appendTo( 'body' )
.show();
switch (currentOpts.titlePosition) {
case 'inside':
title
.css({
'width' : final_pos.width - (currentOpts.padding * 2),
'marginLeft' : currentOpts.padding,
'marginRight' : currentOpts.padding
});
titleHeight = title.outerHeight(true);
title.appendTo( outer );
final_pos.height += titleHeight;
break;
case 'over':
title
.css({
'marginLeft' : currentOpts.padding,
'width' : final_pos.width - (currentOpts.padding * 2),
'bottom' : currentOpts.padding
})
.appendTo( outer );
break;
case 'float':
title
.css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1)
.appendTo( wrap );
break;
default:
title
.css({
'width' : final_pos.width - (currentOpts.padding * 2),
'paddingLeft' : currentOpts.padding,
'paddingRight' : currentOpts.padding
})
.appendTo( wrap );
break;
}
title.hide();
},
_set_navigation = function() {
if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) {
$(document).bind('keydown.fb', function(e) {
if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
e.preventDefault();
$.fancybox.close();
} else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
e.preventDefault();
$.fancybox[ e.keyCode == 37 ? 'prev' : 'next']();
}
});
}
if (!currentOpts.showNavArrows) {
nav_left.hide();
nav_right.hide();
return;
}
if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
nav_left.show();
}
if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
nav_right.show();
}
},
_finish = function () {
if (!$.support.opacity) {
content.get(0).style.removeAttribute('filter');
wrap.get(0).style.removeAttribute('filter');
}
if (selectedOpts.autoDimensions) {
content.css('height', 'auto');
}
wrap.css('height', 'auto');
if (titleStr && titleStr.length) {
title.show();
}
if (currentOpts.showCloseButton) {
close.show();
}
_set_navigation();
if (currentOpts.hideOnContentClick) {
content.bind('click', $.fancybox.close);
}
if (currentOpts.hideOnOverlayClick) {
overlay.bind('click', $.fancybox.close);
}
$(window).bind("resize.fb", $.fancybox.resize);
if (currentOpts.centerOnScroll) {
$(window).bind("scroll.fb", $.fancybox.center);
}
if (currentOpts.type == 'iframe') {
$('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
}
wrap.show();
busy = false;
$.fancybox.center();
currentOpts.onComplete(currentArray, currentIndex, currentOpts);
_preload_images();
},
_preload_images = function() {
var href,
objNext;
if ((currentArray.length -1) > currentIndex) {
href = currentArray[ currentIndex + 1 ].href;
if (typeof href !== 'undefined' && href.match(imgRegExp)) {
objNext = new Image();
objNext.src = href;
}
}
if (currentIndex > 0) {
href = currentArray[ currentIndex - 1 ].href;
if (typeof href !== 'undefined' && href.match(imgRegExp)) {
objNext = new Image();
objNext.src = href;
}
}
},
_draw = function(pos) {
var dim = {
width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10),
height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10),
top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10),
left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10)
};
if (typeof final_pos.opacity !== 'undefined') {
dim.opacity = pos < 0.5 ? 0.5 : pos;
}
wrap.css(dim);
content.css({
'width' : dim.width - currentOpts.padding * 2,
'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2
});
},
_get_viewport = function() {
return [
$(window).width() - (currentOpts.margin * 2),
$(window).height() - (currentOpts.margin * 2),
$(document).scrollLeft() + currentOpts.margin,
$(document).scrollTop() + currentOpts.margin
];
},
_get_zoom_to = function () {
var view = _get_viewport(),
to = {},
resize = currentOpts.autoScale,
double_padding = currentOpts.padding * 2,
ratio;
if (currentOpts.width.toString().indexOf('%') > -1) {
to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10);
} else {
to.width = currentOpts.width + double_padding;
}
if (currentOpts.height.toString().indexOf('%') > -1) {
to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10);
} else {
to.height = currentOpts.height + double_padding;
}
if (resize && (to.width > view[0] || to.height > view[1])) {
if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
ratio = (currentOpts.width ) / (currentOpts.height );
if ((to.width ) > view[0]) {
to.width = view[0];
to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10);
}
if ((to.height) > view[1]) {
to.height = view[1];
to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10);
}
} else {
to.width = Math.min(to.width, view[0]);
to.height = Math.min(to.height, view[1]);
}
}
to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10);
to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10);
return to;
},
_get_obj_pos = function(obj) {
var pos = obj.offset();
pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0;
pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0;
pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0;
pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0;
pos.width = obj.width();
pos.height = obj.height();
return pos;
},
_get_zoom_from = function() {
var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
from = {},
pos,
view;
if (orig && orig.length) {
pos = _get_obj_pos(orig);
from = {
width : pos.width + (currentOpts.padding * 2),
height : pos.height + (currentOpts.padding * 2),
top : pos.top - currentOpts.padding - 20,
left : pos.left - currentOpts.padding - 20
};
} else {
view = _get_viewport();
from = {
width : currentOpts.padding * 2,
height : currentOpts.padding * 2,
top : parseInt(view[3] + view[1] * 0.5, 10),
left : parseInt(view[2] + view[0] * 0.5, 10)
};
}
return from;
},
_animate_loading = function() {
if (!loading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$('div', loading).css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
/*
* Public methods
*/
$.fn.fancybox = function(options) {
if (!$(this).length) {
return this;
}
$(this)
.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
.unbind('click.fb')
.bind('click.fb', function(e) {
e.preventDefault();
if (busy) {
return;
}
busy = true;
$(this).blur();
selectedArray = [];
selectedIndex = 0;
var rel = $(this).attr('rel') || '';
if (!rel || rel == '' || rel === 'nofollow') {
selectedArray.push(this);
} else {
selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
selectedIndex = selectedArray.index( this );
}
_start();
return;
});
return this;
};
$.fancybox = function(obj) {
var opts;
if (busy) {
return;
}
busy = true;
opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};
selectedArray = [];
selectedIndex = parseInt(opts.index, 10) || 0;
if ($.isArray(obj)) {
for (var i = 0, j = obj.length; i < j; i++) {
if (typeof obj[i] == 'object') {
$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
} else {
obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
}
}
selectedArray = jQuery.merge(selectedArray, obj);
} else {
if (typeof obj == 'object') {
$(obj).data('fancybox', $.extend({}, opts, obj));
} else {
obj = $({}).data('fancybox', $.extend({content : obj}, opts));
}
selectedArray.push(obj);
}
if (selectedIndex > selectedArray.length || selectedIndex < 0) {
selectedIndex = 0;
}
_start();
};
$.fancybox.showActivity = function() {
clearInterval(loadingTimer);
loading.show();
loadingTimer = setInterval(_animate_loading, 66);
};
$.fancybox.hideActivity = function() {
loading.hide();
};
$.fancybox.next = function() {
return $.fancybox.pos( currentIndex + 1);
};
$.fancybox.prev = function() {
return $.fancybox.pos( currentIndex - 1);
};
$.fancybox.pos = function(pos) {
if (busy) {
return;
}
pos = parseInt(pos);
selectedArray = currentArray;
if (pos > -1 && pos < currentArray.length) {
selectedIndex = pos;
_start();
} else if (currentOpts.cyclic && currentArray.length > 1) {
selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1;
_start();
}
return;
};
$.fancybox.cancel = function() {
if (busy) {
return;
}
busy = true;
$.event.trigger('fancybox-cancel');
_abort();
selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
busy = false;
};
// Note: within an iframe use - parent.$.fancybox.close();
$.fancybox.close = function() {
if (busy || wrap.is(':hidden')) {
return;
}
busy = true;
if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
busy = false;
return;
}
_abort();
$(close.add( nav_left ).add( nav_right )).hide();
$(content.add( overlay )).unbind();
$(window).unbind("resize.fb scroll.fb");
$(document).unbind('keydown.fb');
content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank');
if (currentOpts.titlePosition !== 'inside') {
title.empty();
}
wrap.stop();
function _cleanup() {
overlay.fadeOut('fast');
title.empty().hide();
wrap.hide();
$.event.trigger('fancybox-cleanup');
content.empty();
currentOpts.onClosed(currentArray, currentIndex, currentOpts);
currentArray = selectedOpts = [];
currentIndex = selectedIndex = 0;
currentOpts = selectedOpts = {};
busy = false;
}
if (currentOpts.transitionOut == 'elastic') {
start_pos = _get_zoom_from();
var pos = wrap.position();
final_pos = {
top : pos.top ,
left : pos.left,
width : wrap.width(),
height : wrap.height()
};
if (currentOpts.opacity) {
final_pos.opacity = 1;
}
title.empty().hide();
fx.prop = 1;
$(fx).animate({ prop: 0 }, {
duration : currentOpts.speedOut,
easing : currentOpts.easingOut,
step : _draw,
complete : _cleanup
});
} else {
wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
}
};
$.fancybox.resize = function() {
if (overlay.is(':visible')) {
overlay.css('height', $(document).height());
}
$.fancybox.center(true);
};
$.fancybox.center = function() {
var view, align;
if (busy) {
return;
}
align = arguments[0] === true ? 1 : 0;
view = _get_viewport();
if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) {
return;
}
wrap
.stop()
.animate({
'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)),
'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding))
}, typeof arguments[0] == 'number' ? arguments[0] : 200);
};
$.fancybox.init = function() {
if ($("#fancybox-wrap").length) {
return;
}
$('body').append(
tmp = $('<div id="fancybox-tmp"></div>'),
loading = $('<div id="fancybox-loading"><div></div></div>'),
overlay = $('<div id="fancybox-overlay"></div>'),
wrap = $('<div id="fancybox-wrap"></div>')
);
outer = $('<div id="fancybox-outer"></div>')
.append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>')
.appendTo( wrap );
outer.append(
content = $('<div id="fancybox-content"></div>'),
close = $('<a id="fancybox-close"></a>'),
title = $('<div id="fancybox-title"></div>'),
nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
);
close.click($.fancybox.close);
loading.click($.fancybox.cancel);
nav_left.click(function(e) {
e.preventDefault();
$.fancybox.prev();
});
nav_right.click(function(e) {
e.preventDefault();
$.fancybox.next();
});
if ($.fn.mousewheel) {
wrap.bind('mousewheel.fb', function(e, delta) {
if (busy) {
e.preventDefault();
} else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) {
e.preventDefault();
$.fancybox[ delta > 0 ? 'prev' : 'next']();
}
});
}
if (!$.support.opacity) {
wrap.addClass('fancybox-ie');
}
if (isIE6) {
loading.addClass('fancybox-ie6');
wrap.addClass('fancybox-ie6');
$('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer);
}
};
$.fn.fancybox.defaults = {
padding : 10,
margin : 40,
opacity : false,
modal : false,
cyclic : false,
scrolling : 'auto', // 'auto', 'yes' or 'no'
width : 560,
height : 340,
autoScale : true,
autoDimensions : true,
centerOnScroll : false,
ajax : {},
swf : { wmode: 'transparent' },
hideOnOverlayClick : true,
hideOnContentClick : false,
overlayShow : true,
overlayOpacity : 0.7,
overlayColor : '#777',
titleShow : true,
titlePosition : 'float', // 'float', 'outside', 'inside' or 'over'
titleFormat : null,
titleFromAlt : false,
transitionIn : 'fade', // 'elastic', 'fade' or 'none'
transitionOut : 'fade', // 'elastic', 'fade' or 'none'
speedIn : 300,
speedOut : 300,
changeSpeed : 300,
changeFade : 'fast',
easingIn : 'swing',
easingOut : 'swing',
showCloseButton : true,
showNavArrows : true,
enableEscapeButton : true,
enableKeyboardNav : true,
onStart : function(){},
onCancel : function(){},
onComplete : function(){},
onCleanup : function(){},
onClosed : function(){},
onError : function(){}
};
$(document).ready(function() {
$.fancybox.init();
});
})(jQuery);
|
AusQB/ABInteriors
|
www/public_html/themes/third_party/freeform/fancybox/jquery.fancybox-1.3.4.js
|
JavaScript
|
apache-2.0
| 28,243
|
/*!
{
"name": "ES5 String.prototype.contains",
"property": "contains",
"authors": ["Robert Kowalski"],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 `String.prototype.contains` per specification.
*/
define(['Modernizr', 'is'], function(Modernizr, is) {
Modernizr.addTest('contains', is(String.prototype.contains, 'function'));
});
|
CardiacAtlasProject/CAPServer2.0
|
xpacs/src/main/webapp/bower_components/modernizr/feature-detects/es6/contains.js
|
JavaScript
|
apache-2.0
| 365
|
/*
* 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.
*
* Robert Olsson <robert.olsson@its.uu.se> Uppsala Universitet
* & Swedish University of Agricultural Sciences.
*
* Jens Laas <jens.laas@data.slu.se> Swedish University of
* Agricultural Sciences.
*
* Hans Liss <hans.liss@its.uu.se> Uppsala Universitet
*
* This work is based on the LPC-trie which is originally described in:
*
* An experimental study of compression methods for dynamic tries
* Stefan Nilsson and Matti Tikkanen. Algorithmica, 33(1):19-33, 2002.
* http://www.csc.kth.se/~snilsson/software/dyntrie2/
*
*
* IP-address lookup using LC-tries. Stefan Nilsson and Gunnar Karlsson
* IEEE Journal on Selected Areas in Communications, 17(6):1083-1092, June 1999
*
*
* Code from fib_hash has been reused which includes the following header:
*
*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* IPv4 FIB: lookup engine and maintenance routines.
*
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
* 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.
*
* Substantial contributions to this work comes from:
*
* David S. Miller, <davem@davemloft.net>
* Stephen Hemminger <shemminger@osdl.org>
* Paul E. McKenney <paulmck@us.ibm.com>
* Patrick McHardy <kaber@trash.net>
*/
#define VERSION "0.409"
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/bitops.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/rcupdate.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/prefetch.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <net/route.h>
#include <net/tcp.h>
#include <net/sock.h>
#include <net/ip_fib.h>
#include "fib_lookup.h"
#define MAX_STAT_DEPTH 32
#define KEYLENGTH (8*sizeof(t_key))
typedef unsigned int t_key;
#define T_TNODE 0
#define T_LEAF 1
#define NODE_TYPE_MASK 0x1UL
#define NODE_TYPE(node) ((node)->parent & NODE_TYPE_MASK)
#define IS_TNODE(n) (!(n->parent & T_LEAF))
#define IS_LEAF(n) (n->parent & T_LEAF)
struct rt_trie_node {
unsigned long parent;
t_key key;
};
struct leaf {
unsigned long parent;
t_key key;
struct hlist_head list;
struct rcu_head rcu;
};
struct leaf_info {
struct hlist_node hlist;
struct rcu_head rcu;
int plen;
struct list_head falh;
};
struct tnode {
unsigned long parent;
t_key key;
unsigned char pos; /* 2log(KEYLENGTH) bits needed */
unsigned char bits; /* 2log(KEYLENGTH) bits needed */
unsigned int full_children; /* KEYLENGTH bits needed */
unsigned int empty_children; /* KEYLENGTH bits needed */
union {
struct rcu_head rcu;
struct work_struct work;
struct tnode *tnode_free;
};
struct rt_trie_node __rcu *child[0];
};
#ifdef CONFIG_IP_FIB_TRIE_STATS
struct trie_use_stats {
unsigned int gets;
unsigned int backtrack;
unsigned int semantic_match_passed;
unsigned int semantic_match_miss;
unsigned int null_node_hit;
unsigned int resize_node_skipped;
};
#endif
struct trie_stat {
unsigned int totdepth;
unsigned int maxdepth;
unsigned int tnodes;
unsigned int leaves;
unsigned int nullpointers;
unsigned int prefixes;
unsigned int nodesizes[MAX_STAT_DEPTH];
};
struct trie {
struct rt_trie_node __rcu *trie;
#ifdef CONFIG_IP_FIB_TRIE_STATS
struct trie_use_stats stats;
#endif
};
static void put_child(struct trie *t, struct tnode *tn, int i, struct rt_trie_node *n);
static void tnode_put_child_reorg(struct tnode *tn, int i, struct rt_trie_node *n,
int wasfull);
static struct rt_trie_node *resize(struct trie *t, struct tnode *tn);
static struct tnode *inflate(struct trie *t, struct tnode *tn);
static struct tnode *halve(struct trie *t, struct tnode *tn);
/* tnodes to free after resize(); protected by RTNL */
static struct tnode *tnode_free_head;
static size_t tnode_free_size;
/*
* synchronize_rcu after call_rcu for that many pages; it should be especially
* useful before resizing the root node with PREEMPT_NONE configs; the value was
* obtained experimentally, aiming to avoid visible slowdown.
*/
static const int sync_pages = 128;
static struct kmem_cache *fn_alias_kmem __read_mostly;
static struct kmem_cache *trie_leaf_kmem __read_mostly;
/*
* caller must hold RTNL
*/
static inline struct tnode *node_parent(const struct rt_trie_node *node)
{
unsigned long parent;
parent = rcu_dereference_index_check(node->parent, lockdep_rtnl_is_held());
return (struct tnode *)(parent & ~NODE_TYPE_MASK);
}
/*
* caller must hold RCU read lock or RTNL
*/
static inline struct tnode *node_parent_rcu(const struct rt_trie_node *node)
{
unsigned long parent;
parent = rcu_dereference_index_check(node->parent, rcu_read_lock_held() ||
lockdep_rtnl_is_held());
return (struct tnode *)(parent & ~NODE_TYPE_MASK);
}
/* Same as rcu_assign_pointer
* but that macro() assumes that value is a pointer.
*/
static inline void node_set_parent(struct rt_trie_node *node, struct tnode *ptr)
{
smp_wmb();
node->parent = (unsigned long)ptr | NODE_TYPE(node);
}
/*
* caller must hold RTNL
*/
static inline struct rt_trie_node *tnode_get_child(const struct tnode *tn, unsigned int i)
{
BUG_ON(i >= 1U << tn->bits);
return rtnl_dereference(tn->child[i]);
}
/*
* caller must hold RCU read lock or RTNL
*/
static inline struct rt_trie_node *tnode_get_child_rcu(const struct tnode *tn, unsigned int i)
{
BUG_ON(i >= 1U << tn->bits);
return rcu_dereference_rtnl(tn->child[i]);
}
static inline int tnode_child_length(const struct tnode *tn)
{
return 1 << tn->bits;
}
static inline t_key mask_pfx(t_key k, unsigned int l)
{
return (l == 0) ? 0 : k >> (KEYLENGTH-l) << (KEYLENGTH-l);
}
static inline t_key tkey_extract_bits(t_key a, unsigned int offset, unsigned int bits)
{
if (offset < KEYLENGTH)
return ((t_key)(a << offset)) >> (KEYLENGTH - bits);
else
return 0;
}
static inline int tkey_equals(t_key a, t_key b)
{
return a == b;
}
static inline int tkey_sub_equals(t_key a, int offset, int bits, t_key b)
{
if (bits == 0 || offset >= KEYLENGTH)
return 1;
bits = bits > KEYLENGTH ? KEYLENGTH : bits;
return ((a ^ b) << offset) >> (KEYLENGTH - bits) == 0;
}
static inline int tkey_mismatch(t_key a, int offset, t_key b)
{
t_key diff = a ^ b;
int i = offset;
if (!diff)
return 0;
while ((diff << i) >> (KEYLENGTH-1) == 0)
i++;
return i;
}
/*
To understand this stuff, an understanding of keys and all their bits is
necessary. Every node in the trie has a key associated with it, but not
all of the bits in that key are significant.
Consider a node 'n' and its parent 'tp'.
If n is a leaf, every bit in its key is significant. Its presence is
necessitated by path compression, since during a tree traversal (when
searching for a leaf - unless we are doing an insertion) we will completely
ignore all skipped bits we encounter. Thus we need to verify, at the end of
a potentially successful search, that we have indeed been walking the
correct key path.
Note that we can never "miss" the correct key in the tree if present by
following the wrong path. Path compression ensures that segments of the key
that are the same for all keys with a given prefix are skipped, but the
skipped part *is* identical for each node in the subtrie below the skipped
bit! trie_insert() in this implementation takes care of that - note the
call to tkey_sub_equals() in trie_insert().
if n is an internal node - a 'tnode' here, the various parts of its key
have many different meanings.
Example:
_________________________________________________________________
| i | i | i | i | i | i | i | N | N | N | S | S | S | S | S | C |
-----------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
_________________________________________________________________
| C | C | C | u | u | u | u | u | u | u | u | u | u | u | u | u |
-----------------------------------------------------------------
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
tp->pos = 7
tp->bits = 3
n->pos = 15
n->bits = 4
First, let's just ignore the bits that come before the parent tp, that is
the bits from 0 to (tp->pos-1). They are *known* but at this point we do
not use them for anything.
The bits from (tp->pos) to (tp->pos + tp->bits - 1) - "N", above - are the
index into the parent's child array. That is, they will be used to find
'n' among tp's children.
The bits from (tp->pos + tp->bits) to (n->pos - 1) - "S" - are skipped bits
for the node n.
All the bits we have seen so far are significant to the node n. The rest
of the bits are really not needed or indeed known in n->key.
The bits from (n->pos) to (n->pos + n->bits - 1) - "C" - are the index into
n's child array, and will of course be different for each child.
The rest of the bits, from (n->pos + n->bits) onward, are completely unknown
at this point.
*/
static inline void check_tnode(const struct tnode *tn)
{
WARN_ON(tn && tn->pos+tn->bits > 32);
}
static const int halve_threshold = 25;
static const int inflate_threshold = 50;
static const int halve_threshold_root = 15;
static const int inflate_threshold_root = 30;
static void __alias_free_mem(struct rcu_head *head)
{
struct fib_alias *fa = container_of(head, struct fib_alias, rcu);
kmem_cache_free(fn_alias_kmem, fa);
}
static inline void alias_free_mem_rcu(struct fib_alias *fa)
{
call_rcu(&fa->rcu, __alias_free_mem);
}
static void __leaf_free_rcu(struct rcu_head *head)
{
struct leaf *l = container_of(head, struct leaf, rcu);
kmem_cache_free(trie_leaf_kmem, l);
}
static inline void free_leaf(struct leaf *l)
{
call_rcu_bh(&l->rcu, __leaf_free_rcu);
}
static inline void free_leaf_info(struct leaf_info *leaf)
{
kfree_rcu(leaf, rcu);
}
static struct tnode *tnode_alloc(size_t size)
{
if (size <= PAGE_SIZE)
return kzalloc(size, GFP_KERNEL);
else
return vzalloc(size);
}
static void __tnode_vfree(struct work_struct *arg)
{
struct tnode *tn = container_of(arg, struct tnode, work);
vfree(tn);
}
static void __tnode_free_rcu(struct rcu_head *head)
{
struct tnode *tn = container_of(head, struct tnode, rcu);
size_t size = sizeof(struct tnode) +
(sizeof(struct rt_trie_node *) << tn->bits);
if (size <= PAGE_SIZE)
kfree(tn);
else {
INIT_WORK(&tn->work, __tnode_vfree);
schedule_work(&tn->work);
}
}
static inline void tnode_free(struct tnode *tn)
{
if (IS_LEAF(tn))
free_leaf((struct leaf *) tn);
else
call_rcu(&tn->rcu, __tnode_free_rcu);
}
static void tnode_free_safe(struct tnode *tn)
{
BUG_ON(IS_LEAF(tn));
tn->tnode_free = tnode_free_head;
tnode_free_head = tn;
tnode_free_size += sizeof(struct tnode) +
(sizeof(struct rt_trie_node *) << tn->bits);
}
static void tnode_free_flush(void)
{
struct tnode *tn;
while ((tn = tnode_free_head)) {
tnode_free_head = tn->tnode_free;
tn->tnode_free = NULL;
tnode_free(tn);
}
if (tnode_free_size >= PAGE_SIZE * sync_pages) {
tnode_free_size = 0;
synchronize_rcu();
}
}
static struct leaf *leaf_new(void)
{
struct leaf *l = kmem_cache_alloc(trie_leaf_kmem, GFP_KERNEL);
if (l) {
l->parent = T_LEAF;
INIT_HLIST_HEAD(&l->list);
}
return l;
}
static struct leaf_info *leaf_info_new(int plen)
{
struct leaf_info *li = kmalloc(sizeof(struct leaf_info), GFP_KERNEL);
if (li) {
li->plen = plen;
INIT_LIST_HEAD(&li->falh);
}
return li;
}
static struct tnode *tnode_new(t_key key, int pos, int bits)
{
size_t sz = sizeof(struct tnode) + (sizeof(struct rt_trie_node *) << bits);
struct tnode *tn = tnode_alloc(sz);
if (tn) {
tn->parent = T_TNODE;
tn->pos = pos;
tn->bits = bits;
tn->key = key;
tn->full_children = 0;
tn->empty_children = 1<<bits;
}
pr_debug("AT %p s=%zu %zu\n", tn, sizeof(struct tnode),
sizeof(struct rt_trie_node) << bits);
return tn;
}
/*
* Check whether a tnode 'n' is "full", i.e. it is an internal node
* and no bits are skipped. See discussion in dyntree paper p. 6
*/
static inline int tnode_full(const struct tnode *tn, const struct rt_trie_node *n)
{
if (n == NULL || IS_LEAF(n))
return 0;
return ((struct tnode *) n)->pos == tn->pos + tn->bits;
}
static inline void put_child(struct trie *t, struct tnode *tn, int i,
struct rt_trie_node *n)
{
tnode_put_child_reorg(tn, i, n, -1);
}
/*
* Add a child at position i overwriting the old value.
* Update the value of full_children and empty_children.
*/
static void tnode_put_child_reorg(struct tnode *tn, int i, struct rt_trie_node *n,
int wasfull)
{
struct rt_trie_node *chi = rtnl_dereference(tn->child[i]);
int isfull;
BUG_ON(i >= 1<<tn->bits);
/* update emptyChildren */
if (n == NULL && chi != NULL)
tn->empty_children++;
else if (n != NULL && chi == NULL)
tn->empty_children--;
/* update fullChildren */
if (wasfull == -1)
wasfull = tnode_full(tn, chi);
isfull = tnode_full(tn, n);
if (wasfull && !isfull)
tn->full_children--;
else if (!wasfull && isfull)
tn->full_children++;
if (n)
node_set_parent(n, tn);
rcu_assign_pointer(tn->child[i], n);
}
#define MAX_WORK 10
static struct rt_trie_node *resize(struct trie *t, struct tnode *tn)
{
int i;
struct tnode *old_tn;
int inflate_threshold_use;
int halve_threshold_use;
int max_work;
if (!tn)
return NULL;
pr_debug("In tnode_resize %p inflate_threshold=%d threshold=%d\n",
tn, inflate_threshold, halve_threshold);
/* No children */
if (tn->empty_children == tnode_child_length(tn)) {
tnode_free_safe(tn);
return NULL;
}
/* One child */
if (tn->empty_children == tnode_child_length(tn) - 1)
goto one_child;
/*
* Double as long as the resulting node has a number of
* nonempty nodes that are above the threshold.
*/
/*
* From "Implementing a dynamic compressed trie" by Stefan Nilsson of
* the Helsinki University of Technology and Matti Tikkanen of Nokia
* Telecommunications, page 6:
* "A node is doubled if the ratio of non-empty children to all
* children in the *doubled* node is at least 'high'."
*
* 'high' in this instance is the variable 'inflate_threshold'. It
* is expressed as a percentage, so we multiply it with
* tnode_child_length() and instead of multiplying by 2 (since the
* child array will be doubled by inflate()) and multiplying
* the left-hand side by 100 (to handle the percentage thing) we
* multiply the left-hand side by 50.
*
* The left-hand side may look a bit weird: tnode_child_length(tn)
* - tn->empty_children is of course the number of non-null children
* in the current node. tn->full_children is the number of "full"
* children, that is non-null tnodes with a skip value of 0.
* All of those will be doubled in the resulting inflated tnode, so
* we just count them one extra time here.
*
* A clearer way to write this would be:
*
* to_be_doubled = tn->full_children;
* not_to_be_doubled = tnode_child_length(tn) - tn->empty_children -
* tn->full_children;
*
* new_child_length = tnode_child_length(tn) * 2;
*
* new_fill_factor = 100 * (not_to_be_doubled + 2*to_be_doubled) /
* new_child_length;
* if (new_fill_factor >= inflate_threshold)
*
* ...and so on, tho it would mess up the while () loop.
*
* anyway,
* 100 * (not_to_be_doubled + 2*to_be_doubled) / new_child_length >=
* inflate_threshold
*
* avoid a division:
* 100 * (not_to_be_doubled + 2*to_be_doubled) >=
* inflate_threshold * new_child_length
*
* expand not_to_be_doubled and to_be_doubled, and shorten:
* 100 * (tnode_child_length(tn) - tn->empty_children +
* tn->full_children) >= inflate_threshold * new_child_length
*
* expand new_child_length:
* 100 * (tnode_child_length(tn) - tn->empty_children +
* tn->full_children) >=
* inflate_threshold * tnode_child_length(tn) * 2
*
* shorten again:
* 50 * (tn->full_children + tnode_child_length(tn) -
* tn->empty_children) >= inflate_threshold *
* tnode_child_length(tn)
*
*/
check_tnode(tn);
/* Keep root node larger */
if (!node_parent((struct rt_trie_node *)tn)) {
inflate_threshold_use = inflate_threshold_root;
halve_threshold_use = halve_threshold_root;
} else {
inflate_threshold_use = inflate_threshold;
halve_threshold_use = halve_threshold;
}
max_work = MAX_WORK;
while ((tn->full_children > 0 && max_work-- &&
50 * (tn->full_children + tnode_child_length(tn)
- tn->empty_children)
>= inflate_threshold_use * tnode_child_length(tn))) {
old_tn = tn;
tn = inflate(t, tn);
if (IS_ERR(tn)) {
tn = old_tn;
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.resize_node_skipped++;
#endif
break;
}
}
check_tnode(tn);
/* Return if at least one inflate is run */
if (max_work != MAX_WORK)
return (struct rt_trie_node *) tn;
/*
* Halve as long as the number of empty children in this
* node is above threshold.
*/
max_work = MAX_WORK;
while (tn->bits > 1 && max_work-- &&
100 * (tnode_child_length(tn) - tn->empty_children) <
halve_threshold_use * tnode_child_length(tn)) {
old_tn = tn;
tn = halve(t, tn);
if (IS_ERR(tn)) {
tn = old_tn;
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.resize_node_skipped++;
#endif
break;
}
}
/* Only one child remains */
if (tn->empty_children == tnode_child_length(tn) - 1) {
one_child:
for (i = 0; i < tnode_child_length(tn); i++) {
struct rt_trie_node *n;
n = rtnl_dereference(tn->child[i]);
if (!n)
continue;
/* compress one level */
node_set_parent(n, NULL);
tnode_free_safe(tn);
return n;
}
}
return (struct rt_trie_node *) tn;
}
static void tnode_clean_free(struct tnode *tn)
{
int i;
struct tnode *tofree;
for (i = 0; i < tnode_child_length(tn); i++) {
tofree = (struct tnode *)rtnl_dereference(tn->child[i]);
if (tofree)
tnode_free(tofree);
}
tnode_free(tn);
}
static struct tnode *inflate(struct trie *t, struct tnode *tn)
{
struct tnode *oldtnode = tn;
int olen = tnode_child_length(tn);
int i;
pr_debug("In inflate\n");
tn = tnode_new(oldtnode->key, oldtnode->pos, oldtnode->bits + 1);
if (!tn)
return ERR_PTR(-ENOMEM);
/*
* Preallocate and store tnodes before the actual work so we
* don't get into an inconsistent state if memory allocation
* fails. In case of failure we return the oldnode and inflate
* of tnode is ignored.
*/
for (i = 0; i < olen; i++) {
struct tnode *inode;
inode = (struct tnode *) tnode_get_child(oldtnode, i);
if (inode &&
IS_TNODE(inode) &&
inode->pos == oldtnode->pos + oldtnode->bits &&
inode->bits > 1) {
struct tnode *left, *right;
t_key m = ~0U << (KEYLENGTH - 1) >> inode->pos;
left = tnode_new(inode->key&(~m), inode->pos + 1,
inode->bits - 1);
if (!left)
goto nomem;
right = tnode_new(inode->key|m, inode->pos + 1,
inode->bits - 1);
if (!right) {
tnode_free(left);
goto nomem;
}
put_child(t, tn, 2*i, (struct rt_trie_node *) left);
put_child(t, tn, 2*i+1, (struct rt_trie_node *) right);
}
}
for (i = 0; i < olen; i++) {
struct tnode *inode;
struct rt_trie_node *node = tnode_get_child(oldtnode, i);
struct tnode *left, *right;
int size, j;
/* An empty child */
if (node == NULL)
continue;
/* A leaf or an internal node with skipped bits */
if (IS_LEAF(node) || ((struct tnode *) node)->pos >
tn->pos + tn->bits - 1) {
if (tkey_extract_bits(node->key,
oldtnode->pos + oldtnode->bits,
1) == 0)
put_child(t, tn, 2*i, node);
else
put_child(t, tn, 2*i+1, node);
continue;
}
/* An internal node with two children */
inode = (struct tnode *) node;
if (inode->bits == 1) {
put_child(t, tn, 2*i, rtnl_dereference(inode->child[0]));
put_child(t, tn, 2*i+1, rtnl_dereference(inode->child[1]));
tnode_free_safe(inode);
continue;
}
/* An internal node with more than two children */
/* We will replace this node 'inode' with two new
* ones, 'left' and 'right', each with half of the
* original children. The two new nodes will have
* a position one bit further down the key and this
* means that the "significant" part of their keys
* (see the discussion near the top of this file)
* will differ by one bit, which will be "0" in
* left's key and "1" in right's key. Since we are
* moving the key position by one step, the bit that
* we are moving away from - the bit at position
* (inode->pos) - is the one that will differ between
* left and right. So... we synthesize that bit in the
* two new keys.
* The mask 'm' below will be a single "one" bit at
* the position (inode->pos)
*/
/* Use the old key, but set the new significant
* bit to zero.
*/
left = (struct tnode *) tnode_get_child(tn, 2*i);
put_child(t, tn, 2*i, NULL);
BUG_ON(!left);
right = (struct tnode *) tnode_get_child(tn, 2*i+1);
put_child(t, tn, 2*i+1, NULL);
BUG_ON(!right);
size = tnode_child_length(left);
for (j = 0; j < size; j++) {
put_child(t, left, j, rtnl_dereference(inode->child[j]));
put_child(t, right, j, rtnl_dereference(inode->child[j + size]));
}
put_child(t, tn, 2*i, resize(t, left));
put_child(t, tn, 2*i+1, resize(t, right));
tnode_free_safe(inode);
}
tnode_free_safe(oldtnode);
return tn;
nomem:
tnode_clean_free(tn);
return ERR_PTR(-ENOMEM);
}
static struct tnode *halve(struct trie *t, struct tnode *tn)
{
struct tnode *oldtnode = tn;
struct rt_trie_node *left, *right;
int i;
int olen = tnode_child_length(tn);
pr_debug("In halve\n");
tn = tnode_new(oldtnode->key, oldtnode->pos, oldtnode->bits - 1);
if (!tn)
return ERR_PTR(-ENOMEM);
/*
* Preallocate and store tnodes before the actual work so we
* don't get into an inconsistent state if memory allocation
* fails. In case of failure we return the oldnode and halve
* of tnode is ignored.
*/
for (i = 0; i < olen; i += 2) {
left = tnode_get_child(oldtnode, i);
right = tnode_get_child(oldtnode, i+1);
/* Two nonempty children */
if (left && right) {
struct tnode *newn;
newn = tnode_new(left->key, tn->pos + tn->bits, 1);
if (!newn)
goto nomem;
put_child(t, tn, i/2, (struct rt_trie_node *)newn);
}
}
for (i = 0; i < olen; i += 2) {
struct tnode *newBinNode;
left = tnode_get_child(oldtnode, i);
right = tnode_get_child(oldtnode, i+1);
/* At least one of the children is empty */
if (left == NULL) {
if (right == NULL) /* Both are empty */
continue;
put_child(t, tn, i/2, right);
continue;
}
if (right == NULL) {
put_child(t, tn, i/2, left);
continue;
}
/* Two nonempty children */
newBinNode = (struct tnode *) tnode_get_child(tn, i/2);
put_child(t, tn, i/2, NULL);
put_child(t, newBinNode, 0, left);
put_child(t, newBinNode, 1, right);
put_child(t, tn, i/2, resize(t, newBinNode));
}
tnode_free_safe(oldtnode);
return tn;
nomem:
tnode_clean_free(tn);
return ERR_PTR(-ENOMEM);
}
/* readside must use rcu_read_lock currently dump routines
via get_fa_head and dump */
static struct leaf_info *find_leaf_info(struct leaf *l, int plen)
{
struct hlist_head *head = &l->list;
struct hlist_node *node;
struct leaf_info *li;
hlist_for_each_entry_rcu(li, node, head, hlist)
if (li->plen == plen)
return li;
return NULL;
}
static inline struct list_head *get_fa_head(struct leaf *l, int plen)
{
struct leaf_info *li = find_leaf_info(l, plen);
if (!li)
return NULL;
return &li->falh;
}
static void insert_leaf_info(struct hlist_head *head, struct leaf_info *new)
{
struct leaf_info *li = NULL, *last = NULL;
struct hlist_node *node;
if (hlist_empty(head)) {
hlist_add_head_rcu(&new->hlist, head);
} else {
hlist_for_each_entry(li, node, head, hlist) {
if (new->plen > li->plen)
break;
last = li;
}
if (last)
hlist_add_after_rcu(&last->hlist, &new->hlist);
else
hlist_add_before_rcu(&new->hlist, &li->hlist);
}
}
/* rcu_read_lock needs to be hold by caller from readside */
static struct leaf *
fib_find_node(struct trie *t, u32 key)
{
int pos;
struct tnode *tn;
struct rt_trie_node *n;
pos = 0;
n = rcu_dereference_rtnl(t->trie);
while (n != NULL && NODE_TYPE(n) == T_TNODE) {
tn = (struct tnode *) n;
check_tnode(tn);
if (tkey_sub_equals(tn->key, pos, tn->pos-pos, key)) {
pos = tn->pos + tn->bits;
n = tnode_get_child_rcu(tn,
tkey_extract_bits(key,
tn->pos,
tn->bits));
} else
break;
}
/* Case we have found a leaf. Compare prefixes */
if (n != NULL && IS_LEAF(n) && tkey_equals(key, n->key))
return (struct leaf *)n;
return NULL;
}
static void trie_rebalance(struct trie *t, struct tnode *tn)
{
int wasfull;
t_key cindex, key;
struct tnode *tp;
key = tn->key;
while (tn != NULL && (tp = node_parent((struct rt_trie_node *)tn)) != NULL) {
cindex = tkey_extract_bits(key, tp->pos, tp->bits);
wasfull = tnode_full(tp, tnode_get_child(tp, cindex));
tn = (struct tnode *) resize(t, (struct tnode *)tn);
tnode_put_child_reorg((struct tnode *)tp, cindex,
(struct rt_trie_node *)tn, wasfull);
tp = node_parent((struct rt_trie_node *) tn);
if (!tp)
rcu_assign_pointer(t->trie, (struct rt_trie_node *)tn);
tnode_free_flush();
if (!tp)
break;
tn = tp;
}
/* Handle last (top) tnode */
if (IS_TNODE(tn))
tn = (struct tnode *)resize(t, (struct tnode *)tn);
rcu_assign_pointer(t->trie, (struct rt_trie_node *)tn);
tnode_free_flush();
}
/* only used from updater-side */
static struct list_head *fib_insert_node(struct trie *t, u32 key, int plen)
{
int pos, newpos;
struct tnode *tp = NULL, *tn = NULL;
struct rt_trie_node *n;
struct leaf *l;
int missbit;
struct list_head *fa_head = NULL;
struct leaf_info *li;
t_key cindex;
pos = 0;
n = rtnl_dereference(t->trie);
/* If we point to NULL, stop. Either the tree is empty and we should
* just put a new leaf in if, or we have reached an empty child slot,
* and we should just put our new leaf in that.
* If we point to a T_TNODE, check if it matches our key. Note that
* a T_TNODE might be skipping any number of bits - its 'pos' need
* not be the parent's 'pos'+'bits'!
*
* If it does match the current key, get pos/bits from it, extract
* the index from our key, push the T_TNODE and walk the tree.
*
* If it doesn't, we have to replace it with a new T_TNODE.
*
* If we point to a T_LEAF, it might or might not have the same key
* as we do. If it does, just change the value, update the T_LEAF's
* value, and return it.
* If it doesn't, we need to replace it with a T_TNODE.
*/
while (n != NULL && NODE_TYPE(n) == T_TNODE) {
tn = (struct tnode *) n;
check_tnode(tn);
if (tkey_sub_equals(tn->key, pos, tn->pos-pos, key)) {
tp = tn;
pos = tn->pos + tn->bits;
n = tnode_get_child(tn,
tkey_extract_bits(key,
tn->pos,
tn->bits));
BUG_ON(n && node_parent(n) != tn);
} else
break;
}
/*
* n ----> NULL, LEAF or TNODE
*
* tp is n's (parent) ----> NULL or TNODE
*/
BUG_ON(tp && IS_LEAF(tp));
/* Case 1: n is a leaf. Compare prefixes */
if (n != NULL && IS_LEAF(n) && tkey_equals(key, n->key)) {
l = (struct leaf *) n;
li = leaf_info_new(plen);
if (!li)
return NULL;
fa_head = &li->falh;
insert_leaf_info(&l->list, li);
goto done;
}
l = leaf_new();
if (!l)
return NULL;
l->key = key;
li = leaf_info_new(plen);
if (!li) {
free_leaf(l);
return NULL;
}
fa_head = &li->falh;
insert_leaf_info(&l->list, li);
if (t->trie && n == NULL) {
/* Case 2: n is NULL, and will just insert a new leaf */
node_set_parent((struct rt_trie_node *)l, tp);
cindex = tkey_extract_bits(key, tp->pos, tp->bits);
put_child(t, (struct tnode *)tp, cindex, (struct rt_trie_node *)l);
} else {
/* Case 3: n is a LEAF or a TNODE and the key doesn't match. */
/*
* Add a new tnode here
* first tnode need some special handling
*/
if (tp)
pos = tp->pos+tp->bits;
else
pos = 0;
if (n) {
newpos = tkey_mismatch(key, pos, n->key);
tn = tnode_new(n->key, newpos, 1);
} else {
newpos = 0;
tn = tnode_new(key, newpos, 1); /* First tnode */
}
if (!tn) {
free_leaf_info(li);
free_leaf(l);
return NULL;
}
node_set_parent((struct rt_trie_node *)tn, tp);
missbit = tkey_extract_bits(key, newpos, 1);
put_child(t, tn, missbit, (struct rt_trie_node *)l);
put_child(t, tn, 1-missbit, n);
if (tp) {
cindex = tkey_extract_bits(key, tp->pos, tp->bits);
put_child(t, (struct tnode *)tp, cindex,
(struct rt_trie_node *)tn);
} else {
rcu_assign_pointer(t->trie, (struct rt_trie_node *)tn);
tp = tn;
}
}
if (tp && tp->pos + tp->bits > 32)
pr_warning("fib_trie"
" tp=%p pos=%d, bits=%d, key=%0x plen=%d\n",
tp, tp->pos, tp->bits, key, plen);
/* Rebalance the trie */
trie_rebalance(t, tp);
done:
return fa_head;
}
/*
* Caller must hold RTNL.
*/
int fib_table_insert(struct fib_table *tb, struct fib_config *cfg)
{
struct trie *t = (struct trie *) tb->tb_data;
struct fib_alias *fa, *new_fa;
struct list_head *fa_head = NULL;
struct fib_info *fi;
int plen = cfg->fc_dst_len;
u8 tos = cfg->fc_tos;
u32 key, mask;
int err;
struct leaf *l;
if (plen > 32)
return -EINVAL;
key = ntohl(cfg->fc_dst);
pr_debug("Insert table=%u %08x/%d\n", tb->tb_id, key, plen);
mask = ntohl(inet_make_mask(plen));
if (key & ~mask)
return -EINVAL;
key = key & mask;
fi = fib_create_info(cfg);
if (IS_ERR(fi)) {
err = PTR_ERR(fi);
goto err;
}
l = fib_find_node(t, key);
fa = NULL;
if (l) {
fa_head = get_fa_head(l, plen);
fa = fib_find_alias(fa_head, tos, fi->fib_priority);
}
/* Now fa, if non-NULL, points to the first fib alias
* with the same keys [prefix,tos,priority], if such key already
* exists or to the node before which we will insert new one.
*
* If fa is NULL, we will need to allocate a new one and
* insert to the head of f.
*
* If f is NULL, no fib node matched the destination key
* and we need to allocate a new one of those as well.
*/
if (fa && fa->fa_tos == tos &&
fa->fa_info->fib_priority == fi->fib_priority) {
struct fib_alias *fa_first, *fa_match;
err = -EEXIST;
if (cfg->fc_nlflags & NLM_F_EXCL)
goto out;
/* We have 2 goals:
* 1. Find exact match for type, scope, fib_info to avoid
* duplicate routes
* 2. Find next 'fa' (or head), NLM_F_APPEND inserts before it
*/
fa_match = NULL;
fa_first = fa;
fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
list_for_each_entry_continue(fa, fa_head, fa_list) {
if (fa->fa_tos != tos)
break;
if (fa->fa_info->fib_priority != fi->fib_priority)
break;
if (fa->fa_type == cfg->fc_type &&
fa->fa_info == fi) {
fa_match = fa;
break;
}
}
if (cfg->fc_nlflags & NLM_F_REPLACE) {
struct fib_info *fi_drop;
u8 state;
fa = fa_first;
if (fa_match) {
if (fa == fa_match)
err = 0;
goto out;
}
err = -ENOBUFS;
new_fa = kmem_cache_alloc(fn_alias_kmem, GFP_KERNEL);
if (new_fa == NULL)
goto out;
fi_drop = fa->fa_info;
new_fa->fa_tos = fa->fa_tos;
new_fa->fa_info = fi;
new_fa->fa_type = cfg->fc_type;
state = fa->fa_state;
new_fa->fa_state = state & ~FA_S_ACCESSED;
list_replace_rcu(&fa->fa_list, &new_fa->fa_list);
alias_free_mem_rcu(fa);
fib_release_info(fi_drop);
if (state & FA_S_ACCESSED)
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
rtmsg_fib(RTM_NEWROUTE, htonl(key), new_fa, plen,
tb->tb_id, &cfg->fc_nlinfo, NLM_F_REPLACE);
goto succeeded;
}
/* Error if we find a perfect match which
* uses the same scope, type, and nexthop
* information.
*/
if (fa_match)
goto out;
if (!(cfg->fc_nlflags & NLM_F_APPEND))
fa = fa_first;
}
err = -ENOENT;
if (!(cfg->fc_nlflags & NLM_F_CREATE))
goto out;
err = -ENOBUFS;
new_fa = kmem_cache_alloc(fn_alias_kmem, GFP_KERNEL);
if (new_fa == NULL)
goto out;
new_fa->fa_info = fi;
new_fa->fa_tos = tos;
new_fa->fa_type = cfg->fc_type;
new_fa->fa_state = 0;
/*
* Insert new entry to the list.
*/
if (!fa_head) {
fa_head = fib_insert_node(t, key, plen);
if (unlikely(!fa_head)) {
err = -ENOMEM;
goto out_free_new_fa;
}
}
if (!plen)
tb->tb_num_default++;
list_add_tail_rcu(&new_fa->fa_list,
(fa ? &fa->fa_list : fa_head));
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
rtmsg_fib(RTM_NEWROUTE, htonl(key), new_fa, plen, tb->tb_id,
&cfg->fc_nlinfo, 0);
succeeded:
return 0;
out_free_new_fa:
kmem_cache_free(fn_alias_kmem, new_fa);
out:
fib_release_info(fi);
err:
return err;
}
/* should be called with rcu_read_lock */
static int check_leaf(struct fib_table *tb, struct trie *t, struct leaf *l,
t_key key, const struct flowi4 *flp,
struct fib_result *res, int fib_flags)
{
struct leaf_info *li;
struct hlist_head *hhead = &l->list;
struct hlist_node *node;
hlist_for_each_entry_rcu(li, node, hhead, hlist) {
struct fib_alias *fa;
int plen = li->plen;
__be32 mask = inet_make_mask(plen);
if (l->key != (key & ntohl(mask)))
continue;
list_for_each_entry_rcu(fa, &li->falh, fa_list) {
struct fib_info *fi = fa->fa_info;
int nhsel, err;
if (fa->fa_tos && fa->fa_tos != flp->flowi4_tos)
continue;
if (fa->fa_info->fib_scope < flp->flowi4_scope)
continue;
fib_alias_accessed(fa);
err = fib_props[fa->fa_type].error;
if (err) {
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.semantic_match_passed++;
#endif
return err;
}
if (fi->fib_flags & RTNH_F_DEAD)
continue;
for (nhsel = 0; nhsel < fi->fib_nhs; nhsel++) {
const struct fib_nh *nh = &fi->fib_nh[nhsel];
if (nh->nh_flags & RTNH_F_DEAD)
continue;
if (flp->flowi4_oif && flp->flowi4_oif != nh->nh_oif)
continue;
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.semantic_match_passed++;
#endif
res->prefixlen = plen;
res->nh_sel = nhsel;
res->type = fa->fa_type;
res->scope = fa->fa_info->fib_scope;
res->fi = fi;
res->table = tb;
res->fa_head = &li->falh;
if (!(fib_flags & FIB_LOOKUP_NOREF))
atomic_inc(&res->fi->fib_clntref);
return 0;
}
}
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.semantic_match_miss++;
#endif
}
return 1;
}
int fib_table_lookup(struct fib_table *tb, const struct flowi4 *flp,
struct fib_result *res, int fib_flags)
{
struct trie *t = (struct trie *) tb->tb_data;
int ret;
struct rt_trie_node *n;
struct tnode *pn;
unsigned int pos, bits;
t_key key = ntohl(flp->daddr);
unsigned int chopped_off;
t_key cindex = 0;
unsigned int current_prefix_length = KEYLENGTH;
struct tnode *cn;
t_key pref_mismatch;
rcu_read_lock();
n = rcu_dereference(t->trie);
if (!n)
goto failed;
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.gets++;
#endif
/* Just a leaf? */
if (IS_LEAF(n)) {
ret = check_leaf(tb, t, (struct leaf *)n, key, flp, res, fib_flags);
goto found;
}
pn = (struct tnode *) n;
chopped_off = 0;
while (pn) {
pos = pn->pos;
bits = pn->bits;
if (!chopped_off)
cindex = tkey_extract_bits(mask_pfx(key, current_prefix_length),
pos, bits);
n = tnode_get_child_rcu(pn, cindex);
if (n == NULL) {
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.null_node_hit++;
#endif
goto backtrace;
}
if (IS_LEAF(n)) {
ret = check_leaf(tb, t, (struct leaf *)n, key, flp, res, fib_flags);
if (ret > 0)
goto backtrace;
goto found;
}
cn = (struct tnode *)n;
/*
* It's a tnode, and we can do some extra checks here if we
* like, to avoid descending into a dead-end branch.
* This tnode is in the parent's child array at index
* key[p_pos..p_pos+p_bits] but potentially with some bits
* chopped off, so in reality the index may be just a
* subprefix, padded with zero at the end.
* We can also take a look at any skipped bits in this
* tnode - everything up to p_pos is supposed to be ok,
* and the non-chopped bits of the index (se previous
* paragraph) are also guaranteed ok, but the rest is
* considered unknown.
*
* The skipped bits are key[pos+bits..cn->pos].
*/
/* If current_prefix_length < pos+bits, we are already doing
* actual prefix matching, which means everything from
* pos+(bits-chopped_off) onward must be zero along some
* branch of this subtree - otherwise there is *no* valid
* prefix present. Here we can only check the skipped
* bits. Remember, since we have already indexed into the
* parent's child array, we know that the bits we chopped of
* *are* zero.
*/
/* NOTA BENE: Checking only skipped bits
for the new node here */
if (current_prefix_length < pos+bits) {
if (tkey_extract_bits(cn->key, current_prefix_length,
cn->pos - current_prefix_length)
|| !(cn->child[0]))
goto backtrace;
}
/*
* If chopped_off=0, the index is fully validated and we
* only need to look at the skipped bits for this, the new,
* tnode. What we actually want to do is to find out if
* these skipped bits match our key perfectly, or if we will
* have to count on finding a matching prefix further down,
* because if we do, we would like to have some way of
* verifying the existence of such a prefix at this point.
*/
/* The only thing we can do at this point is to verify that
* any such matching prefix can indeed be a prefix to our
* key, and if the bits in the node we are inspecting that
* do not match our key are not ZERO, this cannot be true.
* Thus, find out where there is a mismatch (before cn->pos)
* and verify that all the mismatching bits are zero in the
* new tnode's key.
*/
/*
* Note: We aren't very concerned about the piece of
* the key that precede pn->pos+pn->bits, since these
* have already been checked. The bits after cn->pos
* aren't checked since these are by definition
* "unknown" at this point. Thus, what we want to see
* is if we are about to enter the "prefix matching"
* state, and in that case verify that the skipped
* bits that will prevail throughout this subtree are
* zero, as they have to be if we are to find a
* matching prefix.
*/
pref_mismatch = mask_pfx(cn->key ^ key, cn->pos);
/*
* In short: If skipped bits in this node do not match
* the search key, enter the "prefix matching"
* state.directly.
*/
if (pref_mismatch) {
int mp = KEYLENGTH - fls(pref_mismatch);
if (tkey_extract_bits(cn->key, mp, cn->pos - mp) != 0)
goto backtrace;
if (current_prefix_length >= cn->pos)
current_prefix_length = mp;
}
pn = (struct tnode *)n; /* Descend */
chopped_off = 0;
continue;
backtrace:
chopped_off++;
/* As zero don't change the child key (cindex) */
while ((chopped_off <= pn->bits)
&& !(cindex & (1<<(chopped_off-1))))
chopped_off++;
/* Decrease current_... with bits chopped off */
if (current_prefix_length > pn->pos + pn->bits - chopped_off)
current_prefix_length = pn->pos + pn->bits
- chopped_off;
/*
* Either we do the actual chop off according or if we have
* chopped off all bits in this tnode walk up to our parent.
*/
if (chopped_off <= pn->bits) {
cindex &= ~(1 << (chopped_off-1));
} else {
struct tnode *parent = node_parent_rcu((struct rt_trie_node *) pn);
if (!parent)
goto failed;
/* Get Child's index */
cindex = tkey_extract_bits(pn->key, parent->pos, parent->bits);
pn = parent;
chopped_off = 0;
#ifdef CONFIG_IP_FIB_TRIE_STATS
t->stats.backtrack++;
#endif
goto backtrace;
}
}
failed:
ret = 1;
found:
rcu_read_unlock();
return ret;
}
/*
* Remove the leaf and return parent.
*/
static void trie_leaf_remove(struct trie *t, struct leaf *l)
{
struct tnode *tp = node_parent((struct rt_trie_node *) l);
pr_debug("entering trie_leaf_remove(%p)\n", l);
if (tp) {
t_key cindex = tkey_extract_bits(l->key, tp->pos, tp->bits);
put_child(t, (struct tnode *)tp, cindex, NULL);
trie_rebalance(t, tp);
} else
rcu_assign_pointer(t->trie, NULL);
free_leaf(l);
}
/*
* Caller must hold RTNL.
*/
int fib_table_delete(struct fib_table *tb, struct fib_config *cfg)
{
struct trie *t = (struct trie *) tb->tb_data;
u32 key, mask;
int plen = cfg->fc_dst_len;
u8 tos = cfg->fc_tos;
struct fib_alias *fa, *fa_to_delete;
struct list_head *fa_head;
struct leaf *l;
struct leaf_info *li;
if (plen > 32)
return -EINVAL;
key = ntohl(cfg->fc_dst);
mask = ntohl(inet_make_mask(plen));
if (key & ~mask)
return -EINVAL;
key = key & mask;
l = fib_find_node(t, key);
if (!l)
return -ESRCH;
fa_head = get_fa_head(l, plen);
fa = fib_find_alias(fa_head, tos, 0);
if (!fa)
return -ESRCH;
pr_debug("Deleting %08x/%d tos=%d t=%p\n", key, plen, tos, t);
fa_to_delete = NULL;
fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
list_for_each_entry_continue(fa, fa_head, fa_list) {
struct fib_info *fi = fa->fa_info;
if (fa->fa_tos != tos)
break;
if ((!cfg->fc_type || fa->fa_type == cfg->fc_type) &&
(cfg->fc_scope == RT_SCOPE_NOWHERE ||
fa->fa_info->fib_scope == cfg->fc_scope) &&
(!cfg->fc_prefsrc ||
fi->fib_prefsrc == cfg->fc_prefsrc) &&
(!cfg->fc_protocol ||
fi->fib_protocol == cfg->fc_protocol) &&
fib_nh_match(cfg, fi) == 0) {
fa_to_delete = fa;
break;
}
}
if (!fa_to_delete)
return -ESRCH;
fa = fa_to_delete;
rtmsg_fib(RTM_DELROUTE, htonl(key), fa, plen, tb->tb_id,
&cfg->fc_nlinfo, 0);
l = fib_find_node(t, key);
li = find_leaf_info(l, plen);
list_del_rcu(&fa->fa_list);
if (!plen)
tb->tb_num_default--;
if (list_empty(fa_head)) {
hlist_del_rcu(&li->hlist);
free_leaf_info(li);
}
if (hlist_empty(&l->list))
trie_leaf_remove(t, l);
if (fa->fa_state & FA_S_ACCESSED)
rt_cache_flush(cfg->fc_nlinfo.nl_net, -1);
fib_release_info(fa->fa_info);
alias_free_mem_rcu(fa);
return 0;
}
static int trie_flush_list(struct list_head *head)
{
struct fib_alias *fa, *fa_node;
int found = 0;
list_for_each_entry_safe(fa, fa_node, head, fa_list) {
struct fib_info *fi = fa->fa_info;
if (fi && (fi->fib_flags & RTNH_F_DEAD)) {
list_del_rcu(&fa->fa_list);
fib_release_info(fa->fa_info);
alias_free_mem_rcu(fa);
found++;
}
}
return found;
}
static int trie_flush_leaf(struct leaf *l)
{
int found = 0;
struct hlist_head *lih = &l->list;
struct hlist_node *node, *tmp;
struct leaf_info *li = NULL;
hlist_for_each_entry_safe(li, node, tmp, lih, hlist) {
found += trie_flush_list(&li->falh);
if (list_empty(&li->falh)) {
hlist_del_rcu(&li->hlist);
free_leaf_info(li);
}
}
return found;
}
/*
* Scan for the next right leaf starting at node p->child[idx]
* Since we have back pointer, no recursion necessary.
*/
static struct leaf *leaf_walk_rcu(struct tnode *p, struct rt_trie_node *c)
{
do {
t_key idx;
if (c)
idx = tkey_extract_bits(c->key, p->pos, p->bits) + 1;
else
idx = 0;
while (idx < 1u << p->bits) {
c = tnode_get_child_rcu(p, idx++);
if (!c)
continue;
if (IS_LEAF(c)) {
prefetch(rcu_dereference_rtnl(p->child[idx]));
return (struct leaf *) c;
}
/* Rescan start scanning in new node */
p = (struct tnode *) c;
idx = 0;
}
/* Node empty, walk back up to parent */
c = (struct rt_trie_node *) p;
} while ((p = node_parent_rcu(c)) != NULL);
return NULL; /* Root of trie */
}
static struct leaf *trie_firstleaf(struct trie *t)
{
struct tnode *n = (struct tnode *)rcu_dereference_rtnl(t->trie);
if (!n)
return NULL;
if (IS_LEAF(n)) /* trie is just a leaf */
return (struct leaf *) n;
return leaf_walk_rcu(n, NULL);
}
static struct leaf *trie_nextleaf(struct leaf *l)
{
struct rt_trie_node *c = (struct rt_trie_node *) l;
struct tnode *p = node_parent_rcu(c);
if (!p)
return NULL; /* trie with just one leaf */
return leaf_walk_rcu(p, c);
}
static struct leaf *trie_leafindex(struct trie *t, int index)
{
struct leaf *l = trie_firstleaf(t);
while (l && index-- > 0)
l = trie_nextleaf(l);
return l;
}
/*
* Caller must hold RTNL.
*/
int fib_table_flush(struct fib_table *tb)
{
struct trie *t = (struct trie *) tb->tb_data;
struct leaf *l, *ll = NULL;
int found = 0;
for (l = trie_firstleaf(t); l; l = trie_nextleaf(l)) {
found += trie_flush_leaf(l);
if (ll && hlist_empty(&ll->list))
trie_leaf_remove(t, ll);
ll = l;
}
if (ll && hlist_empty(&ll->list))
trie_leaf_remove(t, ll);
pr_debug("trie_flush found=%d\n", found);
return found;
}
void fib_free_table(struct fib_table *tb)
{
kfree(tb);
}
static int fn_trie_dump_fa(t_key key, int plen, struct list_head *fah,
struct fib_table *tb,
struct sk_buff *skb, struct netlink_callback *cb)
{
int i, s_i;
struct fib_alias *fa;
__be32 xkey = htonl(key);
s_i = cb->args[5];
i = 0;
/* rcu_read_lock is hold by caller */
list_for_each_entry_rcu(fa, fah, fa_list) {
if (i < s_i) {
i++;
continue;
}
if (fib_dump_info(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq,
RTM_NEWROUTE,
tb->tb_id,
fa->fa_type,
xkey,
plen,
fa->fa_tos,
fa->fa_info, NLM_F_MULTI) < 0) {
cb->args[5] = i;
return -1;
}
i++;
}
cb->args[5] = i;
return skb->len;
}
static int fn_trie_dump_leaf(struct leaf *l, struct fib_table *tb,
struct sk_buff *skb, struct netlink_callback *cb)
{
struct leaf_info *li;
struct hlist_node *node;
int i, s_i;
s_i = cb->args[4];
i = 0;
/* rcu_read_lock is hold by caller */
hlist_for_each_entry_rcu(li, node, &l->list, hlist) {
if (i < s_i) {
i++;
continue;
}
if (i > s_i)
cb->args[5] = 0;
if (list_empty(&li->falh))
continue;
if (fn_trie_dump_fa(l->key, li->plen, &li->falh, tb, skb, cb) < 0) {
cb->args[4] = i;
return -1;
}
i++;
}
cb->args[4] = i;
return skb->len;
}
int fib_table_dump(struct fib_table *tb, struct sk_buff *skb,
struct netlink_callback *cb)
{
struct leaf *l;
struct trie *t = (struct trie *) tb->tb_data;
t_key key = cb->args[2];
int count = cb->args[3];
rcu_read_lock();
/* Dump starting at last key.
* Note: 0.0.0.0/0 (ie default) is first key.
*/
if (count == 0)
l = trie_firstleaf(t);
else {
/* Normally, continue from last key, but if that is missing
* fallback to using slow rescan
*/
l = fib_find_node(t, key);
if (!l)
l = trie_leafindex(t, count);
}
while (l) {
cb->args[2] = l->key;
if (fn_trie_dump_leaf(l, tb, skb, cb) < 0) {
cb->args[3] = count;
rcu_read_unlock();
return -1;
}
++count;
l = trie_nextleaf(l);
memset(&cb->args[4], 0,
sizeof(cb->args) - 4*sizeof(cb->args[0]));
}
cb->args[3] = count;
rcu_read_unlock();
return skb->len;
}
void __init fib_trie_init(void)
{
fn_alias_kmem = kmem_cache_create("ip_fib_alias",
sizeof(struct fib_alias),
0, SLAB_PANIC, NULL);
trie_leaf_kmem = kmem_cache_create("ip_fib_trie",
max(sizeof(struct leaf),
sizeof(struct leaf_info)),
0, SLAB_PANIC, NULL);
}
struct fib_table *fib_trie_table(u32 id)
{
struct fib_table *tb;
struct trie *t;
tb = kmalloc(sizeof(struct fib_table) + sizeof(struct trie),
GFP_KERNEL);
if (tb == NULL)
return NULL;
tb->tb_id = id;
tb->tb_default = -1;
tb->tb_num_default = 0;
t = (struct trie *) tb->tb_data;
memset(t, 0, sizeof(*t));
return tb;
}
#ifdef CONFIG_PROC_FS
/* Depth first Trie walk iterator */
struct fib_trie_iter {
struct seq_net_private p;
struct fib_table *tb;
struct tnode *tnode;
unsigned int index;
unsigned int depth;
};
static struct rt_trie_node *fib_trie_get_next(struct fib_trie_iter *iter)
{
struct tnode *tn = iter->tnode;
unsigned int cindex = iter->index;
struct tnode *p;
/* A single entry routing table */
if (!tn)
return NULL;
pr_debug("get_next iter={node=%p index=%d depth=%d}\n",
iter->tnode, iter->index, iter->depth);
rescan:
while (cindex < (1<<tn->bits)) {
struct rt_trie_node *n = tnode_get_child_rcu(tn, cindex);
if (n) {
if (IS_LEAF(n)) {
iter->tnode = tn;
iter->index = cindex + 1;
} else {
/* push down one level */
iter->tnode = (struct tnode *) n;
iter->index = 0;
++iter->depth;
}
return n;
}
++cindex;
}
/* Current node exhausted, pop back up */
p = node_parent_rcu((struct rt_trie_node *)tn);
if (p) {
cindex = tkey_extract_bits(tn->key, p->pos, p->bits)+1;
tn = p;
--iter->depth;
goto rescan;
}
/* got root? */
return NULL;
}
static struct rt_trie_node *fib_trie_get_first(struct fib_trie_iter *iter,
struct trie *t)
{
struct rt_trie_node *n;
if (!t)
return NULL;
n = rcu_dereference(t->trie);
if (!n)
return NULL;
if (IS_TNODE(n)) {
iter->tnode = (struct tnode *) n;
iter->index = 0;
iter->depth = 1;
} else {
iter->tnode = NULL;
iter->index = 0;
iter->depth = 0;
}
return n;
}
static void trie_collect_stats(struct trie *t, struct trie_stat *s)
{
struct rt_trie_node *n;
struct fib_trie_iter iter;
memset(s, 0, sizeof(*s));
rcu_read_lock();
for (n = fib_trie_get_first(&iter, t); n; n = fib_trie_get_next(&iter)) {
if (IS_LEAF(n)) {
struct leaf *l = (struct leaf *)n;
struct leaf_info *li;
struct hlist_node *tmp;
s->leaves++;
s->totdepth += iter.depth;
if (iter.depth > s->maxdepth)
s->maxdepth = iter.depth;
hlist_for_each_entry_rcu(li, tmp, &l->list, hlist)
++s->prefixes;
} else {
const struct tnode *tn = (const struct tnode *) n;
int i;
s->tnodes++;
if (tn->bits < MAX_STAT_DEPTH)
s->nodesizes[tn->bits]++;
for (i = 0; i < (1<<tn->bits); i++)
if (!tn->child[i])
s->nullpointers++;
}
}
rcu_read_unlock();
}
/*
* This outputs /proc/net/fib_triestats
*/
static void trie_show_stats(struct seq_file *seq, struct trie_stat *stat)
{
unsigned int i, max, pointers, bytes, avdepth;
if (stat->leaves)
avdepth = stat->totdepth*100 / stat->leaves;
else
avdepth = 0;
seq_printf(seq, "\tAver depth: %u.%02d\n",
avdepth / 100, avdepth % 100);
seq_printf(seq, "\tMax depth: %u\n", stat->maxdepth);
seq_printf(seq, "\tLeaves: %u\n", stat->leaves);
bytes = sizeof(struct leaf) * stat->leaves;
seq_printf(seq, "\tPrefixes: %u\n", stat->prefixes);
bytes += sizeof(struct leaf_info) * stat->prefixes;
seq_printf(seq, "\tInternal nodes: %u\n\t", stat->tnodes);
bytes += sizeof(struct tnode) * stat->tnodes;
max = MAX_STAT_DEPTH;
while (max > 0 && stat->nodesizes[max-1] == 0)
max--;
pointers = 0;
for (i = 1; i <= max; i++)
if (stat->nodesizes[i] != 0) {
seq_printf(seq, " %u: %u", i, stat->nodesizes[i]);
pointers += (1<<i) * stat->nodesizes[i];
}
seq_putc(seq, '\n');
seq_printf(seq, "\tPointers: %u\n", pointers);
bytes += sizeof(struct rt_trie_node *) * pointers;
seq_printf(seq, "Null ptrs: %u\n", stat->nullpointers);
seq_printf(seq, "Total size: %u kB\n", (bytes + 1023) / 1024);
}
#ifdef CONFIG_IP_FIB_TRIE_STATS
static void trie_show_usage(struct seq_file *seq,
const struct trie_use_stats *stats)
{
seq_printf(seq, "\nCounters:\n---------\n");
seq_printf(seq, "gets = %u\n", stats->gets);
seq_printf(seq, "backtracks = %u\n", stats->backtrack);
seq_printf(seq, "semantic match passed = %u\n",
stats->semantic_match_passed);
seq_printf(seq, "semantic match miss = %u\n",
stats->semantic_match_miss);
seq_printf(seq, "null node hit= %u\n", stats->null_node_hit);
seq_printf(seq, "skipped node resize = %u\n\n",
stats->resize_node_skipped);
}
#endif /* CONFIG_IP_FIB_TRIE_STATS */
static void fib_table_print(struct seq_file *seq, struct fib_table *tb)
{
if (tb->tb_id == RT_TABLE_LOCAL)
seq_puts(seq, "Local:\n");
else if (tb->tb_id == RT_TABLE_MAIN)
seq_puts(seq, "Main:\n");
else
seq_printf(seq, "Id %d:\n", tb->tb_id);
}
static int fib_triestat_seq_show(struct seq_file *seq, void *v)
{
struct net *net = (struct net *)seq->private;
unsigned int h;
seq_printf(seq,
"Basic info: size of leaf:"
" %Zd bytes, size of tnode: %Zd bytes.\n",
sizeof(struct leaf), sizeof(struct tnode));
for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv4.fib_table_hash[h];
struct hlist_node *node;
struct fib_table *tb;
hlist_for_each_entry_rcu(tb, node, head, tb_hlist) {
struct trie *t = (struct trie *) tb->tb_data;
struct trie_stat stat;
if (!t)
continue;
fib_table_print(seq, tb);
trie_collect_stats(t, &stat);
trie_show_stats(seq, &stat);
#ifdef CONFIG_IP_FIB_TRIE_STATS
trie_show_usage(seq, &t->stats);
#endif
}
}
return 0;
}
static int fib_triestat_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, fib_triestat_seq_show);
}
static const struct file_operations fib_triestat_fops = {
.owner = THIS_MODULE,
.open = fib_triestat_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
static struct rt_trie_node *fib_trie_get_idx(struct seq_file *seq, loff_t pos)
{
struct fib_trie_iter *iter = seq->private;
struct net *net = seq_file_net(seq);
loff_t idx = 0;
unsigned int h;
for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
struct hlist_head *head = &net->ipv4.fib_table_hash[h];
struct hlist_node *node;
struct fib_table *tb;
hlist_for_each_entry_rcu(tb, node, head, tb_hlist) {
struct rt_trie_node *n;
for (n = fib_trie_get_first(iter,
(struct trie *) tb->tb_data);
n; n = fib_trie_get_next(iter))
if (pos == idx++) {
iter->tb = tb;
return n;
}
}
}
return NULL;
}
static void *fib_trie_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
return fib_trie_get_idx(seq, *pos);
}
static void *fib_trie_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct fib_trie_iter *iter = seq->private;
struct net *net = seq_file_net(seq);
struct fib_table *tb = iter->tb;
struct hlist_node *tb_node;
unsigned int h;
struct rt_trie_node *n;
++*pos;
/* next node in same table */
n = fib_trie_get_next(iter);
if (n)
return n;
/* walk rest of this hash chain */
h = tb->tb_id & (FIB_TABLE_HASHSZ - 1);
while ((tb_node = rcu_dereference(hlist_next_rcu(&tb->tb_hlist)))) {
tb = hlist_entry(tb_node, struct fib_table, tb_hlist);
n = fib_trie_get_first(iter, (struct trie *) tb->tb_data);
if (n)
goto found;
}
/* new hash chain */
while (++h < FIB_TABLE_HASHSZ) {
struct hlist_head *head = &net->ipv4.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, tb_node, head, tb_hlist) {
n = fib_trie_get_first(iter, (struct trie *) tb->tb_data);
if (n)
goto found;
}
}
return NULL;
found:
iter->tb = tb;
return n;
}
static void fib_trie_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static void seq_indent(struct seq_file *seq, int n)
{
while (n-- > 0)
seq_puts(seq, " ");
}
static inline const char *rtn_scope(char *buf, size_t len, enum rt_scope_t s)
{
switch (s) {
case RT_SCOPE_UNIVERSE: return "universe";
case RT_SCOPE_SITE: return "site";
case RT_SCOPE_LINK: return "link";
case RT_SCOPE_HOST: return "host";
case RT_SCOPE_NOWHERE: return "nowhere";
default:
snprintf(buf, len, "scope=%d", s);
return buf;
}
}
static const char *const rtn_type_names[__RTN_MAX] = {
[RTN_UNSPEC] = "UNSPEC",
[RTN_UNICAST] = "UNICAST",
[RTN_LOCAL] = "LOCAL",
[RTN_BROADCAST] = "BROADCAST",
[RTN_ANYCAST] = "ANYCAST",
[RTN_MULTICAST] = "MULTICAST",
[RTN_BLACKHOLE] = "BLACKHOLE",
[RTN_UNREACHABLE] = "UNREACHABLE",
[RTN_PROHIBIT] = "PROHIBIT",
[RTN_THROW] = "THROW",
[RTN_NAT] = "NAT",
[RTN_XRESOLVE] = "XRESOLVE",
};
static inline const char *rtn_type(char *buf, size_t len, unsigned int t)
{
if (t < __RTN_MAX && rtn_type_names[t])
return rtn_type_names[t];
snprintf(buf, len, "type %u", t);
return buf;
}
/* Pretty print the trie */
static int fib_trie_seq_show(struct seq_file *seq, void *v)
{
const struct fib_trie_iter *iter = seq->private;
struct rt_trie_node *n = v;
if (!node_parent_rcu(n))
fib_table_print(seq, iter->tb);
if (IS_TNODE(n)) {
struct tnode *tn = (struct tnode *) n;
__be32 prf = htonl(mask_pfx(tn->key, tn->pos));
seq_indent(seq, iter->depth-1);
seq_printf(seq, " +-- %pI4/%d %d %d %d\n",
&prf, tn->pos, tn->bits, tn->full_children,
tn->empty_children);
} else {
struct leaf *l = (struct leaf *) n;
struct leaf_info *li;
struct hlist_node *node;
__be32 val = htonl(l->key);
seq_indent(seq, iter->depth);
seq_printf(seq, " |-- %pI4\n", &val);
hlist_for_each_entry_rcu(li, node, &l->list, hlist) {
struct fib_alias *fa;
list_for_each_entry_rcu(fa, &li->falh, fa_list) {
char buf1[32], buf2[32];
seq_indent(seq, iter->depth+1);
seq_printf(seq, " /%d %s %s", li->plen,
rtn_scope(buf1, sizeof(buf1),
fa->fa_info->fib_scope),
rtn_type(buf2, sizeof(buf2),
fa->fa_type));
if (fa->fa_tos)
seq_printf(seq, " tos=%d", fa->fa_tos);
seq_putc(seq, '\n');
}
}
}
return 0;
}
static const struct seq_operations fib_trie_seq_ops = {
.start = fib_trie_seq_start,
.next = fib_trie_seq_next,
.stop = fib_trie_seq_stop,
.show = fib_trie_seq_show,
};
static int fib_trie_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &fib_trie_seq_ops,
sizeof(struct fib_trie_iter));
}
static const struct file_operations fib_trie_fops = {
.owner = THIS_MODULE,
.open = fib_trie_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
struct fib_route_iter {
struct seq_net_private p;
struct trie *main_trie;
loff_t pos;
t_key key;
};
static struct leaf *fib_route_get_idx(struct fib_route_iter *iter, loff_t pos)
{
struct leaf *l = NULL;
struct trie *t = iter->main_trie;
/* use cache location of last found key */
if (iter->pos > 0 && pos >= iter->pos && (l = fib_find_node(t, iter->key)))
pos -= iter->pos;
else {
iter->pos = 0;
l = trie_firstleaf(t);
}
while (l && pos-- > 0) {
iter->pos++;
l = trie_nextleaf(l);
}
if (l)
iter->key = pos; /* remember it */
else
iter->pos = 0; /* forget it */
return l;
}
static void *fib_route_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct fib_route_iter *iter = seq->private;
struct fib_table *tb;
rcu_read_lock();
tb = fib_get_table(seq_file_net(seq), RT_TABLE_MAIN);
if (!tb)
return NULL;
iter->main_trie = (struct trie *) tb->tb_data;
if (*pos == 0)
return SEQ_START_TOKEN;
else
return fib_route_get_idx(iter, *pos - 1);
}
static void *fib_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct fib_route_iter *iter = seq->private;
struct leaf *l = v;
++*pos;
if (v == SEQ_START_TOKEN) {
iter->pos = 0;
l = trie_firstleaf(iter->main_trie);
} else {
iter->pos++;
l = trie_nextleaf(l);
}
if (l)
iter->key = l->key;
else
iter->pos = 0;
return l;
}
static void fib_route_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static unsigned int fib_flag_trans(int type, __be32 mask, const struct fib_info *fi)
{
unsigned int flags = 0;
if (type == RTN_UNREACHABLE || type == RTN_PROHIBIT)
flags = RTF_REJECT;
if (fi && fi->fib_nh->nh_gw)
flags |= RTF_GATEWAY;
if (mask == htonl(0xFFFFFFFF))
flags |= RTF_HOST;
flags |= RTF_UP;
return flags;
}
/*
* This outputs /proc/net/route.
* The format of the file is not supposed to be changed
* and needs to be same as fib_hash output to avoid breaking
* legacy utilities
*/
static int fib_route_seq_show(struct seq_file *seq, void *v)
{
struct leaf *l = v;
struct leaf_info *li;
struct hlist_node *node;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway "
"\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU"
"\tWindow\tIRTT");
return 0;
}
hlist_for_each_entry_rcu(li, node, &l->list, hlist) {
struct fib_alias *fa;
__be32 mask, prefix;
mask = inet_make_mask(li->plen);
prefix = htonl(l->key);
list_for_each_entry_rcu(fa, &li->falh, fa_list) {
const struct fib_info *fi = fa->fa_info;
unsigned int flags = fib_flag_trans(fa->fa_type, mask, fi);
int len;
if (fa->fa_type == RTN_BROADCAST
|| fa->fa_type == RTN_MULTICAST)
continue;
if (fi)
seq_printf(seq,
"%s\t%08X\t%08X\t%04X\t%d\t%u\t"
"%d\t%08X\t%d\t%u\t%u%n",
fi->fib_dev ? fi->fib_dev->name : "*",
prefix,
fi->fib_nh->nh_gw, flags, 0, 0,
fi->fib_priority,
mask,
(fi->fib_advmss ?
fi->fib_advmss + 40 : 0),
fi->fib_window,
fi->fib_rtt >> 3, &len);
else
seq_printf(seq,
"*\t%08X\t%08X\t%04X\t%d\t%u\t"
"%d\t%08X\t%d\t%u\t%u%n",
prefix, 0, flags, 0, 0, 0,
mask, 0, 0, 0, &len);
seq_printf(seq, "%*s\n", 127 - len, "");
}
}
return 0;
}
static const struct seq_operations fib_route_seq_ops = {
.start = fib_route_seq_start,
.next = fib_route_seq_next,
.stop = fib_route_seq_stop,
.show = fib_route_seq_show,
};
static int fib_route_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &fib_route_seq_ops,
sizeof(struct fib_route_iter));
}
static const struct file_operations fib_route_fops = {
.owner = THIS_MODULE,
.open = fib_route_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
int __net_init fib_proc_init(struct net *net)
{
if (!proc_net_fops_create(net, "fib_trie", S_IRUGO, &fib_trie_fops))
goto out1;
if (!proc_net_fops_create(net, "fib_triestat", S_IRUGO,
&fib_triestat_fops))
goto out2;
if (!proc_net_fops_create(net, "route", S_IRUGO, &fib_route_fops))
goto out3;
return 0;
out3:
proc_net_remove(net, "fib_triestat");
out2:
proc_net_remove(net, "fib_trie");
out1:
return -ENOMEM;
}
void __net_exit fib_proc_exit(struct net *net)
{
proc_net_remove(net, "fib_trie");
proc_net_remove(net, "fib_triestat");
proc_net_remove(net, "route");
}
#endif /* CONFIG_PROC_FS */
|
tohenk/android_kernel_samsung_smdk4x12
|
net/ipv4/fib_trie.c
|
C
|
gpl-2.0
| 63,049
|
! { dg-do compile }
! { dg-options "-std=f95 -Wall" }
!
! PR fortran/34495
!
! Check for invalid Fortran 95 initialization expressions
!
program main
implicit none
real, parameter :: r1 = real(33) ! { dg-error "Fortran 2003: Function 'real' as initialization expression" }
real, parameter :: r2 = dble(33) ! { dg-error "Fortran 2003: Function 'dble' as initialization expression" }
complex, parameter :: z = cmplx(33,33)! { dg-error "Fortran 2003: Function 'cmplx' as initialization expression" }
real, parameter :: r4 = sngl(3.d0) ! { dg-error "Fortran 2003: Function 'sngl' as initialization expression" }
real, parameter :: r5 = float(33) ! { dg-error "Fortran 2003: Function 'float' as initialization expression" }
end program main
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/gcc/gcc-4.6.3/gcc/testsuite/gfortran.dg/initialization_16.f90
|
FORTRAN
|
gpl-2.0
| 758
|
program trivial
end
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/gcc/gcc-4.6.3/gcc/testsuite/gfortran.dg/debug/trivial.f
|
FORTRAN
|
gpl-2.0
| 32
|
/* { dg-do preprocess } */
/* { dg-options "-P -dU" } */
/* { dg-final { scan-file-not cmdlne-dU-23.i "__FILE__" } } */
#ifdef __FILE__
#endif
|
SanDisk-Open-Source/SSD_Dashboard
|
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.dg/cpp/cmdlne-dU-23.c
|
C
|
gpl-2.0
| 143
|
/*
* ALSA driver for the Aureal Vortex family of soundprocessors.
* Author: Manuel Jander (mjander@embedded.cl)
*
* This driver is the result of the OpenVortex Project from Savannah
* (savannah.nongnu.org/projects/openvortex). I would like to thank
* the developers of OpenVortex, Jeff Muizelaar and Kester Maddock, from
* whom i got plenty of help, and their codebase was invaluable.
* Thanks to the ALSA developers, they helped a lot working out
* the ALSA part.
* Thanks also to Sourceforge for maintaining the old binary drivers,
* and the forum, where developers could comunicate.
*
* Now at least i can play Legacy DOOM with MIDI music :-)
*/
#include "au88x0.h"
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <sound/initval.h>
// module parameters (see "Module Parameters")
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static int pcifix[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 255 };
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
module_param_array(pcifix, int, NULL, 0444);
MODULE_PARM_DESC(pcifix, "Enable VIA-workaround for " CARD_NAME " soundcard.");
MODULE_DESCRIPTION("Aureal vortex");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Aureal Semiconductor Inc., Aureal Vortex Sound Processor}}");
MODULE_DEVICE_TABLE(pci, snd_vortex_ids);
static void vortex_fix_latency(struct pci_dev *vortex)
{
int rc;
if (!(rc = pci_write_config_byte(vortex, 0x40, 0xff))) {
printk(KERN_INFO CARD_NAME
": vortex latency is 0xff\n");
} else {
printk(KERN_WARNING CARD_NAME
": could not set vortex latency: pci error 0x%x\n", rc);
}
}
static void vortex_fix_agp_bridge(struct pci_dev *via)
{
int rc;
u8 value;
/*
* only set the bit (Extend PCI#2 Internal Master for
* Efficient Handling of Dummy Requests) if the can
* read the config and it is not already set
*/
if (!(rc = pci_read_config_byte(via, 0x42, &value))
&& ((value & 0x10)
|| !(rc = pci_write_config_byte(via, 0x42, value | 0x10)))) {
printk(KERN_INFO CARD_NAME
": bridge config is 0x%x\n", value | 0x10);
} else {
printk(KERN_WARNING CARD_NAME
": could not set vortex latency: pci error 0x%x\n", rc);
}
}
static void snd_vortex_workaround(struct pci_dev *vortex, int fix)
{
struct pci_dev *via = NULL;
/* autodetect if workarounds are required */
if (fix == 255) {
/* VIA KT133 */
via = pci_get_device(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_8365_1, NULL);
/* VIA Apollo */
if (via == NULL) {
via = pci_get_device(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_82C598_1, NULL);
/* AMD Irongate */
if (via == NULL)
via = pci_get_device(PCI_VENDOR_ID_AMD,
PCI_DEVICE_ID_AMD_FE_GATE_7007, NULL);
}
if (via) {
printk(KERN_INFO CARD_NAME ": Activating latency workaround...\n");
vortex_fix_latency(vortex);
vortex_fix_agp_bridge(via);
}
} else {
if (fix & 0x1)
vortex_fix_latency(vortex);
if ((fix & 0x2) && (via = pci_get_device(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_8365_1, NULL)))
vortex_fix_agp_bridge(via);
if ((fix & 0x4) && (via = pci_get_device(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_82C598_1, NULL)))
vortex_fix_agp_bridge(via);
if ((fix & 0x8) && (via = pci_get_device(PCI_VENDOR_ID_AMD,
PCI_DEVICE_ID_AMD_FE_GATE_7007, NULL)))
vortex_fix_agp_bridge(via);
}
pci_dev_put(via);
}
// component-destructor
// (see "Management of Cards and Components")
static int snd_vortex_dev_free(struct snd_device *device)
{
vortex_t *vortex = device->device_data;
vortex_gameport_unregister(vortex);
vortex_core_shutdown(vortex);
// Take down PCI interface.
free_irq(vortex->irq, vortex);
iounmap(vortex->mmio);
pci_release_regions(vortex->pci_dev);
pci_disable_device(vortex->pci_dev);
kfree(vortex);
return 0;
}
// chip-specific constructor
// (see "Management of Cards and Components")
static int
snd_vortex_create(struct snd_card *card, struct pci_dev *pci, vortex_t ** rchip)
{
vortex_t *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_vortex_dev_free,
};
*rchip = NULL;
// check PCI availability (DMA).
if ((err = pci_enable_device(pci)) < 0)
return err;
if (pci_set_dma_mask(pci, DMA_BIT_MASK(32)) < 0 ||
pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(32)) < 0) {
printk(KERN_ERR "error to set DMA mask\n");
pci_disable_device(pci);
return -ENXIO;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
chip->card = card;
// initialize the stuff
chip->pci_dev = pci;
chip->io = pci_resource_start(pci, 0);
chip->vendor = pci->vendor;
chip->device = pci->device;
chip->card = card;
chip->irq = -1;
// (1) PCI resource allocation
// Get MMIO area
//
if ((err = pci_request_regions(pci, CARD_NAME_SHORT)) != 0)
goto regions_out;
chip->mmio = pci_ioremap_bar(pci, 0);
if (!chip->mmio) {
printk(KERN_ERR "MMIO area remap failed.\n");
err = -ENOMEM;
goto ioremap_out;
}
/* Init audio core.
* This must be done before we do request_irq otherwise we can get spurious
* interrupts that we do not handle properly and make a mess of things */
if ((err = vortex_core_init(chip)) != 0) {
printk(KERN_ERR "hw core init failed\n");
goto core_out;
}
if ((err = request_irq(pci->irq, vortex_interrupt,
IRQF_SHARED, KBUILD_MODNAME,
chip)) != 0) {
printk(KERN_ERR "cannot grab irq\n");
goto irq_out;
}
chip->irq = pci->irq;
pci_set_master(pci);
// End of PCI setup.
// Register alsa root device.
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
goto alloc_out;
}
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
alloc_out:
free_irq(chip->irq, chip);
irq_out:
vortex_core_shutdown(chip);
core_out:
iounmap(chip->mmio);
ioremap_out:
pci_release_regions(chip->pci_dev);
regions_out:
pci_disable_device(chip->pci_dev);
//FIXME: this not the right place to unregister the gameport
vortex_gameport_unregister(chip);
kfree(chip);
return err;
}
// constructor -- see "Constructor" sub-section
static int
snd_vortex_probe(struct pci_dev *pci, const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
vortex_t *chip;
int err;
// (1)
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
// (2)
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
// (3)
if ((err = snd_vortex_create(card, pci, &chip)) < 0) {
snd_card_free(card);
return err;
}
snd_vortex_workaround(pci, pcifix[dev]);
// Card details needed in snd_vortex_midi
strcpy(card->driver, CARD_NAME_SHORT);
sprintf(card->shortname, "Aureal Vortex %s", CARD_NAME_SHORT);
sprintf(card->longname, "%s at 0x%lx irq %i",
card->shortname, chip->io, chip->irq);
// (4) Alloc components.
err = snd_vortex_mixer(chip);
if (err < 0) {
snd_card_free(card);
return err;
}
// ADB pcm.
err = snd_vortex_new_pcm(chip, VORTEX_PCM_ADB, NR_PCM);
if (err < 0) {
snd_card_free(card);
return err;
}
#ifndef CHIP_AU8820
// ADB SPDIF
if ((err = snd_vortex_new_pcm(chip, VORTEX_PCM_SPDIF, 1)) < 0) {
snd_card_free(card);
return err;
}
// A3D
if ((err = snd_vortex_new_pcm(chip, VORTEX_PCM_A3D, NR_A3D)) < 0) {
snd_card_free(card);
return err;
}
#endif
/*
// ADB I2S
if ((err = snd_vortex_new_pcm(chip, VORTEX_PCM_I2S, 1)) < 0) {
snd_card_free(card);
return err;
}
*/
#ifndef CHIP_AU8810
// WT pcm.
if ((err = snd_vortex_new_pcm(chip, VORTEX_PCM_WT, NR_WT)) < 0) {
snd_card_free(card);
return err;
}
#endif
if ((err = snd_vortex_midi(chip)) < 0) {
snd_card_free(card);
return err;
}
vortex_gameport_register(chip);
#if 0
if (snd_seq_device_new(card, 1, SNDRV_SEQ_DEV_ID_VORTEX_SYNTH,
sizeof(snd_vortex_synth_arg_t), &wave) < 0
|| wave == NULL) {
snd_printk(KERN_ERR "Can't initialize Aureal wavetable synth\n");
} else {
snd_vortex_synth_arg_t *arg;
arg = SNDRV_SEQ_DEVICE_ARGPTR(wave);
strcpy(wave->name, "Aureal Synth");
arg->hwptr = vortex;
arg->index = 1;
arg->seq_ports = seq_ports[dev];
arg->max_voices = max_synth_voices[dev];
}
#endif
// (5)
if ((err = pci_read_config_word(pci, PCI_DEVICE_ID,
&(chip->device))) < 0) {
snd_card_free(card);
return err;
}
if ((err = pci_read_config_word(pci, PCI_VENDOR_ID,
&(chip->vendor))) < 0) {
snd_card_free(card);
return err;
}
chip->rev = pci->revision;
#ifdef CHIP_AU8830
if ((chip->rev) != 0xfe && (chip->rev) != 0xfa) {
printk(KERN_ALERT
"vortex: The revision (%x) of your card has not been seen before.\n",
chip->rev);
printk(KERN_ALERT
"vortex: Please email the results of 'lspci -vv' to openvortex-dev@nongnu.org.\n");
snd_card_free(card);
err = -ENODEV;
return err;
}
#endif
// (6)
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
// (7)
pci_set_drvdata(pci, card);
dev++;
vortex_connect_default(chip, 1);
vortex_enable_int(chip);
return 0;
}
// destructor -- see "Destructor" sub-section
static void snd_vortex_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
// pci_driver definition
static struct pci_driver vortex_driver = {
.name = KBUILD_MODNAME,
.id_table = snd_vortex_ids,
.probe = snd_vortex_probe,
.remove = snd_vortex_remove,
};
module_pci_driver(vortex_driver);
|
prasidh09/cse506
|
unionfs-3.10.y/sound/pci/au88x0/au88x0.c
|
C
|
gpl-2.0
| 9,956
|
DELETE FROM `spell_dbc` WHERE `id`=18350;
INSERT INTO `spell_dbc` (`id`,`Effect1`,`EffectImplicitTargetA1`,`Comment`) VALUES
(18350,3,1,'Soul Preserver trinket spell');
DELETE FROM `spell_script_names` WHERE `spell_id`=18350;
INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES
(18350,'spell_gen_soul_preserver');
|
Kirshan/ALiveCoreRC2
|
sql/updates/world/2011_08_01_03_world_spell_misc.sql
|
SQL
|
gpl-2.0
| 329
|
<!doctype html>
<title>CodeMirror: ASCII Armor (PGP) mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="asciiarmor.js"></script>
<style>.CodeMirror {background: #f8f8f8;}</style>
<div id=nav>
<a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/codemirror/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">ASCII Armor</a>
</ul>
</div>
<article>
<h2>ASCII Armor (PGP) mode</h2>
<form><textarea id="code" name="code">
-----BEGIN PGP MESSAGE-----
Version: OpenPrivacy 0.99
yDgBO22WxBHv7O8X7O/jygAEzol56iUKiXmV+XmpCtmpqQUKiQrFqclFqUDBovzS
vBSFjNSiVHsuAA==
=njUN
-----END PGP MESSAGE-----
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
</script>
<p><strong>MIME types
defined:</strong> <code>application/pgp</code>, <code>application/pgp-keys</code>, <code>application/pgp-signature</code></p>
</article>
|
zhanglei13/zeppelin
|
zeppelin-client/src/asserts/codemirror-5.10/mode/asciiarmor/index.html
|
HTML
|
apache-2.0
| 1,289
|
/*
* leds-lm3533.c -- LM3533 LED driver
*
* Copyright (C) 2011-2012 Texas Instruments
*
* Author: Johan Hovold <jhovold@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; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/leds.h>
#include <linux/mfd/core.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mfd/lm3533.h>
#define LM3533_LVCTRLBANK_MIN 2
#define LM3533_LVCTRLBANK_MAX 5
#define LM3533_LVCTRLBANK_COUNT 4
#define LM3533_RISEFALLTIME_MAX 7
#define LM3533_ALS_CHANNEL_LV_MIN 1
#define LM3533_ALS_CHANNEL_LV_MAX 2
#define LM3533_REG_CTRLBANK_BCONF_BASE 0x1b
#define LM3533_REG_PATTERN_ENABLE 0x28
#define LM3533_REG_PATTERN_LOW_TIME_BASE 0x71
#define LM3533_REG_PATTERN_HIGH_TIME_BASE 0x72
#define LM3533_REG_PATTERN_RISETIME_BASE 0x74
#define LM3533_REG_PATTERN_FALLTIME_BASE 0x75
#define LM3533_REG_PATTERN_STEP 0x10
#define LM3533_REG_CTRLBANK_BCONF_MAPPING_MASK 0x04
#define LM3533_REG_CTRLBANK_BCONF_ALS_EN_MASK 0x02
#define LM3533_REG_CTRLBANK_BCONF_ALS_CHANNEL_MASK 0x01
#define LM3533_LED_FLAG_PATTERN_ENABLE 1
struct lm3533_led {
struct lm3533 *lm3533;
struct lm3533_ctrlbank cb;
struct led_classdev cdev;
int id;
struct mutex mutex;
unsigned long flags;
};
static inline struct lm3533_led *to_lm3533_led(struct led_classdev *cdev)
{
return container_of(cdev, struct lm3533_led, cdev);
}
static inline int lm3533_led_get_ctrlbank_id(struct lm3533_led *led)
{
return led->id + 2;
}
static inline u8 lm3533_led_get_lv_reg(struct lm3533_led *led, u8 base)
{
return base + led->id;
}
static inline u8 lm3533_led_get_pattern(struct lm3533_led *led)
{
return led->id;
}
static inline u8 lm3533_led_get_pattern_reg(struct lm3533_led *led,
u8 base)
{
return base + lm3533_led_get_pattern(led) * LM3533_REG_PATTERN_STEP;
}
static int lm3533_led_pattern_enable(struct lm3533_led *led, int enable)
{
u8 mask;
u8 val;
int pattern;
int state;
int ret = 0;
dev_dbg(led->cdev.dev, "%s - %d\n", __func__, enable);
mutex_lock(&led->mutex);
state = test_bit(LM3533_LED_FLAG_PATTERN_ENABLE, &led->flags);
if ((enable && state) || (!enable && !state))
goto out;
pattern = lm3533_led_get_pattern(led);
mask = 1 << (2 * pattern);
if (enable)
val = mask;
else
val = 0;
ret = lm3533_update(led->lm3533, LM3533_REG_PATTERN_ENABLE, val, mask);
if (ret) {
dev_err(led->cdev.dev, "failed to enable pattern %d (%d)\n",
pattern, enable);
goto out;
}
__change_bit(LM3533_LED_FLAG_PATTERN_ENABLE, &led->flags);
out:
mutex_unlock(&led->mutex);
return ret;
}
static int lm3533_led_set(struct led_classdev *cdev,
enum led_brightness value)
{
struct lm3533_led *led = to_lm3533_led(cdev);
dev_dbg(led->cdev.dev, "%s - %d\n", __func__, value);
if (value == 0)
lm3533_led_pattern_enable(led, 0); /* disable blink */
return lm3533_ctrlbank_set_brightness(&led->cb, value);
}
static enum led_brightness lm3533_led_get(struct led_classdev *cdev)
{
struct lm3533_led *led = to_lm3533_led(cdev);
u8 val;
int ret;
ret = lm3533_ctrlbank_get_brightness(&led->cb, &val);
if (ret)
return ret;
dev_dbg(led->cdev.dev, "%s - %u\n", __func__, val);
return val;
}
/* Pattern generator defines (delays in us). */
#define LM3533_LED_DELAY1_VMIN 0x00
#define LM3533_LED_DELAY2_VMIN 0x3d
#define LM3533_LED_DELAY3_VMIN 0x80
#define LM3533_LED_DELAY1_VMAX (LM3533_LED_DELAY2_VMIN - 1)
#define LM3533_LED_DELAY2_VMAX (LM3533_LED_DELAY3_VMIN - 1)
#define LM3533_LED_DELAY3_VMAX 0xff
#define LM3533_LED_DELAY1_TMIN 16384U
#define LM3533_LED_DELAY2_TMIN 1130496U
#define LM3533_LED_DELAY3_TMIN 10305536U
#define LM3533_LED_DELAY1_TMAX 999424U
#define LM3533_LED_DELAY2_TMAX 9781248U
#define LM3533_LED_DELAY3_TMAX 76890112U
/* t_step = (t_max - t_min) / (v_max - v_min) */
#define LM3533_LED_DELAY1_TSTEP 16384
#define LM3533_LED_DELAY2_TSTEP 131072
#define LM3533_LED_DELAY3_TSTEP 524288
/* Delay limits for hardware accelerated blinking (in ms). */
#define LM3533_LED_DELAY_ON_MAX \
((LM3533_LED_DELAY2_TMAX + LM3533_LED_DELAY2_TSTEP / 2) / 1000)
#define LM3533_LED_DELAY_OFF_MAX \
((LM3533_LED_DELAY3_TMAX + LM3533_LED_DELAY3_TSTEP / 2) / 1000)
/*
* Returns linear map of *t from [t_min,t_max] to [v_min,v_max] with a step
* size of t_step, where
*
* t_step = (t_max - t_min) / (v_max - v_min)
*
* and updates *t to reflect the mapped value.
*/
static u8 time_to_val(unsigned *t, unsigned t_min, unsigned t_step,
u8 v_min, u8 v_max)
{
unsigned val;
val = (*t + t_step / 2 - t_min) / t_step + v_min;
*t = t_step * (val - v_min) + t_min;
return (u8)val;
}
/*
* Returns time code corresponding to *delay (in ms) and updates *delay to
* reflect actual hardware delay.
*
* Hardware supports 256 discrete delay times, divided into three groups with
* the following ranges and step-sizes:
*
* [ 16, 999] [0x00, 0x3e] step 16 ms
* [ 1130, 9781] [0x3d, 0x7f] step 131 ms
* [10306, 76890] [0x80, 0xff] step 524 ms
*
* Note that delay group 3 is only available for delay_off.
*/
static u8 lm3533_led_get_hw_delay(unsigned *delay)
{
unsigned t;
u8 val;
t = *delay * 1000;
if (t >= (LM3533_LED_DELAY2_TMAX + LM3533_LED_DELAY3_TMIN) / 2) {
t = clamp(t, LM3533_LED_DELAY3_TMIN, LM3533_LED_DELAY3_TMAX);
val = time_to_val(&t, LM3533_LED_DELAY3_TMIN,
LM3533_LED_DELAY3_TSTEP,
LM3533_LED_DELAY3_VMIN,
LM3533_LED_DELAY3_VMAX);
} else if (t >= (LM3533_LED_DELAY1_TMAX + LM3533_LED_DELAY2_TMIN) / 2) {
t = clamp(t, LM3533_LED_DELAY2_TMIN, LM3533_LED_DELAY2_TMAX);
val = time_to_val(&t, LM3533_LED_DELAY2_TMIN,
LM3533_LED_DELAY2_TSTEP,
LM3533_LED_DELAY2_VMIN,
LM3533_LED_DELAY2_VMAX);
} else {
t = clamp(t, LM3533_LED_DELAY1_TMIN, LM3533_LED_DELAY1_TMAX);
val = time_to_val(&t, LM3533_LED_DELAY1_TMIN,
LM3533_LED_DELAY1_TSTEP,
LM3533_LED_DELAY1_VMIN,
LM3533_LED_DELAY1_VMAX);
}
*delay = (t + 500) / 1000;
return val;
}
/*
* Set delay register base to *delay (in ms) and update *delay to reflect
* actual hardware delay used.
*/
static u8 lm3533_led_delay_set(struct lm3533_led *led, u8 base,
unsigned long *delay)
{
unsigned t;
u8 val;
u8 reg;
int ret;
t = (unsigned)*delay;
/* Delay group 3 is only available for low time (delay off). */
if (base != LM3533_REG_PATTERN_LOW_TIME_BASE)
t = min(t, LM3533_LED_DELAY2_TMAX / 1000);
val = lm3533_led_get_hw_delay(&t);
dev_dbg(led->cdev.dev, "%s - %lu: %u (0x%02x)\n", __func__,
*delay, t, val);
reg = lm3533_led_get_pattern_reg(led, base);
ret = lm3533_write(led->lm3533, reg, val);
if (ret)
dev_err(led->cdev.dev, "failed to set delay (%02x)\n", reg);
*delay = t;
return ret;
}
static int lm3533_led_delay_on_set(struct lm3533_led *led, unsigned long *t)
{
return lm3533_led_delay_set(led, LM3533_REG_PATTERN_HIGH_TIME_BASE, t);
}
static int lm3533_led_delay_off_set(struct lm3533_led *led, unsigned long *t)
{
return lm3533_led_delay_set(led, LM3533_REG_PATTERN_LOW_TIME_BASE, t);
}
static int lm3533_led_blink_set(struct led_classdev *cdev,
unsigned long *delay_on,
unsigned long *delay_off)
{
struct lm3533_led *led = to_lm3533_led(cdev);
int ret;
dev_dbg(led->cdev.dev, "%s - on = %lu, off = %lu\n", __func__,
*delay_on, *delay_off);
if (*delay_on > LM3533_LED_DELAY_ON_MAX ||
*delay_off > LM3533_LED_DELAY_OFF_MAX)
return -EINVAL;
if (*delay_on == 0 && *delay_off == 0) {
*delay_on = 500;
*delay_off = 500;
}
ret = lm3533_led_delay_on_set(led, delay_on);
if (ret)
return ret;
ret = lm3533_led_delay_off_set(led, delay_off);
if (ret)
return ret;
return lm3533_led_pattern_enable(led, 1);
}
static ssize_t show_id(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
return scnprintf(buf, PAGE_SIZE, "%d\n", led->id);
}
/*
* Pattern generator rise/fall times:
*
* 0 - 2048 us (default)
* 1 - 262 ms
* 2 - 524 ms
* 3 - 1.049 s
* 4 - 2.097 s
* 5 - 4.194 s
* 6 - 8.389 s
* 7 - 16.78 s
*/
static ssize_t show_risefalltime(struct device *dev,
struct device_attribute *attr,
char *buf, u8 base)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
ssize_t ret;
u8 reg;
u8 val;
reg = lm3533_led_get_pattern_reg(led, base);
ret = lm3533_read(led->lm3533, reg, &val);
if (ret)
return ret;
return scnprintf(buf, PAGE_SIZE, "%x\n", val);
}
static ssize_t show_risetime(struct device *dev,
struct device_attribute *attr, char *buf)
{
return show_risefalltime(dev, attr, buf,
LM3533_REG_PATTERN_RISETIME_BASE);
}
static ssize_t show_falltime(struct device *dev,
struct device_attribute *attr, char *buf)
{
return show_risefalltime(dev, attr, buf,
LM3533_REG_PATTERN_FALLTIME_BASE);
}
static ssize_t store_risefalltime(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len, u8 base)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
u8 val;
u8 reg;
int ret;
if (kstrtou8(buf, 0, &val) || val > LM3533_RISEFALLTIME_MAX)
return -EINVAL;
reg = lm3533_led_get_pattern_reg(led, base);
ret = lm3533_write(led->lm3533, reg, val);
if (ret)
return ret;
return len;
}
static ssize_t store_risetime(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
return store_risefalltime(dev, attr, buf, len,
LM3533_REG_PATTERN_RISETIME_BASE);
}
static ssize_t store_falltime(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
return store_risefalltime(dev, attr, buf, len,
LM3533_REG_PATTERN_FALLTIME_BASE);
}
static ssize_t show_als_channel(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
unsigned channel;
u8 reg;
u8 val;
int ret;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
ret = lm3533_read(led->lm3533, reg, &val);
if (ret)
return ret;
channel = (val & LM3533_REG_CTRLBANK_BCONF_ALS_CHANNEL_MASK) + 1;
return scnprintf(buf, PAGE_SIZE, "%u\n", channel);
}
static ssize_t store_als_channel(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
unsigned channel;
u8 reg;
u8 val;
u8 mask;
int ret;
if (kstrtouint(buf, 0, &channel))
return -EINVAL;
if (channel < LM3533_ALS_CHANNEL_LV_MIN ||
channel > LM3533_ALS_CHANNEL_LV_MAX)
return -EINVAL;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
mask = LM3533_REG_CTRLBANK_BCONF_ALS_CHANNEL_MASK;
val = channel - 1;
ret = lm3533_update(led->lm3533, reg, val, mask);
if (ret)
return ret;
return len;
}
static ssize_t show_als_en(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
bool enable;
u8 reg;
u8 val;
int ret;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
ret = lm3533_read(led->lm3533, reg, &val);
if (ret)
return ret;
enable = val & LM3533_REG_CTRLBANK_BCONF_ALS_EN_MASK;
return scnprintf(buf, PAGE_SIZE, "%d\n", enable);
}
static ssize_t store_als_en(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
unsigned enable;
u8 reg;
u8 mask;
u8 val;
int ret;
if (kstrtouint(buf, 0, &enable))
return -EINVAL;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
mask = LM3533_REG_CTRLBANK_BCONF_ALS_EN_MASK;
if (enable)
val = mask;
else
val = 0;
ret = lm3533_update(led->lm3533, reg, val, mask);
if (ret)
return ret;
return len;
}
static ssize_t show_linear(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
u8 reg;
u8 val;
int linear;
int ret;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
ret = lm3533_read(led->lm3533, reg, &val);
if (ret)
return ret;
if (val & LM3533_REG_CTRLBANK_BCONF_MAPPING_MASK)
linear = 1;
else
linear = 0;
return scnprintf(buf, PAGE_SIZE, "%x\n", linear);
}
static ssize_t store_linear(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
unsigned long linear;
u8 reg;
u8 mask;
u8 val;
int ret;
if (kstrtoul(buf, 0, &linear))
return -EINVAL;
reg = lm3533_led_get_lv_reg(led, LM3533_REG_CTRLBANK_BCONF_BASE);
mask = LM3533_REG_CTRLBANK_BCONF_MAPPING_MASK;
if (linear)
val = mask;
else
val = 0;
ret = lm3533_update(led->lm3533, reg, val, mask);
if (ret)
return ret;
return len;
}
static ssize_t show_pwm(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
u8 val;
int ret;
ret = lm3533_ctrlbank_get_pwm(&led->cb, &val);
if (ret)
return ret;
return scnprintf(buf, PAGE_SIZE, "%u\n", val);
}
static ssize_t store_pwm(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
u8 val;
int ret;
if (kstrtou8(buf, 0, &val))
return -EINVAL;
ret = lm3533_ctrlbank_set_pwm(&led->cb, val);
if (ret)
return ret;
return len;
}
static LM3533_ATTR_RW(als_channel);
static LM3533_ATTR_RW(als_en);
static LM3533_ATTR_RW(falltime);
static LM3533_ATTR_RO(id);
static LM3533_ATTR_RW(linear);
static LM3533_ATTR_RW(pwm);
static LM3533_ATTR_RW(risetime);
static struct attribute *lm3533_led_attributes[] = {
&dev_attr_als_channel.attr,
&dev_attr_als_en.attr,
&dev_attr_falltime.attr,
&dev_attr_id.attr,
&dev_attr_linear.attr,
&dev_attr_pwm.attr,
&dev_attr_risetime.attr,
NULL,
};
static umode_t lm3533_led_attr_is_visible(struct kobject *kobj,
struct attribute *attr, int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3533_led *led = to_lm3533_led(led_cdev);
umode_t mode = attr->mode;
if (attr == &dev_attr_als_channel.attr ||
attr == &dev_attr_als_en.attr) {
if (!led->lm3533->have_als)
mode = 0;
}
return mode;
};
static const struct attribute_group lm3533_led_attribute_group = {
.is_visible = lm3533_led_attr_is_visible,
.attrs = lm3533_led_attributes
};
static const struct attribute_group *lm3533_led_attribute_groups[] = {
&lm3533_led_attribute_group,
NULL
};
static int lm3533_led_setup(struct lm3533_led *led,
struct lm3533_led_platform_data *pdata)
{
int ret;
ret = lm3533_ctrlbank_set_max_current(&led->cb, pdata->max_current);
if (ret)
return ret;
return lm3533_ctrlbank_set_pwm(&led->cb, pdata->pwm);
}
static int lm3533_led_probe(struct platform_device *pdev)
{
struct lm3533 *lm3533;
struct lm3533_led_platform_data *pdata;
struct lm3533_led *led;
int ret;
dev_dbg(&pdev->dev, "%s\n", __func__);
lm3533 = dev_get_drvdata(pdev->dev.parent);
if (!lm3533)
return -EINVAL;
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "no platform data\n");
return -EINVAL;
}
if (pdev->id < 0 || pdev->id >= LM3533_LVCTRLBANK_COUNT) {
dev_err(&pdev->dev, "illegal LED id %d\n", pdev->id);
return -EINVAL;
}
led = devm_kzalloc(&pdev->dev, sizeof(*led), GFP_KERNEL);
if (!led)
return -ENOMEM;
led->lm3533 = lm3533;
led->cdev.name = pdata->name;
led->cdev.default_trigger = pdata->default_trigger;
led->cdev.brightness_set_blocking = lm3533_led_set;
led->cdev.brightness_get = lm3533_led_get;
led->cdev.blink_set = lm3533_led_blink_set;
led->cdev.brightness = LED_OFF;
led->cdev.groups = lm3533_led_attribute_groups,
led->id = pdev->id;
mutex_init(&led->mutex);
/* The class framework makes a callback to get brightness during
* registration so use parent device (for error reporting) until
* registered.
*/
led->cb.lm3533 = lm3533;
led->cb.id = lm3533_led_get_ctrlbank_id(led);
led->cb.dev = lm3533->dev;
platform_set_drvdata(pdev, led);
ret = devm_led_classdev_register(pdev->dev.parent, &led->cdev);
if (ret) {
dev_err(&pdev->dev, "failed to register LED %d\n", pdev->id);
return ret;
}
led->cb.dev = led->cdev.dev;
ret = lm3533_led_setup(led, pdata);
if (ret)
return ret;
ret = lm3533_ctrlbank_enable(&led->cb);
if (ret)
return ret;
return 0;
}
static int lm3533_led_remove(struct platform_device *pdev)
{
struct lm3533_led *led = platform_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s\n", __func__);
lm3533_ctrlbank_disable(&led->cb);
return 0;
}
static void lm3533_led_shutdown(struct platform_device *pdev)
{
struct lm3533_led *led = platform_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s\n", __func__);
lm3533_ctrlbank_disable(&led->cb);
lm3533_led_set(&led->cdev, LED_OFF); /* disable blink */
}
static struct platform_driver lm3533_led_driver = {
.driver = {
.name = "lm3533-leds",
},
.probe = lm3533_led_probe,
.remove = lm3533_led_remove,
.shutdown = lm3533_led_shutdown,
};
module_platform_driver(lm3533_led_driver);
MODULE_AUTHOR("Johan Hovold <jhovold@gmail.com>");
MODULE_DESCRIPTION("LM3533 LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:lm3533-leds");
|
BPI-SINOVOIP/BPI-Mainline-kernel
|
linux-4.19/drivers/leds/leds-lm3533.c
|
C
|
gpl-2.0
| 18,041
|
/**
* Handsontable 0.10.5
* Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://handsontable.com/
*
* Date: Mon Mar 31 2014 14:19:47 GMT+0200 (CEST)
*/
/*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */
var Handsontable = { //class namespace
extension: {}, //extenstion namespace
plugins: {}, //plugin namespace
helper: {} //helper namespace
};
(function ($, window, Handsontable) {
"use strict";
//http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
/**
* Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun, thisp) {
"use strict";
if (typeof this === "undefined" || this === null) {
throw new TypeError();
}
if (typeof fun !== "function") {
throw new TypeError();
}
thisp = thisp || this;
if (isNodeList(thisp)) {
thisp = convertNodeListToArray(thisp);
}
var len = thisp.length,
res = [],
i,
val;
for (i = 0; i < len; i += 1) {
if (thisp.hasOwnProperty(i)) {
val = thisp[i]; // in case fun mutates this
if (fun.call(thisp, val, i, thisp)) {
res.push(val);
}
}
}
return res;
function isNodeList(object) {
return /NodeList/i.test(object.item);
}
function convertNodeListToArray(nodeList) {
var array = [];
for (var i = 0, len = nodeList.length; i < len; i++){
array[i] = nodeList[i]
}
return array;
}
};
}
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
try {
var properDefineProperty = true;
defineProperty(function(){}, 'foo', {});
} catch (e) {
properDefineProperty = false;
}
/*
IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does.
M$ deserves a high five for this one :)
*/
var counter = +(new Date) % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
if(!properDefineProperty){
this._wmCache = [];
}
};
if(properDefineProperty){
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
'delete': function(key) {
this.set(key, undefined);
}
};
} else {
WeakMap.prototype = {
set: function(key, value) {
if(typeof key == 'undefined' || typeof value == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
this._wmCache[i].value = value;
return;
}
}
this._wmCache.push({key: key, value: value});
},
get: function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
return this._wmCache[i].value;
}
}
return;
},
'delete': function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
Array.prototype.slice.call(this._wmCache, i, 1);
}
}
}
};
}
window.WeakMap = WeakMap;
})();
}
Handsontable.activeGuid = null;
/**
* Handsontable constructor
* @param rootElement The jQuery element in which Handsontable DOM will be inserted
* @param userSettings
* @constructor
*/
Handsontable.Core = function (rootElement, userSettings) {
var priv
, datamap
, grid
, selection
, editorManager
, autofill
, instance = this
, GridSettings = function () {};
Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings
Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings
Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings));
this.rootElement = rootElement;
var $document = $(document.documentElement);
var $body = $(document.body);
this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events
if (!this.rootElement[0].id) {
this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id
}
priv = {
cellSettings: [],
columnSettings: [],
columnsSettingConflicts: ['data', 'width'],
settings: new GridSettings(), // current settings instance
settingsFromDOM: {},
selStart: new Handsontable.SelectionPoint(),
selEnd: new Handsontable.SelectionPoint(),
isPopulated: null,
scrollable: null,
extensions: {},
firstRun: true
};
grid = {
/**
* Inserts or removes rows and columns
* @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
*/
alter: function (action, index, amount, source, keepEmptyRows) {
var delta;
amount = amount || 1;
switch (action) {
case "insert_row":
delta = datamap.createRow(index, amount);
if (delta) {
if (priv.selStart.exists() && priv.selStart.row() >= index) {
priv.selStart.row(priv.selStart.row() + delta);
selection.transformEnd(delta, 0); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "insert_col":
delta = datamap.createCol(index, amount);
if (delta) {
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
var spliceArray = [index, 0];
spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array
}
if (priv.selStart.exists() && priv.selStart.col() >= index) {
priv.selStart.col(priv.selStart.col() + delta);
selection.transformEnd(0, delta); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "remove_row":
datamap.removeRow(index, amount);
priv.cellSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
case "remove_col":
datamap.removeCol(index, amount);
for(var row = 0, len = datamap.getAll().length; row < len; row++){
if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings
priv.cellSettings[row].splice(index, amount);
}
}
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
if(typeof index == 'undefined'){
index = -1;
}
instance.getSettings().colHeaders.splice(index, amount);
}
priv.columnSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
default:
throw new Error('There is no such action "' + action + '"');
break;
}
if (!keepEmptyRows) {
grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh
}
},
/**
* Makes sure there are empty rows at the bottom of the table
*/
adjustRowsAndCols: function () {
var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols;
//should I add empty rows to data source to meet minRows?
rlen = instance.countRows();
if (rlen < priv.settings.minRows) {
for (r = 0; r < priv.settings.minRows - rlen; r++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//should I add empty rows to meet minSpareRows?
if (emptyRows < priv.settings.minSpareRows) {
for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//count currently empty cols
emptyCols = instance.countEmptyCols(true);
//should I add empty cols to meet minCols?
if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) {
for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
//should I add empty cols to meet minSpareCols?
if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
if (priv.settings.enterBeginsEditing) {
for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) {
datamap.removeRow();
}
}
if (priv.settings.enterBeginsEditing && !priv.settings.columns) {
for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) {
datamap.removeCol();
}
}
var rowCount = instance.countRows();
var colCount = instance.countCols();
if (rowCount === 0 || colCount === 0) {
selection.deselect();
}
if (priv.selStart.exists()) {
var selectionChanged;
var fromRow = priv.selStart.row();
var fromCol = priv.selStart.col();
var toRow = priv.selEnd.row();
var toCol = priv.selEnd.col();
//if selection is outside, move selection to last row
if (fromRow > rowCount - 1) {
fromRow = rowCount - 1;
selectionChanged = true;
if (toRow > fromRow) {
toRow = fromRow;
}
} else if (toRow > rowCount - 1) {
toRow = rowCount - 1;
selectionChanged = true;
if (fromRow > toRow) {
fromRow = toRow;
}
}
//if selection is outside, move selection to last row
if (fromCol > colCount - 1) {
fromCol = colCount - 1;
selectionChanged = true;
if (toCol > fromCol) {
toCol = fromCol;
}
} else if (toCol > colCount - 1) {
toCol = colCount - 1;
selectionChanged = true;
if (fromCol > toCol) {
fromCol = toCol;
}
}
if (selectionChanged) {
instance.selectCell(fromRow, fromCol, toRow, toCol);
}
}
},
/**
* Populate cells at position with 2d array
* @param {Object} start Start selection position
* @param {Array} input 2d array
* @param {Object} [end] End selection position (only for drag-down mode)
* @param {String} [source="populateFromArray"]
* @param {String} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
populateFromArray: function (start, input, end, source, method) {
var r, rlen, c, clen, setData = [], current = {};
rlen = input.length;
if (rlen === 0) {
return false;
}
var repeatCol
, repeatRow
, cmax
, rmax;
// insert data with specified pasteMode method
switch (method) {
case 'shift_down' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
input = Handsontable.helper.translateRowsToColumns(input);
for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
if (c < clen) {
for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
input[c].push(input[c][r % rlen]);
}
input[c].unshift(start.col + c, start.row, 0);
instance.spliceCol.apply(instance, input[c]);
}
else {
input[c % clen][0] = start.col + c;
instance.spliceCol.apply(instance, input[c % clen]);
}
}
break;
case 'shift_right' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
if (r < rlen) {
for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
input[r].push(input[r][c % clen]);
}
input[r].unshift(start.row + r, start.col, 0);
instance.spliceRow.apply(instance, input[r]);
}
else {
input[r % rlen][0] = start.row + r;
instance.spliceRow.apply(instance, input[r % rlen]);
}
}
break;
case 'overwrite' :
default:
// overwrite and other not specified options
current.row = start.row;
current.col = start.col;
for (r = 0; r < rlen; r++) {
if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) {
break;
}
current.col = start.col;
clen = input[r] ? input[r].length : 0;
for (c = 0; c < clen; c++) {
if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) {
break;
}
if (!instance.getCellMeta(current.row, current.col).readOnly) {
setData.push([current.row, current.col, input[r][c]]);
}
current.col++;
if (end && c === clen - 1) {
c = -1;
}
}
current.row++;
if (end && r === rlen - 1) {
r = -1;
}
}
instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
break;
}
},
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @param {Object[]} coordsArr
* @returns {Object}
*/
getCornerCoords: function (coordsArr) {
function mapProp(func, array, prop) {
function getProp(el) {
return el[prop];
}
if (Array.prototype.map) {
return func.apply(Math, array.map(getProp));
}
return func.apply(Math, $.map(array, getProp));
}
return {
TL: {
row: mapProp(Math.min, coordsArr, "row"),
col: mapProp(Math.min, coordsArr, "col")
},
BR: {
row: mapProp(Math.max, coordsArr, "row"),
col: mapProp(Math.max, coordsArr, "col")
}
};
},
/**
* Returns array of td objects given start and end coordinates
*/
getCellsAtCoords: function (start, end) {
var corners = grid.getCornerCoords([start, end]);
var r, c, output = [];
for (r = corners.TL.row; r <= corners.BR.row; r++) {
for (c = corners.TL.col; c <= corners.BR.col; c++) {
output.push(instance.view.getCellAtCoords({
row: r,
col: c
}));
}
}
return output;
}
};
this.selection = selection = { //this public assignment is only temporary
inProgress: false,
/**
* Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired
*/
begin: function () {
instance.selection.inProgress = true;
},
/**
* Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp
*/
finish: function () {
var sel = instance.getSelected();
instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]);
instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
instance.selection.inProgress = false;
},
isInProgress: function () {
return instance.selection.inProgress;
},
/**
* Starts selection range on given td object
* @param {Object} coords
*/
setRangeStart: function (coords) {
priv.selStart.coords(coords);
selection.setRangeEnd(coords);
},
/**
* Ends selection range on given td object
* @param {Object} coords
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
*/
setRangeEnd: function (coords, scrollToCell) {
instance.selection.begin();
priv.selEnd.coords(coords);
if (!priv.settings.multiSelect) {
priv.selStart.coords(coords);
}
//set up current selection
instance.view.wt.selections.current.clear();
instance.view.wt.selections.current.add(priv.selStart.arr());
//set up area selection
instance.view.wt.selections.area.clear();
if (selection.isMultiple()) {
instance.view.wt.selections.area.add(priv.selStart.arr());
instance.view.wt.selections.area.add(priv.selEnd.arr());
}
//set up highlight
if (priv.settings.currentRowClassName || priv.settings.currentColClassName) {
instance.view.wt.selections.highlight.clear();
instance.view.wt.selections.highlight.add(priv.selStart.arr());
instance.view.wt.selections.highlight.add(priv.selEnd.arr());
}
//trigger handlers
instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col());
instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col()));
if (scrollToCell !== false) {
instance.view.scrollViewport(coords);
}
selection.refreshBorders();
},
/**
* Destroys editor, redraws borders around cells, prepares editor
* @param {Boolean} revertOriginal
* @param {Boolean} keepEditor
*/
refreshBorders: function (revertOriginal, keepEditor) {
if (!keepEditor) {
editorManager.destroyEditor(revertOriginal);
}
instance.view.render();
if (selection.isSelected() && !keepEditor) {
editorManager.prepareEditor();
}
},
/**
* Returns information if we have a multiselection
* @return {Boolean}
*/
isMultiple: function () {
return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row());
},
/**
* Selects cell relative to current cell (if possible)
*/
transformStart: function (rowDelta, colDelta, force) {
if (priv.selStart.row() + rowDelta > instance.countRows() - 1) {
if (force && priv.settings.minSpareRows > 0) {
instance.alter("insert_row", instance.countRows());
}
else if (priv.settings.autoWrapCol) {
rowDelta = 1 - instance.countRows();
colDelta = priv.selStart.col() + colDelta == instance.countCols() - 1 ? 1 - instance.countCols() : 1;
}
}
else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) {
rowDelta = instance.countRows() - 1;
colDelta = priv.selStart.col() + colDelta == 0 ? instance.countCols() - 1 : -1;
}
if (priv.selStart.col() + colDelta > instance.countCols() - 1) {
if (force && priv.settings.minSpareCols > 0) {
instance.alter("insert_col", instance.countCols());
}
else if (priv.settings.autoWrapRow) {
rowDelta = priv.selStart.row() + rowDelta == instance.countRows() - 1 ? 1 - instance.countRows() : 1;
colDelta = 1 - instance.countCols();
}
}
else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) {
rowDelta = priv.selStart.row() + rowDelta == 0 ? instance.countRows() - 1 : -1;
colDelta = instance.countCols() - 1;
}
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = {
row: priv.selStart.row() + rowDelta,
col: priv.selStart.col() + colDelta
};
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeStart(coords);
},
/**
* Sets selection end cell relative to current selection end cell (if possible)
*/
transformEnd: function (rowDelta, colDelta) {
if (priv.selEnd.exists()) {
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = {
row: priv.selEnd.row() + rowDelta,
col: priv.selEnd.col() + colDelta
};
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeEnd(coords);
}
},
/**
* Returns true if currently there is a selection on screen, false otherwise
* @return {Boolean}
*/
isSelected: function () {
return priv.selEnd.exists();
},
/**
* Returns true if coords is within current selection coords
* @return {Boolean}
*/
inInSelection: function (coords) {
if (!selection.isSelected()) {
return false;
}
var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col);
},
/**
* Deselects all selected cells
*/
deselect: function () {
if (!selection.isSelected()) {
return;
}
instance.selection.inProgress = false; //needed by HT inception
priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one
instance.view.wt.selections.current.clear();
instance.view.wt.selections.area.clear();
editorManager.destroyEditor();
selection.refreshBorders();
instance.PluginHooks.run('afterDeselect');
},
/**
* Select all cells
*/
selectAll: function () {
if (!priv.settings.multiSelect) {
return;
}
selection.setRangeStart({
row: 0,
col: 0
});
selection.setRangeEnd({
row: instance.countRows() - 1,
col: instance.countCols() - 1
}, false);
},
/**
* Deletes data from selected cells
*/
empty: function () {
if (!selection.isSelected()) {
return;
}
var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
var r, c, changes = [];
for (r = corners.TL.row; r <= corners.BR.row; r++) {
for (c = corners.TL.col; c <= corners.BR.col; c++) {
if (!instance.getCellMeta(r, c).readOnly) {
changes.push([r, c, '']);
}
}
}
instance.setDataAtCell(changes);
}
};
this.autofill = autofill = { //this public assignment is only temporary
handle: null,
/**
* Create fill handle and fill border objects
*/
init: function () {
if (!autofill.handle) {
autofill.handle = {};
}
else {
autofill.handle.disabled = false;
}
},
/**
* Hide fill handle and fill border permanently
*/
disable: function () {
autofill.handle.disabled = true;
},
/**
* Selects cells down to the last row in the left column, then fills down to that cell
*/
selectAdjacent: function () {
var select, data, r, maxR, c;
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
data = datamap.getAll();
rows : for (r = select[2] + 1; r < instance.countRows(); r++) {
for (c = select[1]; c <= select[3]; c++) {
if (data[r][c]) {
break rows;
}
}
if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
maxR = r;
}
}
if (maxR) {
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([select[0], select[1]]);
instance.view.wt.selections.fill.add([maxR, select[3]]);
autofill.apply();
}
},
/**
* Apply fill values to the area in fill border, omitting the selection border
*/
apply: function () {
var drag, select, start, end, _data;
autofill.handle.isDragged = 0;
drag = instance.view.wt.selections.fill.getCorners();
if (!drag) {
return;
}
instance.view.wt.selections.fill.clear();
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
if (drag[0] === select[0] && drag[1] < select[1]) {
start = {
row: drag[0],
col: drag[1]
};
end = {
row: drag[2],
col: select[1] - 1
};
}
else if (drag[0] === select[0] && drag[3] > select[3]) {
start = {
row: drag[0],
col: select[3] + 1
};
end = {
row: drag[2],
col: drag[3]
};
}
else if (drag[0] < select[0] && drag[1] === select[1]) {
start = {
row: drag[0],
col: drag[1]
};
end = {
row: select[0] - 1,
col: drag[3]
};
}
else if (drag[2] > select[2] && drag[1] === select[1]) {
start = {
row: select[2] + 1,
col: drag[1]
};
end = {
row: drag[2],
col: drag[3]
};
}
if (start) {
_data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords()));
instance.PluginHooks.run('beforeAutofill', start, end, _data);
grid.populateFromArray(start, _data, end, 'autofill');
selection.setRangeStart({row: drag[0], col: drag[1]});
selection.setRangeEnd({row: drag[2], col: drag[3]});
}
/*else {
//reset to avoid some range bug
selection.refreshBorders();
}*/
},
/**
* Show fill border
*/
showBorder: function (coords) {
coords.row = coords[0];
coords.col = coords[1];
var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]);
if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) {
coords = [coords.row, corners.BR.col];
}
else if (priv.settings.fillHandle !== 'vertical') {
coords = [corners.BR.row, coords.col];
}
else {
return; //wrong direction
}
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]);
instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]);
instance.view.wt.selections.fill.add(coords);
instance.view.render();
}
};
this.init = function () {
instance.PluginHooks.run('beforeInit');
this.view = new Handsontable.TableView(this);
editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap);
this.updateSettings(priv.settings, true);
this.parseSettingsFromDOM();
this.forceFullRender = true; //used when data was changed
this.view.render();
if (typeof priv.firstRun === 'object') {
instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]);
priv.firstRun = false;
}
instance.PluginHooks.run('afterInit');
};
function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
var resolved = false;
return {
validatorsInQueue: 0,
addValidatorToQueue: function () {
this.validatorsInQueue++;
resolved = false;
},
removeValidatorFormQueue: function () {
this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
this.checkIfQueueIsEmpty();
},
onQueueEmpty: function () {
},
checkIfQueueIsEmpty: function () {
if (this.validatorsInQueue == 0 && resolved == false) {
resolved = true;
this.onQueueEmpty();
}
}
};
}
function validateChanges(changes, source, callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = resolve;
for (var i = changes.length - 1; i >= 0; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
}
else {
var row = changes[i][0];
var col = datamap.propToCol(changes[i][1]);
var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user)
var cellProperties = instance.getCellMeta(row, logicalCol);
if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') {
if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) {
changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string
}
}
if (instance.getCellValidator(cellProperties)) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) {
return function (result) {
if (typeof result !== 'boolean') {
throw new Error("Validation error: result is not boolean");
}
if (result === false && cellProperties.allowInvalid === false) {
changes.splice(i, 1); // cancel the change
cellProperties.valid = true; // we cancelled the change, so cell value is still valid
--i;
}
waitingForValidator.removeValidatorFormQueue();
}
})(i, cellProperties)
, source);
}
}
}
waitingForValidator.checkIfQueueIsEmpty();
function resolve() {
var beforeChangeResult;
if (changes.length) {
beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source);
if (typeof beforeChangeResult === 'function') {
$.when(result).then(function () {
callback(); //called when async validators and async beforeChange are resolved
});
}
else if (beforeChangeResult === false) {
changes.splice(0, changes.length); //invalidate all changes (remove everything from array)
}
}
if (typeof beforeChangeResult !== 'function') {
callback(); //called when async validators are resolved and beforeChange was not async
}
}
}
/**
* Internal function to apply changes. Called after validateChanges
* @param {Array} changes Array in form of [row, prop, oldValue, newValue]
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
function applyChanges(changes, source) {
var i = changes.length - 1;
if (i < 0) {
return;
}
for (; 0 <= i; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
continue;
}
if (priv.settings.minSpareRows) {
while (changes[i][0] > instance.countRows() - 1) {
datamap.createRow();
}
}
if (instance.dataType === 'array' && priv.settings.minSpareCols) {
while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
datamap.createCol();
}
}
datamap.set(changes[i][0], changes[i][1], changes[i][3]);
}
instance.forceFullRender = true; //used when data was changed
grid.adjustRowsAndCols();
selection.refreshBorders(null, true);
instance.PluginHooks.run('afterChange', changes, source || 'edit');
}
this.validateCell = function (value, cellProperties, callback, source) {
var validator = instance.getCellValidator(cellProperties);
if (Object.prototype.toString.call(validator) === '[object RegExp]') {
validator = (function (validator) {
return function (value, callback) {
callback(validator.test(value));
}
})(validator);
}
if (typeof validator == 'function') {
value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source);
// To provide consistent behaviour, validation should be always asynchronous
setTimeout(function () {
validator.call(cellProperties, value, function (valid) {
cellProperties.valid = valid;
valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source);
callback(valid);
});
});
} else { //resolve callback even if validator function was not found
cellProperties.valid = true;
callback(true);
}
};
function setDataInputToArray(row, prop_or_col, value) {
if (typeof row === "object") { //is it an array of changes
return row;
}
else if ($.isPlainObject(value)) { //backwards compatibility
return value;
}
else {
return [
[row, prop_or_col, value]
];
}
}
/**
* Set data at given cell
* @public
* @param {Number|Array} row or array of changes in format [[row, col, value], ...]
* @param {Number|String} col or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtCell = function (row, col, value, source) {
var input = setDataInputToArray(row, col, value)
, i
, ilen
, changes = []
, prop;
for (i = 0, ilen = input.length; i < ilen; i++) {
if (typeof input[i] !== 'object') {
throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
}
if (typeof input[i][1] !== 'number') {
throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
}
prop = datamap.colToProp(input[i][1]);
changes.push([
input[i][0],
prop,
datamap.get(input[i][0], prop),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = col;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Set data at given row property
* @public
* @param {Number|Array} row or array of changes in format [[row, prop, value], ...]
* @param {String} prop or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtRowProp = function (row, prop, value, source) {
var input = setDataInputToArray(row, prop, value)
, i
, ilen
, changes = [];
for (i = 0, ilen = input.length; i < ilen; i++) {
changes.push([
input[i][0],
input[i][1],
datamap.get(input[i][0], input[i][1]),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = prop;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Listen to document body keyboard input
*/
this.listen = function () {
Handsontable.activeGuid = instance.guid;
if (document.activeElement && document.activeElement !== document.body) {
document.activeElement.blur();
}
else if (!document.activeElement) { //IE
document.body.focus();
}
};
/**
* Stop listening to document body keyboard input
*/
this.unlisten = function () {
Handsontable.activeGuid = null;
};
/**
* Returns true if current Handsontable instance is listening on document body keyboard input
*/
this.isListening = function () {
return Handsontable.activeGuid === instance.guid;
};
/**
* Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
selection.refreshBorders(revertOriginal);
};
/**
* Populate cells at position with 2d array
* @param {Number} row Start row
* @param {Number} col Start column
* @param {Array} input 2d array
* @param {Number=} endRow End row (use when you want to cut input when certain row is reached)
* @param {Number=} endCol End column (use when you want to cut input when certain column is reached)
* @param {String=} [source="populateFromArray"]
* @param {String=} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
this.populateFromArray = function (row, col, input, endRow, endCol, source, method) {
if (!(typeof input === 'object' && typeof input[0] === 'object')) {
throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly
}
return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method);
};
/**
* Adds/removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceCol = function (col, index, amount/*, elements... */) {
return datamap.spliceCol.apply(datamap, arguments);
};
/**
* Adds/removes data from the row
* @param {Number} row Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceRow = function (row, index, amount/*, elements... */) {
return datamap.spliceRow.apply(datamap, arguments);
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @param {Object[]} coordsArr
* @returns {Object}
*/
this.getCornerCoords = function (coordsArr) {
return grid.getCornerCoords(coordsArr);
};
/**
* Returns current selection. Returns undefined if there is no selection.
* @public
* @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`]
*/
this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()];
}
};
/**
* Parse settings from DOM and CSS
* @public
*/
this.parseSettingsFromDOM = function () {
var overflow = this.rootElement.css('overflow');
if (overflow === 'scroll' || overflow === 'auto') {
this.rootElement[0].style.overflow = 'visible';
priv.settingsFromDOM.overflow = overflow;
}
else if (priv.settings.width === void 0 || priv.settings.height === void 0) {
priv.settingsFromDOM.overflow = 'auto';
}
if (priv.settings.width === void 0) {
priv.settingsFromDOM.width = this.rootElement.width();
}
else {
priv.settingsFromDOM.width = void 0;
}
priv.settingsFromDOM.height = void 0;
if (priv.settings.height === void 0) {
if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') {
//this needs to read only CSS/inline style and not actual height
//so we need to call getComputedStyle on cloned container
var clone = this.rootElement[0].cloneNode(false);
var parent = this.rootElement[0].parentNode;
if (parent) {
clone.removeAttribute('id');
parent.appendChild(clone);
var computedClientHeight = parseInt(clone.clientHeight, 10);
var computedPaddingTop = parseInt(window.getComputedStyle(clone, null).getPropertyValue('paddingTop'), 10) || 0;
var computedPaddingBottom = parseInt(window.getComputedStyle(clone, null).getPropertyValue('paddingBottom'), 10) || 0;
var computedHeight = computedClientHeight - computedPaddingTop - computedPaddingBottom;
if(isNaN(computedHeight) && clone.currentStyle){
computedHeight = parseInt(clone.currentStyle.height, 10)
}
if (computedHeight > 0) {
priv.settingsFromDOM.height = computedHeight;
}
parent.removeChild(clone);
}
}
}
};
/**
* Render visible data
* @public
*/
this.render = function () {
if (instance.view) {
instance.forceFullRender = true; //used when data was changed
instance.parseSettingsFromDOM();
selection.refreshBorders(null, true);
}
};
/**
* Load data from array
* @public
* @param {Array} data
*/
this.loadData = function (data) {
if (typeof data === 'object' && data !== null) {
if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it
//when data is not an array, attempt to make a single-row array of it
data = [data];
}
}
else if(data === null) {
data = [];
var row;
for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
row = [];
for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
row.push(null);
}
data.push(row);
}
}
else {
throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)");
}
priv.isPopulated = false;
GridSettings.prototype.data = data;
if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) {
instance.dataType = 'array';
}
else if (typeof priv.settings.dataSchema === 'function') {
instance.dataType = 'function';
}
else {
instance.dataType = 'object';
}
datamap = new Handsontable.DataMap(instance, priv, GridSettings);
clearCellSettingCache();
grid.adjustRowsAndCols();
instance.PluginHooks.run('afterLoadData');
if (priv.firstRun) {
priv.firstRun = [null, 'loadData'];
}
else {
instance.PluginHooks.run('afterChange', null, 'loadData');
instance.render();
}
priv.isPopulated = true;
function clearCellSettingCache() {
priv.cellSettings.length = 0;
}
};
/**
* Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data
* @public
* @param {Number} r (Optional) From row
* @param {Number} c (Optional) From col
* @param {Number} r2 (Optional) To row
* @param {Number} c2 (Optional) To col
* @return {Array|Object}
*/
this.getData = function (r, c, r2, c2) {
if (typeof r === 'undefined') {
return datamap.getAll();
}
else {
return datamap.getRange({row: r, col: c}, {row: r2, col: c2}, datamap.DESTINATION_RENDERER);
}
};
this.getCopyableData = function (startRow, startCol, endRow, endCol) {
return datamap.getCopyableText({row: startRow, col: startCol}, {row: endRow, col: endCol});
}
/**
* Update settings
* @public
*/
this.updateSettings = function (settings, init) {
var i, clen;
if (typeof settings.rows !== "undefined") {
throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?");
}
if (typeof settings.cols !== "undefined") {
throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?");
}
for (i in settings) {
if (i === 'data') {
continue; //loadData will be triggered later
}
else {
if (instance.PluginHooks.hooks[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) {
if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) {
instance.PluginHooks.add(i, settings[i]);
}
}
else {
// Update settings
if (!init && settings.hasOwnProperty(i)) {
GridSettings.prototype[i] = settings[i];
}
//launch extensions
if (Handsontable.extension[i]) {
priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]);
}
}
}
}
// Load data or create data map
if (settings.data === void 0 && priv.settings.data === void 0) {
instance.loadData(null); //data source created just now
}
else if (settings.data !== void 0) {
instance.loadData(settings.data); //data source given as option
}
else if (settings.columns !== void 0) {
datamap.createMap();
}
// Init columns constructors configuration
clen = instance.countCols();
//Clear cellSettings cache
priv.cellSettings.length = 0;
if (clen > 0) {
var proto, column;
for (i = 0; i < clen; i++) {
priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
// shortcut for prototype
proto = priv.columnSettings[i].prototype;
// Use settings provided by user
if (GridSettings.prototype.columns) {
column = GridSettings.prototype.columns[i];
Handsontable.helper.extend(proto, column);
Handsontable.helper.extend(proto, expandType(column));
}
}
}
if (typeof settings.fillHandle !== "undefined") {
if (autofill.handle && settings.fillHandle === false) {
autofill.disable();
}
else if (!autofill.handle && settings.fillHandle !== false) {
autofill.init();
}
}
if (typeof settings.className !== "undefined") {
if (GridSettings.prototype.className) {
instance.rootElement.removeClass(GridSettings.prototype.className);
}
if (settings.className) {
instance.rootElement.addClass(settings.className);
}
}
if (!init) {
instance.PluginHooks.run('afterUpdateSettings');
}
grid.adjustRowsAndCols();
if (instance.view && !priv.firstRun) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
this.getValue = function () {
var sel = instance.getSelected();
if (GridSettings.prototype.getValue) {
if (typeof GridSettings.prototype.getValue === 'function') {
return GridSettings.prototype.getValue.call(instance);
}
else if (sel) {
return instance.getData()[sel[0]][GridSettings.prototype.getValue];
}
}
else if (sel) {
return instance.getDataAtCell(sel[0], sel[1]);
}
};
function expandType(obj) {
if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type
var type, expandedType = {};
if (typeof obj.type === 'object') {
type = obj.type;
}
else if (typeof obj.type === 'string') {
type = Handsontable.cellTypes[obj.type];
if (type === void 0) {
throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
}
for (var i in type) {
if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
expandedType[i] = type[i];
}
}
return expandedType;
}
/**
* Returns current settings object
* @return {Object}
*/
this.getSettings = function () {
return priv.settings;
};
/**
* Returns current settingsFromDOM object
* @return {Object}
*/
this.getSettingsFromDOM = function () {
return priv.settingsFromDOM;
};
/**
* Clears grid
* @public
*/
this.clear = function () {
selection.selectAll();
selection.empty();
};
/**
* Inserts or removes rows and columns
* @param {String} action See grid.alter for possible values
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
* @public
*/
this.alter = function (action, index, amount, source, keepEmptyRows) {
grid.alter(action, index, amount, source, keepEmptyRows);
};
/**
* Returns <td> element corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Element}
*/
this.getCell = function (row, col) {
return instance.view.getCellAtCoords({row: row, col: col});
};
/**
* Returns property name associated with column number
* @param {Number} col
* @public
* @return {String}
*/
this.colToProp = function (col) {
return datamap.colToProp(col);
};
/**
* Returns column number associated with property name
* @param {String} prop
* @public
* @return {Number}
*/
this.propToCol = function (prop) {
return datamap.propToCol(prop);
};
/**
* Return value at `row`, `col`
* @param {Number} row
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCell = function (row, col) {
return datamap.get(row, datamap.colToProp(col));
};
/**
* Return value at `row`, `prop`
* @param {Number} row
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtRowProp = function (row, prop) {
return datamap.get(row, prop);
};
/**
* Return value at `col`
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCol = function (col) {
return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}, datamap.DESTINATION_RENDERER));
};
/**
* Return value at `prop`
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtProp = function (prop) {
return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}, datamap.DESTINATION_RENDERER));
};
/**
* Return value at `row`
* @param {Number} row
* @public
* @return value (mixed data type)
*/
this.getDataAtRow = function (row) {
return priv.settings.data[row];
};
/**
* Returns cell meta data object corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Object}
*/
this.getCellMeta = function (row, col) {
var prop = datamap.colToProp(col)
, cellProperties;
row = translateRowIndex(row);
col = translateColIndex(col);
if ("undefined" === typeof priv.columnSettings[col]) {
priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache
cellProperties.row = row;
cellProperties.col = col;
cellProperties.prop = prop;
cellProperties.instance = instance;
instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties);
Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta
if (cellProperties.cells) {
var settings = cellProperties.cells.call(cellProperties, row, col, prop);
if (settings) {
Handsontable.helper.extend(cellProperties, settings);
Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells
}
}
instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties);
return cellProperties;
/**
* If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
* we need to translate logical (stored) row index to physical (displayed) index.
* @param row - original row index
* @returns {int} translated row index
*/
function translateRowIndex(row){
var getVars = {row: row};
instance.PluginHooks.execute('beforeGet', getVars);
return getVars.row;
}
/**
* If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin)
* we need to translate logical (stored) column index to physical (displayed) index.
* @param col - original column index
* @returns {int} - translated column index
*/
function translateColIndex(col){
return Handsontable.PluginHooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp
}
};
var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer');
this.getCellRenderer = function (row, col) {
var renderer = rendererLookup.call(this, row, col);
return Handsontable.renderers.getRenderer(renderer);
};
this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor');
this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator');
/**
* Validates all cells using their validator functions and calls callback when finished. Does not render the view
* @param callback
*/
this.validateCells = function (callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = callback;
var i = instance.countRows() - 1;
while (i >= 0) {
var j = instance.countCols() - 1;
while (j >= 0) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () {
waitingForValidator.removeValidatorFormQueue();
}, 'validateCells');
j--;
}
i--;
}
waitingForValidator.checkIfQueueIsEmpty();
};
/**
* Return array of row headers (if they are enabled). If param `row` given, return header at given row as string
* @param {Number} row (Optional)
* @return {Array|String}
*/
this.getRowHeader = function (row) {
if (row === void 0) {
var out = [];
for (var i = 0, ilen = instance.countRows(); i < ilen; i++) {
out.push(instance.getRowHeader(i));
}
return out;
}
else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) {
return priv.settings.rowHeaders[row];
}
else if (typeof priv.settings.rowHeaders === 'function') {
return priv.settings.rowHeaders(row);
}
else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') {
return row + 1;
}
else {
return priv.settings.rowHeaders;
}
};
/**
* Returns information of this table is configured to display row headers
* @returns {boolean}
*/
this.hasRowHeaders = function () {
return !!priv.settings.rowHeaders;
};
/**
* Returns information of this table is configured to display column headers
* @returns {boolean}
*/
this.hasColHeaders = function () {
if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null
return !!priv.settings.colHeaders;
}
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
if (instance.getColHeader(i)) {
return true;
}
}
return false;
};
/**
* Return array of column headers (if they are enabled). If param `col` given, return header at given column as string
* @param {Number} col (Optional)
* @return {Array|String}
*/
this.getColHeader = function (col) {
if (col === void 0) {
var out = [];
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
out.push(instance.getColHeader(i));
}
return out;
}
else {
col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
return priv.settings.columns[col].title;
}
else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) {
return priv.settings.colHeaders[col];
}
else if (typeof priv.settings.colHeaders === 'function') {
return priv.settings.colHeaders(col);
}
else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
return Handsontable.helper.spreadsheetColumnLabel(col);
}
else {
return priv.settings.colHeaders;
}
}
};
/**
* Return column width from settings (no guessing). Private use intended
* @param {Number} col
* @return {Number}
*/
this._getColWidthFromSettings = function (col) {
var cellProperties = instance.getCellMeta(0, col);
var width = cellProperties.width;
if (width === void 0 || width === priv.settings.width) {
width = cellProperties.colWidths;
}
if (width !== void 0 && width !== null) {
switch (typeof width) {
case 'object': //array
width = width[col];
break;
case 'function':
width = width(col);
break;
}
if (typeof width === 'string') {
width = parseInt(width, 10);
}
}
return width;
};
/**
* Return column width
* @param {Number} col
* @return {Number}
*/
this.getColWidth = function (col) {
col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col);
var response = {
width: instance._getColWidthFromSettings(col)
};
if (!response.width) {
response.width = 50;
}
instance.PluginHooks.run('afterGetColWidth', col, response);
return response.width;
};
/**
* Return total number of rows in grid
* @return {Number}
*/
this.countRows = function () {
return priv.settings.data.length;
};
/**
* Return total number of columns in grid
* @return {Number}
*/
this.countCols = function () {
if (instance.dataType === 'object' || instance.dataType === 'function') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else {
return datamap.colToPropCache.length;
}
}
else if (instance.dataType === 'array') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) {
return priv.settings.data[0].length;
}
else {
return 0;
}
}
};
/**
* Return index of first visible row
* @return {Number}
*/
this.rowOffset = function () {
return instance.view.wt.getSetting('offsetRow');
};
/**
* Return index of first visible column
* @return {Number}
*/
this.colOffset = function () {
return instance.view.wt.getSetting('offsetColumn');
};
/**
* Return number of visible rows. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1;
};
/**
* Return number of visible columns. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1;
};
/**
* Return number of empty rows
* @return {Boolean} ending If true, will only count empty rows at the end of the data source
*/
this.countEmptyRows = function (ending) {
var i = instance.countRows() - 1
, empty = 0;
while (i >= 0) {
datamap.get(i, 0);
if (instance.isEmptyRow(datamap.getVars.row)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return number of empty columns
* @return {Boolean} ending If true, will only count empty columns at the end of the data source row
*/
this.countEmptyCols = function (ending) {
if (instance.countRows() < 1) {
return 0;
}
var i = instance.countCols() - 1
, empty = 0;
while (i >= 0) {
if (instance.isEmptyCol(i)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return true if the row at the given index is empty, false otherwise
* @param {Number} r Row index
* @return {Boolean}
*/
this.isEmptyRow = function (r) {
return priv.settings.isEmptyRow.call(instance, r);
};
/**
* Return true if the column at the given index is empty, false otherwise
* @param {Number} c Column index
* @return {Boolean}
*/
this.isEmptyCol = function (c) {
return priv.settings.isEmptyCol.call(instance, c);
};
/**
* Selects cell on grid. Optionally selects range to another cell
* @param {Number} row
* @param {Number} col
* @param {Number} [endRow]
* @param {Number} [endCol]
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection
* @public
* @return {Boolean}
*/
this.selectCell = function (row, col, endRow, endCol, scrollToCell) {
if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
return false;
}
if (typeof endRow !== "undefined") {
if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
return false;
}
if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
return false;
}
}
priv.selStart.coords({row: row, col: col});
if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell)
}
instance.listen();
if (typeof endRow === "undefined") {
selection.setRangeEnd({row: row, col: col}, scrollToCell);
}
else {
selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell);
}
instance.selection.finish();
return true;
};
this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
arguments[1] = datamap.propToCol(arguments[1]);
if (typeof arguments[3] !== "undefined") {
arguments[3] = datamap.propToCol(arguments[3]);
}
return instance.selectCell.apply(instance, arguments);
};
/**
* Deselects current sell selection on grid
* @public
*/
this.deselectCell = function () {
selection.deselect();
};
/**
* Remove grid from DOM
* @public
*/
this.destroy = function () {
instance.clearTimeouts();
if (instance.view) { //in case HT is destroyed before initialization has finished
instance.view.wt.destroy();
}
instance.rootElement.empty();
instance.rootElement.removeData('handsontable');
instance.rootElement.off('.handsontable');
$(window).off('.' + instance.guid);
$document.off('.' + instance.guid);
$body.off('.' + instance.guid);
instance.PluginHooks.run('afterDestroy');
};
/**
* Returns active editor object
* @returns {Object}
*/
this.getActiveEditor = function(){
return editorManager.getActiveEditor();
};
/**
* Return Handsontable instance
* @public
* @return {Object}
*/
this.getInstance = function () {
return instance.rootElement.data("handsontable");
};
(function () {
// Create new instance of plugin hooks
instance.PluginHooks = new Handsontable.PluginHookClass();
// Upgrade methods to call of global PluginHooks instance
var _run = instance.PluginHooks.run
, _exe = instance.PluginHooks.execute;
instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) {
_run.call(this, instance, key, p1, p2, p3, p4, p5);
Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5);
};
instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) {
var globalHandlerResult = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5);
var localHandlerResult = _exe.call(this, instance, key, globalHandlerResult, p2, p3, p4, p5);
return typeof localHandlerResult == 'undefined' ? globalHandlerResult : localHandlerResult;
};
// Map old API with new methods
instance.addHook = function () {
instance.PluginHooks.add.apply(instance.PluginHooks, arguments);
};
instance.addHookOnce = function () {
instance.PluginHooks.once.apply(instance.PluginHooks, arguments);
};
instance.removeHook = function () {
instance.PluginHooks.remove.apply(instance.PluginHooks, arguments);
};
instance.runHooks = function () {
instance.PluginHooks.run.apply(instance.PluginHooks, arguments);
};
instance.runHooksAndReturn = function () {
return instance.PluginHooks.execute.apply(instance.PluginHooks, arguments);
};
})();
this.timeouts = {};
/**
* Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called
* @public
*/
this.registerTimeout = function (key, handle, ms) {
clearTimeout(this.timeouts[key]);
this.timeouts[key] = setTimeout(handle, ms || 0);
};
/**
* Clears all known timeouts
* @public
*/
this.clearTimeouts = function () {
for (var key in this.timeouts) {
if (this.timeouts.hasOwnProperty(key)) {
clearTimeout(this.timeouts[key]);
}
}
};
/**
* Handsontable version
*/
this.version = '0.10.5'; //inserted by grunt from package.json
};
var DefaultSettings = function () {};
DefaultSettings.prototype = {
data: void 0,
width: void 0,
height: void 0,
startRows: 5,
startCols: 5,
rowHeaders: null,
colHeaders: null,
minRows: 0,
minCols: 0,
maxRows: Infinity,
maxCols: Infinity,
minSpareRows: 0,
minSpareCols: 0,
multiSelect: true,
fillHandle: true,
fixedRowsTop: 0,
fixedColumnsLeft: 0,
outsideClickDeselects: true,
enterBeginsEditing: true,
enterMoves: {row: 1, col: 0},
tabMoves: {row: 0, col: 1},
autoWrapRow: false,
autoWrapCol: false,
copyRowsLimit: 1000,
copyColsLimit: 1000,
pasteMode: 'overwrite',
currentRowClassName: void 0,
currentColClassName: void 0,
stretchH: 'hybrid',
isEmptyRow: function (r) {
var val;
for (var c = 0, clen = this.countCols(); c < clen; c++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
isEmptyCol: function (c) {
var val;
for (var r = 0, rlen = this.countRows(); r < rlen; r++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
observeDOMVisibility: true,
allowInvalid: true,
invalidCellClassName: 'htInvalid',
placeholderCellClassName: 'htPlaceholder',
readOnlyCellClassName: 'htDimmed',
fragmentSelection: false,
readOnly: false,
nativeScrollbars: false,
type: 'text',
copyable: true,
debug: false //shows debug overlays in Walkontable
};
Handsontable.DefaultSettings = DefaultSettings;
$.fn.handsontable = function (action) {
var i
, ilen
, args
, output
, userSettings
, $this = this.first() // Use only first element from list
, instance = $this.data('handsontable');
// Init case
if (typeof action !== 'string') {
userSettings = action || {};
if (instance) {
instance.updateSettings(userSettings);
}
else {
instance = new Handsontable.Core($this, userSettings);
$this.data('handsontable', instance);
instance.init();
}
return $this;
}
// Action case
else {
args = [];
if (arguments.length > 1) {
for (i = 1, ilen = arguments.length; i < ilen; i++) {
args.push(arguments[i]);
}
}
if (instance) {
if (typeof instance[action] !== 'undefined') {
output = instance[action].apply(instance, args);
}
else {
throw new Error('Handsontable do not provide action: ' + action);
}
}
return output;
}
};
(function (window) {
'use strict';
function MultiMap() {
var map = {
arrayMap: [],
weakMap: new WeakMap()
};
return {
'get': function (key) {
if (canBeAnArrayMapKey(key)) {
return map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
return map.weakMap.get(key);
}
},
'set': function (key, value) {
if (canBeAnArrayMapKey(key)) {
map.arrayMap[key] = value;
} else if (canBeAWeakMapKey(key)) {
map.weakMap.set(key, value);
} else {
throw new Error('Invalid key type');
}
},
'delete': function (key) {
if (canBeAnArrayMapKey(key)) {
delete map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
map.weakMap['delete'](key); //Delete must be called using square bracket notation, because IE8 does not handle using `delete` with dot notation
}
}
};
function canBeAnArrayMapKey(obj){
return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number');
}
function canBeAWeakMapKey(obj){
return obj !== null && (typeof obj == 'object' || typeof obj == 'function');
}
function isNaNSymbol(obj){
return obj !== obj; // NaN === NaN is always false
}
}
if (!window.MultiMap){
window.MultiMap = MultiMap;
}
})(window);
/**
* Handsontable TableView constructor
* @param {Object} instance
*/
Handsontable.TableView = function (instance) {
var that = this
, $window = $(window)
, $documentElement = $(document.documentElement);
this.instance = instance;
this.settings = instance.getSettings();
this.settingsFromDOM = instance.getSettingsFromDOM();
instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
// in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+
instance.rootElement.addClass('handsontable');
var table = document.createElement('TABLE');
table.className = 'htCore';
this.THEAD = document.createElement('THEAD');
table.appendChild(this.THEAD);
this.TBODY = document.createElement('TBODY');
table.appendChild(this.TBODY);
instance.$table = $(table);
instance.rootElement.prepend(instance.$table);
instance.rootElement.on('mousedown.handsontable', function (event) {
if (!that.isTextSelectionAllowed(event.target)) {
clearTextSelection();
event.preventDefault();
window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe.
}
});
$documentElement.on('keyup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && !event.shiftKey) {
instance.selection.finish();
}
});
var isMouseDown;
$documentElement.on('mouseup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button
instance.selection.finish();
}
isMouseDown = false;
if (instance.autofill.handle && instance.autofill.handle.isDragged) {
if (instance.autofill.handle.isDragged > 1) {
instance.autofill.apply();
}
instance.autofill.handle.isDragged = 0;
}
if (Handsontable.helper.isOutsideInput(document.activeElement)) {
instance.unlisten();
}
});
$documentElement.on('mousedown.' + instance.guid, function (event) {
var next = event.target;
if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar
while (next !== document.documentElement) {
if (next === null) {
return; //click on something that was a row but now is detached (possibly because your click triggered a rerender)
}
if (next === instance.rootElement[0] || next.nodeName === 'HANDSONTABLE-TABLE') {
return; //click inside container or Web Component (HANDSONTABLE-TABLE is the name of the custom element)
}
next = next.parentNode;
}
}
if (that.settings.outsideClickDeselects) {
instance.deselectCell();
}
else {
instance.destroyEditor();
}
});
instance.rootElement.on('mousedown.handsontable', '.dragdealer', function () {
instance.destroyEditor();
});
instance.$table.on('selectstart', function (event) {
if (that.settings.fragmentSelection) {
return;
}
//https://github.com/warpech/jquery-handsontable/issues/160
//selectstart is IE only event. Prevent text from being selected when performing drag down in IE8
event.preventDefault();
});
var clearTextSelection = function () {
//http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
var walkontableConfig = {
debug: function () {
return that.settings.debug;
},
table: table,
stretchH: this.settings.stretchH,
data: instance.getDataAtCell,
totalRows: instance.countRows,
totalColumns: instance.countCols,
nativeScrollbars: this.settings.nativeScrollbars,
offsetRow: 0,
offsetColumn: 0,
width: this.getWidth(),
height: this.getHeight(),
fixedColumnsLeft: function () {
return that.settings.fixedColumnsLeft;
},
fixedRowsTop: function () {
return that.settings.fixedRowsTop;
},
rowHeaders: function () {
return instance.hasRowHeaders() ? [function (index, TH) {
that.appendRowHeader(index, TH);
}] : []
},
columnHeaders: function () {
return instance.hasColHeaders() ? [function (index, TH) {
that.appendColHeader(index, TH);
}] : []
},
columnWidth: instance.getColWidth,
cellRenderer: function (row, col, TD) {
var prop = that.instance.colToProp(col)
, cellProperties = that.instance.getCellMeta(row, col)
, renderer = that.instance.getCellRenderer(cellProperties);
var value = that.instance.getDataAtRowProp(row, prop);
renderer(that.instance, TD, row, col, prop, value, cellProperties);
that.instance.PluginHooks.run('afterRenderer', TD, row, col, prop, value, cellProperties);
},
selections: {
current: {
className: 'current',
border: {
width: 2,
color: '#5292F7',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple()
}
}
},
area: {
className: 'area',
border: {
width: 1,
color: '#89AFF9',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple()
}
}
},
highlight: {
highlightRowClassName: that.settings.currentRowClassName,
highlightColumnClassName: that.settings.currentColClassName
},
fill: {
className: 'fill',
border: {
width: 1,
color: 'red',
style: 'solid'
}
}
},
hideBorderOnMouseDownOver: function () {
return that.settings.fragmentSelection;
},
onCellMouseDown: function (event, coords, TD) {
instance.listen();
isMouseDown = true;
var coordsObj = {row: coords[0], col: coords[1]};
if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button
//do nothing
}
else if (event.shiftKey) {
instance.selection.setRangeEnd(coordsObj);
}
else {
instance.selection.setRangeStart(coordsObj);
}
instance.PluginHooks.run('afterOnCellMouseDown', event, coords, TD);
},
/*onCellMouseOut: function (/*event, coords, TD* /) {
if (isMouseDown && that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}
},*/
onCellMouseOver: function (event, coords, TD) {
var coordsObj = {row: coords[0], col: coords[1]};
if (isMouseDown) {
/*if (that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}*/
instance.selection.setRangeEnd(coordsObj);
}
else if (instance.autofill.handle && instance.autofill.handle.isDragged) {
instance.autofill.handle.isDragged++;
instance.autofill.showBorder(coords);
}
instance.PluginHooks.run('afterOnCellMouseOver', event, coords, TD);
},
onCellCornerMouseDown: function (event) {
instance.autofill.handle.isDragged = 1;
event.preventDefault();
instance.PluginHooks.run('afterOnCellCornerMouseDown', event);
},
onCellCornerDblClick: function () {
instance.autofill.selectAdjacent();
},
beforeDraw: function (force) {
that.beforeRender(force);
},
onDraw: function(force){
that.onDraw(force);
},
onScrollVertically: function () {
instance.runHooks('afterScrollVertically');
},
onScrollHorizontally: function () {
instance.runHooks('afterScrollHorizontally');
}
};
instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig);
this.wt = new Walkontable(walkontableConfig);
$window.on('resize.' + instance.guid, function () {
instance.registerTimeout('resizeTimeout', function () {
instance.parseSettingsFromDOM();
var newWidth = that.getWidth();
var newHeight = that.getHeight();
if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) {
instance.forceFullRender = true;
that.render();
walkontableConfig.width = newWidth;
walkontableConfig.height = newHeight;
}
}, 60);
});
$(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) {
if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar
event.stopPropagation();
}
});
$documentElement.on('click.' + instance.guid, function () {
if (that.settings.observeDOMVisibility) {
if (that.wt.drawInterrupted) {
that.instance.forceFullRender = true;
that.render();
}
}
});
};
Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) {
if ( Handsontable.helper.isInput(el) ) {
return (true);
}
if (this.settings.fragmentSelection && this.wt.wtDom.isChildOf(el, this.TBODY)) {
return (true);
}
return false;
};
Handsontable.TableView.prototype.isCellEdited = function () {
var activeEditor = this.instance.getActiveEditor();
return activeEditor && activeEditor.isOpened();
};
Handsontable.TableView.prototype.getWidth = function () {
var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width;
return typeof val === 'function' ? val() : val;
};
Handsontable.TableView.prototype.getHeight = function () {
var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height;
return typeof val === 'function' ? val() : val;
};
Handsontable.TableView.prototype.beforeRender = function (force) {
if (force) { //force = did Walkontable decide to do full render
this.instance.PluginHooks.run('beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
this.wt.update('width', this.getWidth());
this.wt.update('height', this.getHeight());
}
};
Handsontable.TableView.prototype.onDraw = function(force){
if (force) { //force = did Walkontable decide to do full render
this.instance.PluginHooks.run('afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.render = function () {
this.wt.draw(!this.instance.forceFullRender);
this.instance.forceFullRender = false;
this.instance.rootElement.triggerHandler('render.handsontable');
};
/**
* Returns td object given coordinates
*/
Handsontable.TableView.prototype.getCellAtCoords = function (coords) {
var td = this.wt.wtTable.getCell([coords.row, coords.col]);
if (td < 0) { //there was an exit code (cell is out of bounds)
return null;
}
else {
return td;
}
};
/**
* Scroll viewport to selection
* @param coords
*/
Handsontable.TableView.prototype.scrollViewport = function (coords) {
this.wt.scrollViewport([coords.row, coords.col]);
};
/**
* Append row header to a TH element
* @param row
* @param TH
*/
Handsontable.TableView.prototype.appendRowHeader = function (row, TH) {
if (row > -1) {
this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row));
}
else {
var DIV = document.createElement('DIV');
DIV.className = 'relative';
this.wt.wtDom.fastInnerText(DIV, '\u00A0');
this.wt.wtDom.empty(TH);
TH.appendChild(DIV);
}
};
/**
* Append column header to a TH element
* @param col
* @param TH
*/
Handsontable.TableView.prototype.appendColHeader = function (col, TH) {
var DIV = document.createElement('DIV')
, SPAN = document.createElement('SPAN');
DIV.className = 'relative';
SPAN.className = 'colHeader';
this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col));
DIV.appendChild(SPAN);
this.wt.wtDom.empty(TH);
TH.appendChild(DIV);
this.instance.PluginHooks.run('afterGetColHeader', col, TH);
};
/**
* Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar)
* @param {Number} left
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementWidth = function (left) {
var rootWidth = this.wt.wtViewport.getWorkspaceWidth();
if(this.settings.nativeScrollbars) {
return rootWidth;
}
return rootWidth - left;
};
/**
* Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar)
* @param {Number} top
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementHeight = function (top) {
var rootHeight = this.wt.wtViewport.getWorkspaceHeight();
if(this.settings.nativeScrollbars) {
return rootHeight;
}
return rootHeight - top;
};
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
(function (Handsontable) {
'use strict';
function RegisteredEditor(editorClass) {
var clazz, instances;
instances = {};
clazz = editorClass;
this.getInstance = function (hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new clazz(hotInstance);
}
return instances[hotInstance.guid];
}
}
var registeredEditorNames = {};
var registeredEditorClasses = new WeakMap();
Handsontable.editors = {
/**
* Registers editor under given name
* @param {String} editorName
* @param {Function} editorClass
*/
registerEditor: function (editorName, editorClass) {
var editor = new RegisteredEditor(editorClass);
if (typeof editorName === "string") {
registeredEditorNames[editorName] = editor;
}
registeredEditorClasses.set(editorClass, editor);
},
/**
* Returns instance (singleton) of editor class
* @param {String|Function} editorName/editorClass
* @returns {Function} editorClass
*/
getEditor: function (editorName, hotInstance) {
var editor;
if (typeof editorName == 'function') {
if (!(registeredEditorClasses.get(editorName))) {
this.registerEditor(null, editorName);
}
editor = registeredEditorClasses.get(editorName);
}
else if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
}
else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getInstance(hotInstance);
}
};
})(Handsontable);
(function(Handsontable){
'use strict';
Handsontable.EditorManager = function(instance, priv, selection){
var that = this;
var $document = $(document);
var keyCodes = Handsontable.helper.keyCode;
var activeEditor;
var init = function () {
function onKeyDown(event) {
if (!instance.isListening()) {
return;
}
if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
priv.settings.beforeOnKeyDown.call(instance, event);
}
instance.PluginHooks.run('beforeKeyDown', event);
if (!event.isImmediatePropagationStopped()) {
priv.lastKeyCode = event.keyCode;
if (selection.isSelected()) {
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (!activeEditor.isWaiting()) {
if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) {
that.openEditor('');
event.stopPropagation(); //required by HandsontableEditor
return;
}
}
var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;
switch (event.keyCode) {
case keyCodes.A:
if (ctrlDown) {
selection.selectAll(); //select all cells
event.preventDefault();
event.stopPropagation();
break;
}
case keyCodes.ARROW_UP:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionUp(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_DOWN:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionDown(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_RIGHT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionRight(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_LEFT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionLeft(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.TAB:
var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
if (event.shiftKey) {
selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
}
else {
selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
}
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
selection.empty(event);
that.prepareEditor();
event.preventDefault();
break;
case keyCodes.F2: /* F2 */
that.openEditor();
event.preventDefault(); //prevent Opera from opening Go to Page dialog
break;
case keyCodes.ENTER: /* return/enter */
if(that.isEditorOpened()){
if (activeEditor.state !== Handsontable.EditorState.WAITING){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionAfterEnter(event.shiftKey);
} else {
if (instance.getSettings().enterBeginsEditing){
that.openEditor();
} else {
moveSelectionAfterEnter(event.shiftKey);
}
}
event.preventDefault(); //don't add newline to field
event.stopImmediatePropagation(); //required by HandsontableEditor
break;
case keyCodes.ESCAPE:
if(that.isEditorOpened()){
that.closeEditorAndRestoreOriginalValue(ctrlDown);
}
event.preventDefault();
break;
case keyCodes.HOME:
if (event.ctrlKey || event.metaKey) {
rangeModifier({row: 0, col: priv.selStart.col()});
}
else {
rangeModifier({row: priv.selStart.row(), col: 0});
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.END:
if (event.ctrlKey || event.metaKey) {
rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()});
}
else {
rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1});
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_UP:
selection.transformStart(-instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(-instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page up the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_DOWN:
selection.transformStart(instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page down the window
event.stopPropagation(); //required by HandsontableEditor
break;
default:
break;
}
}
}
}
$document.on('keydown.handsontable.' + instance.guid, onKeyDown);
function onDblClick() {
// that.instance.destroyEditor();
that.openEditor();
}
instance.view.wt.update('onCellDblClick', onDblClick);
instance.addHook('afterDestroy', function(){
$document.off('keydown.handsontable.' + instance.guid);
});
function moveSelectionAfterEnter(shiftKey){
var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;
if (shiftKey) {
selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
}
else {
selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
}
}
function moveSelectionUp(shiftKey){
if (shiftKey) {
selection.transformEnd(-1, 0);
}
else {
selection.transformStart(-1, 0);
}
}
function moveSelectionDown(shiftKey){
if (shiftKey) {
selection.transformEnd(1, 0); //expanding selection down with shift
}
else {
selection.transformStart(1, 0); //move selection down
}
}
function moveSelectionRight(shiftKey){
if (shiftKey) {
selection.transformEnd(0, 1);
}
else {
selection.transformStart(0, 1);
}
}
function moveSelectionLeft(shiftKey){
if (shiftKey) {
selection.transformEnd(0, -1);
}
else {
selection.transformStart(0, -1);
}
}
};
/**
* Destroy current editor, if exists
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
this.closeEditor(revertOriginal);
};
this.getActiveEditor = function () {
return activeEditor;
};
/**
* Prepare text input to be displayed at given grid cell
*/
this.prepareEditor = function () {
if (activeEditor && activeEditor.isWaiting()){
this.closeEditor(false, false, function(dataSaved){
if(dataSaved){
that.prepareEditor();
}
});
return;
}
var row = priv.selStart.row();
var col = priv.selStart.col();
var prop = instance.colToProp(col);
var td = instance.getCell(row, col);
var originalValue = instance.getDataAtCell(row, col);
var cellProperties = instance.getCellMeta(row, col);
var editorClass = instance.getCellEditor(cellProperties);
activeEditor = Handsontable.editors.getEditor(editorClass, instance);
activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);
};
this.isEditorOpened = function () {
return activeEditor.isOpened();
};
this.openEditor = function (initialValue) {
if (!activeEditor.cellProperties.readOnly){
activeEditor.beginEditing(initialValue);
}
};
this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {
if (!activeEditor){
if(callback) {
callback(false);
}
}
else {
activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
}
};
this.closeEditorAndSaveChanges = function(ctrlDown){
return this.closeEditor(false, ctrlDown);
};
this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
return this.closeEditor(true, ctrlDown);
};
init();
};
})(Handsontable);
/**
* Utility to register renderers and common namespace for keeping reference to all renderers classes
*/
(function (Handsontable) {
'use strict';
var registeredRenderers = {};
Handsontable.renderers = {
/**
* Registers renderer under given name
* @param {String} rendererName
* @param {Function} rendererFunction
*/
registerRenderer: function (rendererName, rendererFunction) {
registeredRenderers[rendererName] = rendererFunction
},
/**
* @param {String|Function} rendererName/rendererFunction
* @returns {Function} rendererFunction
*/
getRenderer: function (rendererName) {
if (typeof rendererName == 'function'){
return rendererName;
}
if (typeof rendererName != 'string'){
throw Error('Only strings and functions can be passed as "renderer" parameter ');
}
if (!(rendererName in registeredRenderers)) {
throw Error('No editor registered under name "' + rendererName + '"');
}
return registeredRenderers[rendererName];
}
};
})(Handsontable);
/**
* DOM helper optimized for maximum performance
* It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery
* @type {WalkonableDom}
*/
Handsontable.Dom = new WalkontableDom();
/**
* Returns true if keyCode represents a printable character
* @param {Number} keyCode
* @return {Boolean}
*/
Handsontable.helper.isPrintableChar = function (keyCode) {
return ((keyCode == 32) || //space
(keyCode >= 48 && keyCode <= 57) || //0-9
(keyCode >= 96 && keyCode <= 111) || //numpad
(keyCode >= 186 && keyCode <= 192) || //;=,-./`
(keyCode >= 219 && keyCode <= 222) || //[]{}\|"'
keyCode >= 226 || //special chars (229 for Asian chars)
(keyCode >= 65 && keyCode <= 90)); //a-z
};
Handsontable.helper.isMetaKey = function (keyCode) {
var keyCodes = Handsontable.helper.keyCode;
var metaKeys = [
keyCodes.ARROW_DOWN,
keyCodes.ARROW_UP,
keyCodes.ARROW_LEFT,
keyCodes.ARROW_RIGHT,
keyCodes.HOME,
keyCodes.END,
keyCodes.DELETE,
keyCodes.BACKSPACE,
keyCodes.F1,
keyCodes.F2,
keyCodes.F3,
keyCodes.F4,
keyCodes.F5,
keyCodes.F6,
keyCodes.F7,
keyCodes.F8,
keyCodes.F9,
keyCodes.F10,
keyCodes.F11,
keyCodes.F12,
keyCodes.TAB,
keyCodes.PAGE_DOWN,
keyCodes.PAGE_UP,
keyCodes.ENTER,
keyCodes.ESCAPE,
keyCodes.SHIFT,
keyCodes.CAPS_LOCK,
keyCodes.ALT
];
return metaKeys.indexOf(keyCode) != -1;
};
Handsontable.helper.isCtrlKey = function (keyCode) {
var keys = Handsontable.helper.keyCode;
return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1;
};
/**
* Converts a value to string
* @param value
* @return {String}
*/
Handsontable.helper.stringify = function (value) {
switch (typeof value) {
case 'string':
case 'number':
return value + '';
break;
case 'object':
if (value === null) {
return '';
}
else {
return value.toString();
}
break;
case 'undefined':
return '';
break;
default:
return value.toString();
}
};
/**
* Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc
* @param index
* @returns {String}
*/
Handsontable.helper.spreadsheetColumnLabel = function (index) {
var dividend = index + 1;
var columnLabel = '';
var modulo;
while (dividend > 0) {
modulo = (dividend - 1) % 26;
columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
dividend = parseInt((dividend - modulo) / 26, 10);
}
return columnLabel;
};
/**
* Checks if value of n is a numeric one
* http://jsperf.com/isnan-vs-isnumeric/4
* @param n
* @returns {boolean}
*/
Handsontable.helper.isNumeric = function (n) {
var t = typeof n;
return t == 'number' ? !isNaN(n) && isFinite(n) :
t == 'string' ? !n.length ? false :
n.length == 1 ? /\d/.test(n) :
/^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) :
t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false;
};
Handsontable.helper.isArray = function (obj) {
return Object.prototype.toString.call(obj).match(/array/i) !== null;
};
/**
* Checks if child is a descendant of given parent node
* http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another
* @param parent
* @param child
* @returns {boolean}
*/
Handsontable.helper.isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Generates a random hex string. Used as namespace for Handsontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
Handsontable.helper.randomString = function () {
return walkontableRandomString();
};
/**
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
* Creates temporary dummy function to call it as constructor.
* Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516
* @param {Object} Child child class
* @param {Object} Parent parent class
* @return {Object} extended Child
*/
Handsontable.helper.inherit = function (Child, Parent) {
Parent.prototype.constructor = Parent;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
return Child;
};
/**
* Perform shallow extend of a target object with extension's own properties
* @param {Object} target An object that will receive the new properties
* @param {Object} extension An object containing additional properties to merge into the target
*/
Handsontable.helper.extend = function (target, extension) {
for (var i in extension) {
if (extension.hasOwnProperty(i)) {
target[i] = extension[i];
}
}
};
Handsontable.helper.getPrototypeOf = function (obj) {
var prototype;
if(typeof obj.__proto__ == "object"){
prototype = obj.__proto__;
} else {
var oldConstructor,
constructor = obj.constructor;
if (typeof obj.constructor == "function") {
oldConstructor = constructor;
if (delete obj.constructor){
constructor = obj.constructor; // get real constructor
obj.constructor = oldConstructor; // restore constructor
}
}
prototype = constructor ? constructor.prototype : null; // needed for IE
}
return prototype;
};
/**
* Factory for columns constructors.
* @param {Object} GridSettings
* @param {Array} conflictList
* @return {Object} ColumnSettings
*/
Handsontable.helper.columnFactory = function (GridSettings, conflictList) {
function ColumnSettings () {}
Handsontable.helper.inherit(ColumnSettings, GridSettings);
// Clear conflict settings
for (var i = 0, len = conflictList.length; i < len; i++) {
ColumnSettings.prototype[conflictList[i]] = void 0;
}
return ColumnSettings;
};
Handsontable.helper.translateRowsToColumns = function (input) {
var i
, ilen
, j
, jlen
, output = []
, olen = 0;
for (i = 0, ilen = input.length; i < ilen; i++) {
for (j = 0, jlen = input[i].length; j < jlen; j++) {
if (j == olen) {
output.push([]);
olen++;
}
output[j].push(input[i][j])
}
}
return output;
};
Handsontable.helper.to2dArray = function (arr) {
var i = 0
, ilen = arr.length;
while (i < ilen) {
arr[i] = [arr[i]];
i++;
}
};
Handsontable.helper.extendArray = function (arr, extension) {
var i = 0
, ilen = extension.length;
while (i < ilen) {
arr.push(extension[i]);
i++;
}
};
/**
* Determines if the given DOM element is an input field.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isInput = function (element) {
var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];
return inputs.indexOf(element.nodeName) > -1;
}
/**
* Determines if the given DOM element is an input field placed OUTSIDE of HOT.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isOutsideInput = function (element) {
return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1;
};
Handsontable.helper.keyCode = {
MOUSE_LEFT: 1,
MOUSE_RIGHT: 3,
MOUSE_MIDDLE: 2,
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
END: 35,
ENTER: 13,
ESCAPE: 27,
CONTROL_LEFT: 91,
COMMAND_LEFT: 17,
COMMAND_RIGHT: 93,
ALT: 18,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
SPACE: 32,
SHIFT: 16,
CAPS_LOCK: 20,
TAB: 9,
ARROW_RIGHT: 39,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_DOWN: 40,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
A: 65,
X: 88,
C: 67,
V: 86
};
/**
* Determines whether given object is a plain Object.
* Note: String and Array are not plain Objects
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isObject = function (obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
};
/**
* Determines whether given object is an Array.
* Note: String is not an Array
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isArray = function(obj){
return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]';
};
Handsontable.helper.pivot = function (arr) {
var pivotedArr = [];
if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){
return pivotedArr;
}
var rowCount = arr.length;
var colCount = arr[0].length;
for(var i = 0; i < rowCount; i++){
for(var j = 0; j < colCount; j++){
if(!pivotedArr[j]){
pivotedArr[j] = [];
}
pivotedArr[j][i] = arr[i][j];
}
}
return pivotedArr;
};
Handsontable.helper.proxy = function (fun, context) {
return function () {
return fun.apply(context, arguments);
};
};
/**
* Factory that produces a function for searching methods (or any properties) which could be defined directly in
* table configuration or implicitly, within cell type definition.
*
* For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
* defined implicitly using "type" property.
*
* Methods/properties defined explicitly always takes precedence over those defined through "type".
*
* If the method/property is not found in an object, searching is continued recursively through prototype chain, until
* it reaches the Object.prototype.
*
*
* @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
* @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
* @returns {Function}
*/
Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) {
allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;
return function cellMethodLookup (row, col) {
return (function getMethodFromProperties(properties) {
if (!properties){
return; //method not found
}
else if (properties.hasOwnProperty(methodName) && properties[methodName]) { //check if it is own and is not empty
return properties[methodName]; //method defined directly
} else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty
var type;
if(typeof properties.type != 'string' ){
throw new Error('Cell type must be a string ');
}
type = translateTypeNameToObject(properties.type);
if (type.hasOwnProperty(methodName)) {
return type[methodName]; //method defined in type.
} else if (allowUndefined) {
return; //method does not defined in type (eg. validator), returns undefined
}
}
return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties));
})(typeof row == 'number' ? this.getCellMeta(row, col) : row);
};
function translateTypeNameToObject(typeName) {
var type = Handsontable.cellTypes[typeName];
if(typeof type == 'undefined'){
throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
return type;
}
};
Handsontable.helper.toString = function (obj) {
return '' + obj;
};
Handsontable.SelectionPoint = function () {
this._row = null; //private use intended
this._col = null;
};
Handsontable.SelectionPoint.prototype.exists = function () {
return (this._row !== null);
};
Handsontable.SelectionPoint.prototype.row = function (val) {
if (val !== void 0) {
this._row = val;
}
return this._row;
};
Handsontable.SelectionPoint.prototype.col = function (val) {
if (val !== void 0) {
this._col = val;
}
return this._col;
};
Handsontable.SelectionPoint.prototype.coords = function (coords) {
if (coords !== void 0) {
this._row = coords.row;
this._col = coords.col;
}
return {
row: this._row,
col: this._col
}
};
Handsontable.SelectionPoint.prototype.arr = function (arr) {
if (arr !== void 0) {
this._row = arr[0];
this._col = arr[1];
}
return [this._row, this._col]
};
(function (Handsontable) {
'use strict';
/**
* Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names
* TODO refactor arguments of methods getRange, getText to be numbers (not objects)
* TODO remove priv, GridSettings from object constructor
*
* @param instance
* @param priv
* @param GridSettings
* @constructor
*/
Handsontable.DataMap = function (instance, priv, GridSettings) {
this.instance = instance;
this.priv = priv;
this.GridSettings = GridSettings;
this.dataSource = this.instance.getSettings().data;
if (this.dataSource[0]) {
this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]);
}
else {
this.duckSchema = {};
}
this.createMap();
this.getVars = {}; //used by modifier
this.setVars = {}; //used by modifier
};
Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1;
Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2;
Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) {
var schema;
if ($.isPlainObject(obj)) {
schema = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if ($.isPlainObject(obj[i])) {
schema[i] = this.recursiveDuckSchema(obj[i]);
}
else {
schema[i] = null;
}
}
}
}
else {
schema = [];
}
return schema;
};
Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) {
var prop, i;
if (typeof lastCol === 'undefined') {
lastCol = 0;
parent = '';
}
if ($.isPlainObject(schema)) {
for (i in schema) {
if (schema.hasOwnProperty(i)) {
if (schema[i] === null) {
prop = parent + i;
this.colToPropCache.push(prop);
this.propToColCache.set(prop, lastCol);
lastCol++;
}
else {
lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.');
}
}
}
}
return lastCol;
};
Handsontable.DataMap.prototype.createMap = function () {
if (typeof this.getSchema() === "undefined") {
throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`");
}
var i, ilen, schema = this.getSchema();
this.colToPropCache = [];
this.propToColCache = new MultiMap();
var columns = this.instance.getSettings().columns;
if (columns) {
for (i = 0, ilen = columns.length; i < ilen; i++) {
if (typeof columns[i].data != 'undefined'){
this.colToPropCache[i] = columns[i].data;
this.propToColCache.set(columns[i].data, i);
}
}
}
else {
this.recursiveDuckColumns(schema);
}
};
Handsontable.DataMap.prototype.colToProp = function (col) {
col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col);
if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') {
return this.colToPropCache[col];
}
else {
return col;
}
};
Handsontable.DataMap.prototype.propToCol = function (prop) {
var col;
if (typeof this.propToColCache.get(prop) !== 'undefined') {
col = this.propToColCache.get(prop);
} else {
col = prop;
}
col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col);
return col;
};
Handsontable.DataMap.prototype.getSchema = function () {
var schema = this.instance.getSettings().dataSchema;
if (schema) {
if (typeof schema === 'function') {
return schema();
}
return schema;
}
return this.duckSchema;
};
/**
* Creates row at the bottom of the data array
* @param {Number} [index] Optional. Index of the row before which the new row will be inserted
*/
Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) {
var row
, colCount = this.instance.countCols()
, numberOfCreatedRows = 0
, currentIndex;
if (!amount) {
amount = 1;
}
if (typeof index !== 'number' || index >= this.instance.countRows()) {
index = this.instance.countRows();
}
currentIndex = index;
var maxRows = this.instance.getSettings().maxRows;
while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) {
if (this.instance.dataType === 'array') {
row = [];
for (var c = 0; c < colCount; c++) {
row.push(null);
}
}
else if (this.instance.dataType === 'function') {
row = this.instance.getSettings().dataSchema(index);
}
else {
row = $.extend(true, {}, this.getSchema());
}
if (index === this.instance.countRows()) {
this.dataSource.push(row);
}
else {
this.dataSource.splice(index, 0, row);
}
numberOfCreatedRows++;
currentIndex++;
}
this.instance.PluginHooks.run('afterCreateRow', index, numberOfCreatedRows, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedRows;
};
/**
* Creates col at the right of the data array
* @param {Number} [index] Optional. Index of the column before which the new column will be inserted
* * @param {Number} [amount] Optional.
*/
Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("Cannot create new column. When data source in an object, " +
"you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." +
"If you want to be able to add new columns, you have to use array datasource.");
}
var rlen = this.instance.countRows()
, data = this.dataSource
, constructor
, numberOfCreatedCols = 0
, currentIndex;
if (!amount) {
amount = 1;
}
currentIndex = index;
var maxCols = this.instance.getSettings().maxCols;
while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) {
constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts);
if (typeof index !== 'number' || index >= this.instance.countCols()) {
for (var r = 0; r < rlen; r++) {
if (typeof data[r] === 'undefined') {
data[r] = [];
}
data[r].push(null);
}
// Add new column constructor
this.priv.columnSettings.push(constructor);
}
else {
for (var r = 0; r < rlen; r++) {
data[r].splice(currentIndex, 0, null);
}
// Add new column constructor at given index
this.priv.columnSettings.splice(currentIndex, 0, constructor);
}
numberOfCreatedCols++;
currentIndex++;
}
this.instance.PluginHooks.run('afterCreateCol', index, numberOfCreatedCols, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedCols;
};
/**
* Removes row from the data array
* @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed
* @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed
*/
Handsontable.DataMap.prototype.removeRow = function (index, amount) {
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countRows() + index) % this.instance.countRows();
// We have to map the physical row ids to logical and than perform removing with (possibly) new row id
var logicRows = this.physicalRowsToLogical(index, amount);
var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveRow', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
var newData = data.filter(function (row, index) {
return logicRows.indexOf(index) == -1;
});
data.length = 0;
Array.prototype.push.apply(data, newData);
this.instance.PluginHooks.run('afterRemoveRow', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Removes column from the data array
* @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed
* @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed
*/
Handsontable.DataMap.prototype.removeCol = function (index, amount) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("cannot remove column with object data source or columns option specified");
}
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countCols() + index) % this.instance.countCols();
var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveCol', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) {
data[r].splice(index, amount);
}
this.priv.columnSettings.splice(index, amount);
this.instance.PluginHooks.run('afterRemoveCol', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Add / removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var colData = this.instance.getDataAtCol(col);
var removed = colData.slice(index, index + amount);
var after = colData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
Handsontable.helper.to2dArray(elements);
this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol');
return removed;
};
/**
* Add / removes data from the row
* @param {Number} row Index of row in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var rowData = this.instance.getDataAtRow(row);
var removed = rowData.slice(index, index + amount);
var after = rowData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');
return removed;
};
/**
* Returns single value from the data array
* @param {Number} row
* @param {Number} prop
*/
Handsontable.DataMap.prototype.get = function (row, prop) {
this.getVars.row = row;
this.getVars.prop = prop;
this.instance.PluginHooks.run('beforeGet', this.getVars);
if (typeof this.getVars.prop === 'string' && this.getVars.prop.indexOf('.') > -1) {
var sliced = this.getVars.prop.split(".");
var out = this.dataSource[this.getVars.row];
if (!out) {
return null;
}
for (var i = 0, ilen = sliced.length; i < ilen; i++) {
out = out[sliced[i]];
if (typeof out === 'undefined') {
return null;
}
}
return out;
}
else if (typeof this.getVars.prop === 'function') {
/**
* allows for interacting with complex structures, for example
* d3/jQuery getter/setter properties:
*
* {columns: [{
* data: function(row, value){
* if(arguments.length === 1){
* return row.property();
* }
* row.property(value);
* }
* }]}
*/
return this.getVars.prop(this.dataSource.slice(
this.getVars.row,
this.getVars.row + 1
)[0]);
}
else {
return this.dataSource[this.getVars.row] ? this.dataSource[this.getVars.row][this.getVars.prop] : null;
}
};
var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false);
/**
* Returns single value from the data array (intended for clipboard copy to an external application)
* @param {Number} row
* @param {Number} prop
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyable = function (row, prop) {
if (copyableLookup.call(this.instance, row, this.propToCol(prop))) {
return this.get(row, prop);
}
return '';
};
/**
* Saves single value to the data array
* @param {Number} row
* @param {Number} prop
* @param {String} value
* @param {String} [source] Optional. Source of hook runner.
*/
Handsontable.DataMap.prototype.set = function (row, prop, value, source) {
this.setVars.row = row;
this.setVars.prop = prop;
this.setVars.value = value;
this.instance.PluginHooks.run('beforeSet', this.setVars, source || "datamapGet");
if (typeof this.setVars.prop === 'string' && this.setVars.prop.indexOf('.') > -1) {
var sliced = this.setVars.prop.split(".");
var out = this.dataSource[this.setVars.row];
for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) {
out = out[sliced[i]];
}
out[sliced[i]] = this.setVars.value;
}
else if (typeof this.setVars.prop === 'function') {
/* see the `function` handler in `get` */
this.setVars.prop(this.dataSource.slice(
this.setVars.row,
this.setVars.row + 1
)[0], this.setVars.value);
}
else {
this.dataSource[this.setVars.row][this.setVars.prop] = this.setVars.value;
}
};
/**
* This ridiculous piece of code maps rows Id that are present in table data to those displayed for user.
* The trick is, the physical row id (stored in settings.data) is not necessary the same
* as the logical (displayed) row id (e.g. when sorting is applied).
*/
Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) {
var totalRows = this.instance.countRows();
var physicRow = (totalRows + index) % totalRows;
var logicRows = [];
var rowsToRemove = amount;
while (physicRow < totalRows && rowsToRemove) {
this.get(physicRow, 0); //this performs an actual mapping and saves the result to getVars
logicRows.push(this.getVars.row);
rowsToRemove--;
physicRow++;
}
return logicRows;
};
/**
* Clears the data array
*/
Handsontable.DataMap.prototype.clear = function () {
for (var r = 0; r < this.instance.countRows(); r++) {
for (var c = 0; c < this.instance.countCols(); c++) {
this.set(r, this.colToProp(c), '');
}
}
};
/**
* Returns the data array
* @return {Array}
*/
Handsontable.DataMap.prototype.getAll = function () {
return this.dataSource;
};
/**
* Returns data range as array
* @param {Object} start Start selection position
* @param {Object} end End selection position
* @param {Number} destination Destination of datamap.get
* @return {Array}
*/
Handsontable.DataMap.prototype.getRange = function (start, end, destination) {
var r, rlen, c, clen, output = [], row;
var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get;
rlen = Math.max(start.row, end.row);
clen = Math.max(start.col, end.col);
for (r = Math.min(start.row, end.row); r <= rlen; r++) {
row = [];
for (c = Math.min(start.col, end.col); c <= clen; c++) {
row.push(getFn.call(this, r, this.colToProp(c)));
}
output.push(row);
}
return output;
};
/**
* Return data as text (tab separated columns)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER));
};
/**
* Return data as copyable text (tab separated columns intended for clipboard copy to an external application)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyableText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR));
};
})(Handsontable);
(function (Handsontable) {
'use strict';
/*
Adds appropriate CSS class to table cell, based on cellProperties
*/
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
if (cellProperties.readOnly) {
instance.view.wt.wtDom.addClass(TD, cellProperties.readOnlyCellClassName);
}
if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
instance.view.wt.wtDom.addClass(TD, cellProperties.invalidCellClassName);
}
if (!value && cellProperties.placeholder) {
instance.view.wt.wtDom.addClass(TD, cellProperties.placeholderCellClassName);
}
}
})(Handsontable);
/**
* Default text renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.cellDecorator.apply(this, arguments);
if (!value && cellProperties.placeholder) {
value = cellProperties.placeholder;
}
var escaped = Handsontable.helper.stringify(value);
if (cellProperties.rendererTemplate) {
instance.view.wt.wtDom.empty(TD);
var TEMPLATE = document.createElement('TEMPLATE');
TEMPLATE.setAttribute('bind', '{{}}');
TEMPLATE.innerHTML = cellProperties.rendererTemplate;
HTMLTemplateElement.decorate(TEMPLATE);
TEMPLATE.model = instance.getDataAtRow(row);
TD.appendChild(TEMPLATE);
}
else {
instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
};
//Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility
Handsontable.renderers.TextRenderer = TextRenderer;
Handsontable.renderers.registerRenderer('text', TextRenderer);
})(Handsontable);
(function (Handsontable) {
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
clonableARROW.appendChild(document.createTextNode('\u25BC'));
//this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
var wrapTdContentWithWrapper = function(TD, WRAPPER){
WRAPPER.innerHTML = TD.innerHTML;
Handsontable.Dom.empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
Handsontable.Dom.addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals for a text node
//this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
//not very elegant but easy and fast
instance.acArrowListener = function () {
instance.view.wt.getSetting('onCellDblClick');
};
instance.rootElement.on('mousedown.htAutocompleteArrow', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead
//We need to unbind the listener after the table has been destroyed
instance.addHookOnce('afterDestroy', function () {
this.rootElement.off('mousedown.htAutocompleteArrow');
});
}
};
Handsontable.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer);
})(Handsontable);
/**
* Checkbox renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var clonableINPUT = document.createElement('INPUT');
clonableINPUT.className = 'htCheckboxRendererInput';
clonableINPUT.type = 'checkbox';
clonableINPUT.setAttribute('autocomplete', 'off');
var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (typeof cellProperties.checkedTemplate === "undefined") {
cellProperties.checkedTemplate = true;
}
if (typeof cellProperties.uncheckedTemplate === "undefined") {
cellProperties.uncheckedTemplate = false;
}
instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed
var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement
if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
INPUT.checked = true;
TD.appendChild(INPUT);
}
else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) {
TD.appendChild(INPUT);
}
else if (value === null) { //default value
INPUT.className += ' noValue';
TD.appendChild(INPUT);
}
else {
instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
var $input = $(INPUT);
if (cellProperties.readOnly) {
$input.on('click', function (event) {
event.preventDefault();
});
}
else {
$input.on('mousedown', function (event) {
event.stopPropagation(); //otherwise can confuse cell mousedown handler
});
$input.on('mouseup', function (event) {
event.stopPropagation(); //otherwise can confuse cell dblclick handler
});
$input.on('change', function(){
if (this.checked) {
instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
}
else {
instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
}
});
}
if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){
instance.CheckboxRenderer = {
beforeKeyDownHookBound : true
};
instance.addHook('beforeKeyDown', function(event){
if(event.keyCode == Handsontable.helper.keyCode.SPACE){
var selection = instance.getSelected();
var cell, checkbox, cellProperties;
var selStart = {
row: Math.min(selection[0], selection[2]),
col: Math.min(selection[1], selection[3])
};
var selEnd = {
row: Math.max(selection[0], selection[2]),
col: Math.max(selection[1], selection[3])
};
for(var row = selStart.row; row <= selEnd.row; row++ ){
for(var col = selEnd.col; col <= selEnd.col; col++){
cell = instance.getCell(row, col);
cellProperties = instance.getCellMeta(row, col);
checkbox = cell.querySelectorAll('input[type=checkbox]');
if(checkbox.length > 0 && !cellProperties.readOnly){
if(!event.isImmediatePropagationStopped()){
event.stopImmediatePropagation();
event.preventDefault();
}
for(var i = 0, len = checkbox.length; i < len; i++){
checkbox[i].checked = !checkbox[i].checked;
$(checkbox[i]).trigger('change');
}
}
}
}
}
});
}
};
Handsontable.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer);
})(Handsontable);
/**
* Numeric cell renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (Handsontable.helper.isNumeric(value)) {
if (typeof cellProperties.language !== 'undefined') {
numeral.language(cellProperties.language)
}
value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/
instance.view.wt.wtDom.addClass(TD, 'htNumeric');
}
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
};
Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0
Handsontable.renderers.NumericRenderer = NumericRenderer;
Handsontable.renderers.registerRenderer('numeric', NumericRenderer);
})(Handsontable);
(function(Handosntable){
'use strict';
var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
value = TD.innerHTML;
var hash;
var hashLength = cellProperties.hashLength || value.length;
var hashSymbol = cellProperties.hashSymbol || '*';
for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol);
instance.view.wt.wtDom.fastInnerHTML(TD, hash);
};
Handosntable.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.registerRenderer('password', PasswordRenderer);
})(Handsontable);
(function (Handsontable) {
function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){
Handsontable.renderers.cellDecorator.apply(this, arguments);
Handsontable.Dom.fastInnerHTML(TD, value);
}
Handsontable.renderers.registerRenderer('html', HtmlRenderer);
Handsontable.renderers.HtmlRenderer = HtmlRenderer;
})(Handsontable);
(function (Handsontable) {
'use strict';
Handsontable.EditorState = {
VIRGIN: 'STATE_VIRGIN', //before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', //waiting for async validation
FINISHED: 'STATE_FINISHED'
};
function BaseEditor(instance) {
this.instance = instance;
this.state = Handsontable.EditorState.VIRGIN;
this._opened = false;
this._closeCallback = null;
this.init();
}
BaseEditor.prototype._fireCallbacks = function(result) {
if(this._closeCallback){
this._closeCallback(result);
this._closeCallback = null;
}
}
BaseEditor.prototype.init = function(){};
BaseEditor.prototype.getValue = function(){
throw Error('Editor getValue() method unimplemented');
};
BaseEditor.prototype.setValue = function(newValue){
throw Error('Editor setValue() method unimplemented');
};
BaseEditor.prototype.open = function(){
throw Error('Editor open() method unimplemented');
};
BaseEditor.prototype.close = function(){
throw Error('Editor close() method unimplemented');
};
BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = originalValue;
this.cellProperties = cellProperties;
this.state = Handsontable.EditorState.VIRGIN;
};
BaseEditor.prototype.extend = function(){
var baseClass = this.constructor;
function Editor(){
baseClass.apply(this, arguments);
}
function inherit(Child, Parent){
function Bridge() {
}
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Child.prototype.constructor = Child;
return Child;
}
return inherit(Editor, baseClass);
};
BaseEditor.prototype.saveValue = function (val, ctrlDown) {
if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
var sel = this.instance.getSelected();
this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit');
}
else {
this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit');
}
};
BaseEditor.prototype.beginEditing = function(initialValue){
if (this.state != Handsontable.EditorState.VIRGIN) {
return;
}
this.instance.view.scrollViewport({row: this.row, col: this.col});
this.instance.view.render();
this.state = Handsontable.EditorState.EDITING;
initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue;
this.setValue(Handsontable.helper.stringify(initialValue));
this.open();
this._opened = true;
this.focus();
this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered)
};
BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
if (callback) {
var previousCloseCallback = this._closeCallback;
this._closeCallback = function (result) {
if(previousCloseCallback){
previousCloseCallback(result);
}
callback(result);
};
}
if (this.isWaiting()) {
return;
}
if (this.state == Handsontable.EditorState.VIRGIN) {
var that = this;
setTimeout(function () {
that._fireCallbacks(true);
});
return;
}
if (this.state == Handsontable.EditorState.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
return;
}
var val = [
[String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js
];
this.state = Handsontable.EditorState.WAITING;
this.saveValue(val, ctrlDown);
if(this.instance.getCellValidator(this.cellProperties)){
var that = this;
this.instance.addHookOnce('afterValidate', function (result) {
that.state = Handsontable.EditorState.FINISHED;
that.discardEditor(result);
});
} else {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor(true);
}
}
};
BaseEditor.prototype.cancelChanges = function () {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor();
};
BaseEditor.prototype.discardEditor = function (result) {
if (this.state !== Handsontable.EditorState.FINISHED) {
return;
}
if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed
this.instance.selectCell(this.row, this.col);
this.focus();
this.state = Handsontable.EditorState.EDITING;
this._fireCallbacks(false);
}
else {
this.close();
this._opened = false;
this.state = Handsontable.EditorState.VIRGIN;
this._fireCallbacks(true);
}
};
BaseEditor.prototype.isOpened = function(){
return this._opened;
};
BaseEditor.prototype.isWaiting = function () {
return this.state === Handsontable.EditorState.WAITING;
};
Handsontable.editors.BaseEditor = BaseEditor;
})(Handsontable);
(function(Handsontable){
var TextEditor = Handsontable.editors.BaseEditor.prototype.extend();
TextEditor.prototype.init = function(){
this.createElements();
this.bindEvents();
};
TextEditor.prototype.getValue = function(){
return this.TEXTAREA.value
};
TextEditor.prototype.setValue = function(newValue){
this.TEXTAREA.value = newValue;
};
var onBeforeKeyDown = function onBeforeKeyDown(event){
var instance = this;
var that = instance.getActiveEditor();
var keyCodes = Handsontable.helper.keyCode;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
//Process only events that have been fired in the editor
if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){
return;
}
if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
//when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
event.stopImmediatePropagation();
return;
}
switch (event.keyCode) {
case keyCodes.ARROW_RIGHT:
if (that.wtDom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ARROW_LEFT: /* arrow left */
if (that.wtDom.getCaretPosition(that.TEXTAREA) !== 0) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ENTER:
var selected = that.instance.getSelected();
var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
if(that.isOpened()){
that.setValue(that.getValue() + '\n');
that.focus();
} else {
that.beginEditing(that.originalValue + '\n')
}
event.stopImmediatePropagation();
}
event.preventDefault(); //don't add newline to field
break;
case keyCodes.A:
case keyCodes.X:
case keyCodes.C:
case keyCodes.V:
if(ctrlDown){
event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
break;
}
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
case keyCodes.HOME:
case keyCodes.END:
event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context)
break;
}
};
TextEditor.prototype.open = function(){
this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.close = function(){
this.textareaParentStyle.display = 'none';
if (document.activeElement === this.TEXTAREA) {
this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose
}
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.focus = function(){
this.TEXTAREA.focus();
this.wtDom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
};
TextEditor.prototype.createElements = function () {
this.$body = $(document.body);
this.wtDom = new WalkontableDom();
this.TEXTAREA = document.createElement('TEXTAREA');
this.$textarea = $(this.TEXTAREA);
this.wtDom.addClass(this.TEXTAREA, 'handsontableInput');
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.TEXTAREA_PARENT = document.createElement('DIV');
this.wtDom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder');
this.textareaParentStyle = this.TEXTAREA_PARENT.style;
this.textareaParentStyle.top = 0;
this.textareaParentStyle.left = 0;
this.textareaParentStyle.display = 'none';
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT);
var that = this;
Handsontable.PluginHooks.add('afterRender', function () {
that.instance.registerTimeout('refresh_editor_dimensions', function () {
that.refreshDimensions();
}, 0);
});
};
TextEditor.prototype.refreshDimensions = function () {
if (this.state !== Handsontable.EditorState.EDITING) {
return;
}
///start prepare textarea position
this.TD = this.instance.getCell(this.row, this.col);
if (!this.TD) {
//TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited
return;
}
var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport
var currentOffset = this.wtDom.offset(this.TD);
var containerOffset = this.wtDom.offset(this.instance.rootElement[0]);
var scrollTop = this.instance.rootElement.scrollTop();
var scrollLeft = this.instance.rootElement.scrollLeft();
var editTop = currentOffset.top - containerOffset.top + scrollTop - 1;
var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1;
var settings = this.instance.getSettings();
var rowHeadersCount = settings.rowHeaders === false ? 0 : 1;
var colHeadersCount = settings.colHeaders === false ? 0 : 1;
if (editTop < 0) {
editTop = 0;
}
if (editLeft < 0) {
editLeft = 0;
}
if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) {
editTop += 1;
}
if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) {
editLeft += 1;
}
this.textareaParentStyle.top = editTop + 'px';
this.textareaParentStyle.left = editLeft + 'px';
///end prepare textarea position
var width = $td.width()
, maxWidth = this.instance.view.maximumVisibleElementWidth(editLeft) - 10 //10 is TEXTAREAs border and padding
, height = $td.outerHeight() - 4
, maxHeight = this.instance.view.maximumVisibleElementHeight(editTop) - 5; //10 is TEXTAREAs border and padding
if (parseInt($td.css('border-top-width'), 10) > 0) {
height -= 1;
}
if (parseInt($td.css('border-left-width'), 10) > 0) {
if (rowHeadersCount > 0) {
width -= 1;
}
}
//in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize
this.$textarea.autoResize({
minHeight: Math.min(height, maxHeight),
maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
minWidth: Math.min(width, maxWidth),
maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
animate: false,
extraSpace: 0
});
this.textareaParentStyle.display = 'block';
};
TextEditor.prototype.bindEvents = function () {
this.$textarea.on('cut.editor', function (event) {
event.stopPropagation();
});
this.$textarea.on('paste.editor', function (event) {
event.stopPropagation();
});
};
Handsontable.editors.TextEditor = TextEditor;
Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor);
})(Handsontable);
(function(Handsontable){
//Blank editor, because all the work is done by renderer
var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend();
CheckboxEditor.prototype.beginEditing = function () {
var checkbox = this.TD.querySelector('input[type="checkbox"]');
if (checkbox) {
$(checkbox).trigger('click');
}
};
CheckboxEditor.prototype.finishEditing = function () {};
CheckboxEditor.prototype.init = function () {};
CheckboxEditor.prototype.open = function () {};
CheckboxEditor.prototype.close = function () {};
CheckboxEditor.prototype.getValue = function () {};
CheckboxEditor.prototype.setValue = function () {};
CheckboxEditor.prototype.focus = function () {};
Handsontable.editors.CheckboxEditor = CheckboxEditor;
Handsontable.editors.registerEditor('checkbox', CheckboxEditor);
})(Handsontable);
(function (Handsontable) {
var DateEditor = Handsontable.editors.TextEditor.prototype.extend();
DateEditor.prototype.init = function () {
if (!$.datepicker) {
throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?");
}
Handsontable.editors.TextEditor.prototype.init.apply(this, arguments);
this.isCellEdited = false;
var that = this;
this.instance.addHook('afterDestroy', function () {
that.destroyElements();
})
};
DateEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.datePicker = document.createElement('DIV');
this.instance.view.wt.wtDom.addClass(this.datePicker, 'htDatepickerHolder');
this.datePickerStyle = this.datePicker.style;
this.datePickerStyle.position = 'absolute';
this.datePickerStyle.top = 0;
this.datePickerStyle.left = 0;
this.datePickerStyle.zIndex = 99;
document.body.appendChild(this.datePicker);
this.$datePicker = $(this.datePicker);
var that = this;
var defaultOptions = {
dateFormat: "yy-mm-dd",
showButtonPanel: true,
changeMonth: true,
changeYear: true,
onSelect: function (dateStr) {
that.setValue(dateStr);
that.finishEditing(false);
}
};
this.$datePicker.datepicker(defaultOptions);
/**
* Prevent recognizing clicking on jQuery Datepicker as clicking outside of table
*/
this.$datePicker.on('mousedown', function (event) {
event.stopPropagation();
});
this.hideDatepicker();
};
DateEditor.prototype.destroyElements = function () {
this.$datePicker.datepicker('destroy');
this.$datePicker.remove();
};
DateEditor.prototype.open = function () {
Handsontable.editors.TextEditor.prototype.open.call(this);
this.showDatepicker();
};
DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
this.hideDatepicker();
Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
DateEditor.prototype.showDatepicker = function () {
var $td = $(this.TD);
var offset = $td.offset();
this.datePickerStyle.top = (offset.top + $td.height()) + 'px';
this.datePickerStyle.left = offset.left + 'px';
var dateOptions = {
defaultDate: this.originalValue || void 0
};
$.extend(dateOptions, this.cellProperties);
this.$datePicker.datepicker("option", dateOptions);
if (this.originalValue) {
this.$datePicker.datepicker("setDate", this.originalValue);
}
this.datePickerStyle.display = 'block';
};
DateEditor.prototype.hideDatepicker = function () {
this.datePickerStyle.display = 'none';
};
Handsontable.editors.DateEditor = DateEditor;
Handsontable.editors.registerEditor('date', DateEditor);
})(Handsontable);
/**
* This is inception. Using Handsontable as Handsontable editor
*/
(function (Handsontable) {
"use strict";
var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend();
HandsontableEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
var DIV = document.createElement('DIV');
DIV.className = 'handsontableEditor';
this.TEXTAREA_PARENT.appendChild(DIV);
this.$htContainer = $(DIV);
this.$htContainer.handsontable();
};
HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) {
Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments);
var parent = this;
var options = {
startRows: 0,
startCols: 0,
minRows: 0,
minCols: 0,
className: 'listbox',
copyPaste: false,
cells: function () {
return {
readOnly: true
}
},
fillHandle: false,
afterOnCellMouseDown: function () {
var value = this.getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
},
beforeOnKeyDown: function (event) {
var instance = this;
switch (event.keyCode) {
case Handsontable.helper.keyCode.ESCAPE:
parent.instance.destroyEditor(true);
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ENTER: //enter
var sel = instance.getSelected();
var value = this.getDataAtCell(sel[0], sel[1]);
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){
instance.deselectCell();
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
break;
}
}
};
if (this.cellProperties.handsontable) {
options = $.extend(options, cellProperties.handsontable);
}
this.$htContainer.handsontable('destroy');
this.$htContainer.handsontable(options);
};
var onBeforeKeyDown = function (event) {
if (event.isImmediatePropagationStopped()) {
return;
}
var editor = this.getActiveEditor();
var innerHOT = editor.$htContainer.handsontable('getInstance');
if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) {
if (!innerHOT.getSelected()){
innerHOT.selectCell(0, 0);
} else {
var selectedRow = innerHOT.getSelected()[0];
var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow;
innerHOT.selectCell(rowToSelect, 0);
}
event.preventDefault();
event.stopImmediatePropagation();
}
};
HandsontableEditor.prototype.open = function () {
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
Handsontable.editors.TextEditor.prototype.open.apply(this, arguments);
this.$htContainer.handsontable('render');
if (this.cellProperties.strict) {
this.$htContainer.handsontable('selectCell', 0, 0);
this.$textarea[0].style.visibility = 'hidden';
} else {
this.$htContainer.handsontable('deselectCell');
this.$textarea[0].style.visibility = 'visible';
}
this.wtDom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length);
};
HandsontableEditor.prototype.close = function () {
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
this.instance.listen();
Handsontable.editors.TextEditor.prototype.close.apply(this, arguments);
};
HandsontableEditor.prototype.focus = function () {
this.instance.listen();
Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};
HandsontableEditor.prototype.beginEditing = function (initialValue) {
var onBeginEditing = this.instance.getSettings().onBeginEditing;
if (onBeginEditing && onBeginEditing() === false) {
return;
}
Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments);
};
HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor
this.instance.listen(); //return the focus to the parent HOT instance
}
if (this.$htContainer.handsontable('getSelected')) {
var value = this.$htContainer.handsontable('getInstance').getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
this.setValue(value);
}
}
return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
Handsontable.editors.HandsontableEditor = HandsontableEditor;
Handsontable.editors.registerEditor('handsontable', HandsontableEditor);
})(Handsontable);
(function (Handsontable) {
var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend();
AutocompleteEditor.prototype.init = function () {
Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments);
this.query = null;
this.choices = [];
};
AutocompleteEditor.prototype.createElements = function(){
Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments);
this.$htContainer.addClass('autocompleteEditor');
};
AutocompleteEditor.prototype.bindEvents = function(){
var that = this;
this.$textarea.on('keydown.autocompleteEditor', function(event){
if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){
setTimeout(function () {
that.queryChoices(that.$textarea.val());
});
} else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){
that.$htContainer.handsontable('deselectCell');
}
});
this.$htContainer.on('mouseleave', function () {
if(that.cellProperties.strict === true){
that.highlightBestMatchingChoice();
}
});
this.$htContainer.on('mouseenter', function () {
that.$htContainer.handsontable('deselectCell');
});
Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments);
};
var onBeforeKeyDownInner;
AutocompleteEditor.prototype.open = function () {
Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments);
this.$textarea[0].style.visibility = 'visible';
this.focus();
var choicesListHot = this.$htContainer.handsontable('getInstance');
var that = this;
choicesListHot.updateSettings({
'colWidths': [this.wtDom.outerWidth(this.TEXTAREA) - 2],
afterRenderer: function (TD, row, col, prop, value) {
var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true;
var indexOfMatch = caseSensitive ? value.indexOf(this.query) : value.toLowerCase().indexOf(that.query.toLowerCase());
if(indexOfMatch != -1){
var match = value.substr(indexOfMatch, that.query.length);
TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>');
}
}
});
onBeforeKeyDownInner = function (event) {
var instance = this;
if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){
if (instance.getSelected() && instance.getSelected()[0] == 0){
if(!parent.cellProperties.strict){
instance.deselectCell();
}
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
}
};
choicesListHot.addHook('beforeKeyDown', onBeforeKeyDownInner);
this.queryChoices(this.TEXTAREA.value);
};
AutocompleteEditor.prototype.close = function () {
this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner);
Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments);
};
AutocompleteEditor.prototype.queryChoices = function(query){
this.query = query;
if (typeof this.cellProperties.source == 'function'){
var that = this;
this.cellProperties.source(query, function(choices){
that.updateChoicesList(choices)
});
} else if (Handsontable.helper.isArray(this.cellProperties.source)) {
var choices;
if(!query || this.cellProperties.filter === false){
choices = this.cellProperties.source;
} else {
var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true;
var lowerCaseQuery = query.toLowerCase();
choices = this.cellProperties.source.filter(function(choice){
if (filteringCaseSensitive) {
return choice.indexOf(query) != -1;
} else {
return choice.toLowerCase().indexOf(lowerCaseQuery) != -1;
}
});
}
this.updateChoicesList(choices)
} else {
this.updateChoicesList([]);
}
};
AutocompleteEditor.prototype.updateChoicesList = function (choices) {
this.choices = choices;
this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices]));
if(this.cellProperties.strict === true){
this.highlightBestMatchingChoice();
}
this.focus();
};
AutocompleteEditor.prototype.highlightBestMatchingChoice = function () {
var bestMatchingChoice = this.findBestMatchingChoice();
if ( typeof bestMatchingChoice == 'undefined' && this.cellProperties.allowInvalid === false){
bestMatchingChoice = 0;
}
if(typeof bestMatchingChoice == 'undefined'){
this.$htContainer.handsontable('deselectCell');
} else {
this.$htContainer.handsontable('selectCell', bestMatchingChoice, 0);
}
};
AutocompleteEditor.prototype.findBestMatchingChoice = function(){
var bestMatch = {};
var valueLength = this.getValue().length;
var currentItem;
var indexOfValue;
var charsLeft;
for(var i = 0, len = this.choices.length; i < len; i++){
currentItem = this.choices[i];
if(valueLength > 0){
indexOfValue = currentItem.indexOf(this.getValue())
} else {
indexOfValue = currentItem === this.getValue() ? 0 : -1;
}
if(indexOfValue == -1) continue;
charsLeft = currentItem.length - indexOfValue - valueLength;
if( typeof bestMatch.indexOfValue == 'undefined'
|| bestMatch.indexOfValue > indexOfValue
|| ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){
bestMatch.indexOfValue = indexOfValue;
bestMatch.charsLeft = charsLeft;
bestMatch.index = i;
}
}
return bestMatch.index;
};
Handsontable.editors.AutocompleteEditor = AutocompleteEditor;
Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor);
})(Handsontable);
(function(Handsontable){
var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend();
var wtDom = new WalkontableDom();
PasswordEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.TEXTAREA = document.createElement('input');
this.TEXTAREA.setAttribute('type', 'password');
this.TEXTAREA.className = 'handsontableInput';
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.$textarea = $(this.TEXTAREA);
wtDom.empty(this.TEXTAREA_PARENT);
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
};
Handsontable.editors.PasswordEditor = PasswordEditor;
Handsontable.editors.registerEditor('password', PasswordEditor);
})(Handsontable);
(function (Handsontable) {
var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend();
SelectEditor.prototype.init = function(){
this.select = document.createElement('SELECT');
Handsontable.Dom.addClass(this.select, 'htSelectEditor');
this.select.style.display = 'none';
this.instance.rootElement[0].appendChild(this.select);
};
SelectEditor.prototype.prepare = function(){
Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments);
var selectOptions = this.cellProperties.selectOptions;
var options;
if (typeof selectOptions == 'function'){
options = this.prepareOptions(selectOptions(this.row, this.col, this.prop))
} else {
options = this.prepareOptions(selectOptions);
}
Handsontable.Dom.empty(this.select);
for (var option in options){
if (options.hasOwnProperty(option)){
var optionElement = document.createElement('OPTION');
optionElement.value = option;
Handsontable.Dom.fastInnerHTML(optionElement, options[option]);
this.select.appendChild(optionElement);
}
}
};
SelectEditor.prototype.prepareOptions = function(optionsToPrepare){
var preparedOptions = {};
if (Handsontable.helper.isArray(optionsToPrepare)){
for(var i = 0, len = optionsToPrepare.length; i < len; i++){
preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i];
}
}
else if (typeof optionsToPrepare == 'object') {
preparedOptions = optionsToPrepare;
}
return preparedOptions;
};
SelectEditor.prototype.getValue = function () {
return this.select.value;
};
SelectEditor.prototype.setValue = function (value) {
this.select.value = value;
};
var onBeforeKeyDown = function (event) {
var instance = this;
var editor = instance.getActiveEditor();
switch (event.keyCode){
case Handsontable.helper.keyCode.ARROW_UP:
var previousOption = editor.select.find('option:selected').prev();
if (previousOption.length == 1){
previousOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
var nextOption = editor.select.find('option:selected').next();
if (nextOption.length == 1){
nextOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
}
};
SelectEditor.prototype.open = function () {
var width = Handsontable.Dom.outerWidth(this.TD); //important - group layout reads together for better performance
var height = Handsontable.Dom.outerHeight(this.TD);
var rootOffset = Handsontable.Dom.offset(this.instance.rootElement[0]);
var tdOffset = Handsontable.Dom.offset(this.TD);
this.select.style.height = height + 'px';
this.select.style.minWidth = width + 'px';
this.select.style.top = tdOffset.top - rootOffset.top + 'px';
this.select.style.left = tdOffset.left - rootOffset.left - 2 + 'px'; //2 is cell border
this.select.style.display = '';
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.close = function () {
this.select.style.display = 'none';
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.focus = function () {
this.select.focus();
};
Handsontable.editors.SelectEditor = SelectEditor;
Handsontable.editors.registerEditor('select', SelectEditor);
})(Handsontable);
(function (Handsontable) {
var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend();
DropdownEditor.prototype.prepare = function () {
Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments);
this.cellProperties.filter = false;
this.cellProperties.strict = true;
};
Handsontable.editors.DropdownEditor = DropdownEditor;
Handsontable.editors.registerEditor('dropdown', DropdownEditor);
})(Handsontable);
/**
* Numeric cell validator
* @param {*} value - Value of edited cell
* @param {*} callback - Callback called with validation result
*/
Handsontable.NumericValidator = function (value, callback) {
if (value === null) {
value = '';
}
callback(/^-?\d*\.?\d*$/.test(value));
};
/**
* Function responsible for validation of autocomplete value
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
var process = function (value, callback) {
var originalVal = value;
var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;
return function (source) {
var found = false;
for (var s = 0, slen = source.length; s < slen; s++) {
if (originalVal === source[s]) {
found = true; //perfect match
break;
}
else if (lowercaseVal === source[s].toLowerCase()) {
// changes[i][3] = source[s]; //good match, fix the case << TODO?
found = true;
break;
}
}
callback(found);
}
};
/**
* Autocomplete cell validator
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
Handsontable.AutocompleteValidator = function (value, callback) {
if (this.strict && this.source) {
typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source);
} else {
callback(true);
}
};
/**
* Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta)
*/
Handsontable.AutocompleteCell = {
editor: Handsontable.editors.AutocompleteEditor,
renderer: Handsontable.renderers.AutocompleteRenderer,
validator: Handsontable.AutocompleteValidator
};
Handsontable.CheckboxCell = {
editor: Handsontable.editors.CheckboxEditor,
renderer: Handsontable.renderers.CheckboxRenderer
};
Handsontable.TextCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.TextRenderer
};
Handsontable.NumericCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.NumericRenderer,
validator: Handsontable.NumericValidator,
dataType: 'number'
};
Handsontable.DateCell = {
editor: Handsontable.editors.DateEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.HandsontableCell = {
editor: Handsontable.editors.HandsontableEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.PasswordCell = {
editor: Handsontable.editors.PasswordEditor,
renderer: Handsontable.renderers.PasswordRenderer,
copyable: false
};
Handsontable.DropdownCell = {
editor: Handsontable.editors.DropdownEditor,
renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell
validator: Handsontable.AutocompleteValidator
};
//here setup the friendly aliases that are used by cellProperties.type
Handsontable.cellTypes = {
text: Handsontable.TextCell,
date: Handsontable.DateCell,
numeric: Handsontable.NumericCell,
checkbox: Handsontable.CheckboxCell,
autocomplete: Handsontable.AutocompleteCell,
handsontable: Handsontable.HandsontableCell,
password: Handsontable.PasswordCell,
dropdown: Handsontable.DropdownCell
};
//here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor
Handsontable.cellLookup = {
validator: {
numeric: Handsontable.NumericValidator,
autocomplete: Handsontable.AutocompleteValidator
}
};
/*
* jQuery.fn.autoResize 1.1+
* --
* https://github.com/warpech/jQuery.fn.autoResize
*
* This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically).
* It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future.
*
* originally forked from:
* https://github.com/jamespadolsey/jQuery.fn.autoResize
* which is now located here:
* https://github.com/alexbardas/jQuery.fn.autoResize
* though the mostly maintained for is here:
* https://github.com/dpashkevich/jQuery.fn.autoResize/network
*
* --
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
(function($){
autoResize.defaults = {
onResize: function(){},
animate: {
duration: 200,
complete: function(){}
},
extraSpace: 50,
minHeight: 'original',
maxHeight: 500,
minWidth: 'original',
maxWidth: 500
};
autoResize.cloneCSSProperties = [
'lineHeight', 'textDecoration', 'letterSpacing',
'fontSize', 'fontFamily', 'fontStyle', 'fontWeight',
'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust',
'padding'
];
autoResize.cloneCSSValues = {
position: 'absolute',
top: -9999,
left: -9999,
opacity: 0,
overflow: 'hidden',
overflowX: 'hidden',
overflowY: 'hidden',
border: '1px solid black',
padding: '0.49em' //this must be about the width of caps W character
};
autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]';
autoResize.AutoResizer = AutoResizer;
$.fn.autoResize = autoResize;
function autoResize(config) {
this.filter(autoResize.resizableFilterSelector).each(function(){
new AutoResizer( $(this), config );
});
return this;
}
function AutoResizer(el, config) {
if(this.clones) return;
this.config = $.extend({}, autoResize.defaults, config);
this.el = el;
this.nodeName = el[0].nodeName.toLowerCase();
this.previousScrollTop = null;
if (config.maxWidth === 'original') config.maxWidth = el.width();
if (config.minWidth === 'original') config.minWidth = el.width();
if (config.maxHeight === 'original') config.maxHeight = el.height();
if (config.minHeight === 'original') config.minHeight = el.height();
if (this.nodeName === 'textarea') {
el.css({
resize: 'none',
overflowY: 'none'
});
}
el.data('AutoResizer', this);
this.createClone();
this.injectClone();
this.bind();
}
AutoResizer.prototype = {
bind: function() {
var check = $.proxy(function(){
this.check();
return true;
}, this);
this.unbind();
this.el
.bind('keyup.autoResize', check)
//.bind('keydown.autoResize', check)
.bind('change.autoResize', check);
this.check(null, true);
},
unbind: function() {
this.el.unbind('.autoResize');
},
createClone: function() {
var el = this.el,
self = this,
config = this.config;
this.clones = $();
if (config.minHeight !== 'original' || config.maxHeight !== 'original') {
this.hClone = el.clone().height('auto');
this.clones = this.clones.add(this.hClone);
}
if (config.minWidth !== 'original' || config.maxWidth !== 'original') {
this.wClone = $('<div/>').width('auto').css({
whiteSpace: 'nowrap',
'float': 'left'
});
this.clones = this.clones.add(this.wClone);
}
$.each(autoResize.cloneCSSProperties, function(i, p){
self.clones.css(p, el.css(p));
});
this.clones
.removeAttr('name')
.removeAttr('id')
.attr('tabIndex', -1)
.css(autoResize.cloneCSSValues)
.css('overflowY', 'scroll');
},
check: function(e, immediate) {
var config = this.config,
wClone = this.wClone,
hClone = this.hClone,
el = this.el,
value = el.val();
if (wClone) {
wClone.text(value);
// Calculate new width + whether to change
var cloneWidth = wClone.outerWidth(),
newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ?
cloneWidth + config.extraSpace : config.minWidth,
currentWidth = el.width();
newWidth = Math.min(newWidth, config.maxWidth);
if (
(newWidth < currentWidth && newWidth >= config.minWidth) ||
(newWidth >= config.minWidth && newWidth <= config.maxWidth)
) {
config.onResize.call(el);
el.scrollLeft(0);
config.animate && !immediate ?
el.stop(1,1).animate({
width: newWidth
}, config.animate)
: el.width(newWidth);
}
}
if (hClone) {
if (newWidth) {
hClone.width(newWidth);
}
hClone.height(0).val(value).scrollTop(10000);
var scrollTop = hClone[0].scrollTop + config.extraSpace;
// Don't do anything if scrollTop hasen't changed:
if (this.previousScrollTop === scrollTop) {
return;
}
this.previousScrollTop = scrollTop;
if (scrollTop >= config.maxHeight) {
scrollTop = config.maxHeight;
}
if (scrollTop < config.minHeight) {
scrollTop = config.minHeight;
}
if(scrollTop == config.maxHeight && newWidth == config.maxWidth) {
el.css('overflowY', 'scroll');
}
else {
el.css('overflowY', 'hidden');
}
config.onResize.call(el);
// Either animate or directly apply height:
config.animate && !immediate ?
el.stop(1,1).animate({
height: scrollTop
}, config.animate)
: el.height(scrollTop);
}
},
destroy: function() {
this.unbind();
this.el.removeData('AutoResizer');
this.clones.remove();
delete this.el;
delete this.hClone;
delete this.wClone;
delete this.clones;
},
injectClone: function() {
(
autoResize.cloneContainer ||
(autoResize.cloneContainer = $('<arclones/>').appendTo('body'))
).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once
}
};
})(jQuery);
/**
* SheetClip - Spreadsheet Clipboard Parser
* version 0.2
*
* This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
* Google Docs and Microsoft Excel.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/warpech/sheetclip/
*/
/*jslint white: true*/
(function (global) {
"use strict";
function countQuotes(str) {
return str.split('"').length - 1;
}
global.SheetClip = {
parse: function (str) {
var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
rows = str.split('\n');
if (rows.length > 1 && rows[rows.length - 1] === '') {
rows.pop();
}
for (r = 0, rlen = rows.length; r < rlen; r += 1) {
rows[r] = rows[r].split('\t');
for (c = 0, clen = rows[r].length; c < clen; c += 1) {
if (!arr[a]) {
arr[a] = [];
}
if (multiline && c === 0) {
last = arr[a].length - 1;
arr[a][last] = arr[a][last] + '\n' + rows[r][0];
if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2
multiline = false;
arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
}
}
else {
if (c === clen - 1 && rows[r][c].indexOf('"') === 0) {
arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
multiline = true;
}
else {
arr[a].push(rows[r][c].replace(/""/g, '"'));
multiline = false;
}
}
}
if (!multiline) {
a += 1;
}
}
return arr;
},
stringify: function (arr) {
var r, rlen, c, clen, str = '', val;
for (r = 0, rlen = arr.length; r < rlen; r += 1) {
for (c = 0, clen = arr[r].length; c < clen; c += 1) {
if (c > 0) {
str += '\t';
}
val = arr[r][c];
if (typeof val === 'string') {
if (val.indexOf('\n') > -1) {
str += '"' + val.replace(/"/g, '""') + '"';
}
else {
str += val;
}
}
else if (val === null || val === void 0) { //void 0 resolves to undefined
str += '';
}
else {
str += val;
}
}
str += '\n';
}
return str;
}
};
}(window));
/**
* CopyPaste.js
* Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused
* In future we may implement a better driver when better APIs are available
* @constructor
*/
var CopyPaste = (function () {
var instance;
return {
getInstance: function () {
if (!instance) {
instance = new CopyPasteClass();
} else if (instance.hasBeenDestroyed()){
instance.init();
}
instance.refCounter++;
return instance;
}
};
})();
function CopyPasteClass() {
this.refCounter = 0;
this.init();
}
CopyPasteClass.prototype.init = function () {
var that = this
, style
, parent;
this.copyCallbacks = [];
this.cutCallbacks = [];
this.pasteCallbacks = [];
this.listenerElement = document.documentElement;
parent = document.body;
if (document.getElementById('CopyPasteDiv')) {
this.elDiv = document.getElementById('CopyPasteDiv');
this.elTextarea = this.elDiv.firstChild;
}
else {
this.elDiv = document.createElement('DIV');
this.elDiv.id = 'CopyPasteDiv';
style = this.elDiv.style;
style.position = 'fixed';
style.top = '-10000px';
style.left = '-10000px';
parent.appendChild(this.elDiv);
this.elTextarea = document.createElement('TEXTAREA');
this.elTextarea.className = 'copyPaste';
style = this.elTextarea.style;
style.width = '10000px';
style.height = '10000px';
style.overflow = 'hidden';
this.elDiv.appendChild(this.elTextarea);
if (typeof style.opacity !== 'undefined') {
style.opacity = 0;
}
else {
/*@cc_on @if (@_jscript)
if(typeof style.filter === 'string') {
style.filter = 'alpha(opacity=0)';
}
@end @*/
}
}
this.keydownListener = function (event) {
var isCtrlDown = false;
if (event.metaKey) { //mac
isCtrlDown = true;
}
else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc
isCtrlDown = true;
}
if (isCtrlDown) {
if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) {
return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected
}
that.selectNodeText(that.elTextarea);
setTimeout(function () {
that.selectNodeText(that.elTextarea);
}, 0);
}
/* 67 = c
* 86 = v
* 88 = x
*/
if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) {
// that.selectNodeText(that.elTextarea);
if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12
setTimeout(function () {
that.triggerCut(event);
}, 0);
}
else if (event.keyCode === 86) {
setTimeout(function () {
that.triggerPaste(event);
}, 0);
}
}
}
this._bindEvent(this.listenerElement, 'keydown', this.keydownListener);
};
//http://jsperf.com/textara-selection
//http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie
CopyPasteClass.prototype.selectNodeText = function (el) {
el.select();
};
//http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
CopyPasteClass.prototype.getSelectionText = function () {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
};
CopyPasteClass.prototype.copyable = function (str) {
if (typeof str !== 'string' && str.toString === void 0) {
throw new Error('copyable requires string parameter');
}
this.elTextarea.value = str;
};
/*CopyPasteClass.prototype.onCopy = function (fn) {
this.copyCallbacks.push(fn);
};*/
CopyPasteClass.prototype.onCut = function (fn) {
this.cutCallbacks.push(fn);
};
CopyPasteClass.prototype.onPaste = function (fn) {
this.pasteCallbacks.push(fn);
};
CopyPasteClass.prototype.removeCallback = function (fn) {
var i, ilen;
for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) {
if (this.copyCallbacks[i] === fn) {
this.copyCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) {
if (this.cutCallbacks[i] === fn) {
this.cutCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) {
if (this.pasteCallbacks[i] === fn) {
this.pasteCallbacks.splice(i, 1);
return true;
}
}
return false;
};
CopyPasteClass.prototype.triggerCut = function (event) {
var that = this;
if (that.cutCallbacks) {
setTimeout(function () {
for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) {
that.cutCallbacks[i](event);
}
}, 50);
}
};
CopyPasteClass.prototype.triggerPaste = function (event, str) {
var that = this;
if (that.pasteCallbacks) {
setTimeout(function () {
var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline
for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) {
that.pasteCallbacks[i](val, event);
}
}, 50);
}
};
CopyPasteClass.prototype.destroy = function () {
if(!this.hasBeenDestroyed() && --this.refCounter == 0){
if (this.elDiv && this.elDiv.parentNode) {
this.elDiv.parentNode.removeChild(this.elDiv);
}
this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener);
}
};
CopyPasteClass.prototype.hasBeenDestroyed = function () {
return !this.refCounter;
};
//old version used this:
// - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
// - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
//but that cannot work with jQuery.trigger
CopyPasteClass.prototype._bindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).on(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
CopyPasteClass.prototype._unbindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).off(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
// json-patch-duplex.js 0.3.6
// (c) 2013 Joachim Wester
// MIT license
var jsonpatch;
(function (jsonpatch) {
var objOps = {
add: function (obj, key) {
obj[key] = this.value;
return true;
},
remove: function (obj, key) {
delete obj[key];
return true;
},
replace: function (obj, key) {
obj[key] = this.value;
return true;
},
move: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "remove", path: this.from }
]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
copy: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
test: function (obj, key) {
return (JSON.stringify(obj[key]) === JSON.stringify(this.value));
},
_get: function (obj, key) {
this.value = obj[key];
}
};
var arrOps = {
add: function (arr, i) {
arr.splice(i, 0, this.value);
return true;
},
remove: function (arr, i) {
arr.splice(i, 1);
return true;
},
replace: function (arr, i) {
arr[i] = this.value;
return true;
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
var observeOps = {
add: function (patches, path) {
var patch = {
op: "add",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
},
'delete': function (patches, path) {
var patch = {
op: "remove",
path: path + escapePathComponent(this.name)
};
patches.push(patch);
},
update: function (patches, path) {
var patch = {
op: "replace",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
}
};
function escapePathComponent(str) {
if (str.indexOf('/') === -1 && str.indexOf('~') === -1)
return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function _getPathRecursive(root, obj) {
var found;
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] === obj) {
return escapePathComponent(key) + '/';
} else if (typeof root[key] === 'object') {
found = _getPathRecursive(root[key], obj);
if (found != '') {
return escapePathComponent(key) + '/' + found;
}
}
}
}
return '';
}
function getPath(root, obj) {
if (root === obj) {
return '/';
}
var path = _getPathRecursive(root, obj);
if (path === '') {
throw new Error("Object not found in root");
}
return '/' + path;
}
var beforeDict = [];
jsonpatch.intervals;
var Mirror = (function () {
function Mirror(obj) {
this.observers = [];
this.obj = obj;
}
return Mirror;
})();
var ObserverInfo = (function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
})();
function getMirror(obj) {
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === obj) {
return beforeDict[i];
}
}
}
function getObserverFromMirror(mirror, callback) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].callback === callback) {
return mirror.observers[j].observer;
}
}
}
function removeObserverFromMirror(mirror, observer) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].observer === observer) {
mirror.observers.splice(j, 1);
return;
}
}
}
function unobserve(root, observer) {
generate(observer);
if (Object.observe) {
_unobserve(observer, root);
} else {
clearTimeout(observer.next);
}
var mirror = getMirror(root);
removeObserverFromMirror(mirror, observer);
}
jsonpatch.unobserve = unobserve;
function observe(obj, callback) {
var patches = [];
var root = obj;
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.push(mirror);
} else {
observer = getObserverFromMirror(mirror, callback);
}
if (observer) {
return observer;
}
if (Object.observe) {
observer = function (arr) {
//This "refresh" is needed to begin observing new object properties
_unobserve(observer, obj);
_observe(observer, obj);
var a = 0, alen = arr.length;
while (a < alen) {
if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) {
var type = arr[a].type;
switch (type) {
case 'new':
type = 'add';
break;
case 'deleted':
type = 'delete';
break;
case 'updated':
type = 'update';
break;
}
observeOps[type].call(arr[a], patches, getPath(root, arr[a].object));
}
a++;
}
if (patches) {
if (callback) {
callback(patches);
}
}
observer.patches = patches;
patches = [];
};
} else {
observer = {};
mirror.value = JSON.parse(JSON.stringify(obj));
if (callback) {
//callbacks.push(callback); this has no purpose
observer.callback = callback;
observer.next = null;
var intervals = this.intervals || [100, 1000, 10000, 60000];
var currentInterval = 0;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(function () {
dirtyCheck();
currentInterval = 0;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}, 0);
};
var slowCheck = function () {
dirtyCheck();
if (currentInterval == intervals.length)
currentInterval = intervals.length - 1;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('mousedown', fastCheck);
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keydown', fastCheck);
} else {
window.attachEvent('onmousedown', fastCheck);
window.attachEvent('onmouseup', fastCheck);
window.attachEvent('onkeydown', fastCheck);
}
}
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}
}
observer.patches = patches;
observer.object = obj;
mirror.observers.push(new ObserverInfo(callback, observer));
return _observe(observer, obj);
}
jsonpatch.observe = observe;
/// Listen to changes on an object tree, accumulate patches
function _observe(observer, obj) {
if (Object.observe) {
Object.observe(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_observe(observer, v);
}
}
}
}
return observer;
}
function _unobserve(observer, obj) {
if (Object.observe) {
Object.unobserve(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_unobserve(observer, v);
}
}
}
}
return observer;
}
function generate(observer) {
if (Object.observe) {
Object.deliverChangeRecords(observer);
} else {
var mirror;
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === observer.object) {
mirror = beforeDict[i];
break;
}
}
_generate(mirror.value, observer.object, observer.patches, "");
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
}
jsonpatch.generate = generate;
var _objectKeys;
if (Object.keys) {
_objectKeys = Object.keys;
} else {
_objectKeys = function (obj) {
var keys = [];
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
// Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path) {
var newKeys = _objectKeys(obj);
var oldKeys = _objectKeys(mirror);
var changed = false;
var deleted = false;
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (obj.hasOwnProperty(key)) {
var newVal = obj[key];
if (oldVal instanceof Object) {
_generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key));
} else {
if (oldVal != newVal) {
changed = true;
patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal });
mirror[key] = newVal;
}
}
} else {
patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
delete mirror[key];
deleted = true;
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!mirror.hasOwnProperty(key)) {
patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] });
mirror[key] = JSON.parse(JSON.stringify(obj[key]));
}
}
}
var _isArray;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (obj) {
return obj.push && typeof obj.length === 'number';
};
}
/// Apply a json-patch operation on an object tree
function apply(tree, patches) {
var result = false, p = 0, plen = patches.length, patch;
while (p < plen) {
patch = patches[p];
// Find the object
var keys = patch.path.split('/');
var obj = tree;
var t = 1;
var len = keys.length;
while (true) {
if (_isArray(obj)) {
var index = parseInt(keys[t], 10);
t++;
if (t >= len) {
result = arrOps[patch.op].call(patch, obj, index, tree);
break;
}
obj = obj[index];
} else {
var key = keys[t];
if (key.indexOf('~') != -1)
key = key.replace(/~1/g, '/').replace(/~0/g, '~');
t++;
if (t >= len) {
result = objOps[patch.op].call(patch, obj, key, tree);
break;
}
obj = obj[key];
}
}
p++;
}
return result;
}
jsonpatch.apply = apply;
})(jsonpatch || (jsonpatch = {}));
if (typeof exports !== "undefined") {
exports.apply = jsonpatch.apply;
exports.observe = jsonpatch.observe;
exports.unobserve = jsonpatch.unobserve;
exports.generate = jsonpatch.generate;
}
Handsontable.PluginHookClass = (function () {
var Hooks = function () {
return {
// Hooks
beforeInitWalkontable: [],
beforeInit: [],
beforeRender: [],
beforeChange: [],
beforeRemoveCol: [],
beforeRemoveRow: [],
beforeValidate: [],
beforeGet: [],
beforeSet: [],
beforeGetCellMeta: [],
beforeAutofill: [],
beforeKeyDown: [],
beforeColumnSort: [],
afterInit : [],
afterLoadData : [],
afterUpdateSettings: [],
afterRender : [],
afterRenderer : [],
afterChange : [],
afterValidate: [],
afterGetCellMeta: [],
afterGetColHeader: [],
afterGetColWidth: [],
afterDestroy: [],
afterRemoveRow: [],
afterCreateRow: [],
afterRemoveCol: [],
afterCreateCol: [],
afterColumnResize: [],
afterColumnMove: [],
afterColumnSort: [],
afterDeselect: [],
afterSelection: [],
afterSelectionByProp: [],
afterSelectionEnd: [],
afterSelectionEndByProp: [],
afterCopyLimit: [],
afterOnCellMouseDown: [],
afterOnCellMouseOver: [],
afterOnCellCornerMouseDown: [],
afterScrollVertically: [],
afterScrollHorizontally: [],
// Modifiers
modifyCol: []
}
};
var legacy = {
onBeforeChange: "beforeChange",
onChange: "afterChange",
onCreateRow: "afterCreateRow",
onCreateCol: "afterCreateCol",
onSelection: "afterSelection",
onCopyLimit: "afterCopyLimit",
onSelectionEnd: "afterSelectionEnd",
onSelectionByProp: "afterSelectionByProp",
onSelectionEndByProp: "afterSelectionEndByProp"
};
function PluginHookClass() {
this.hooks = Hooks();
this.legacy = legacy;
}
PluginHookClass.prototype.add = function (key, fn) {
//if fn is array, run this for all the array items
if (Handsontable.helper.isArray(fn)) {
for (var i = 0, len = fn.length; i < len; i++) {
this.add(key, fn[i]);
}
}
else {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
if (typeof this.hooks[key] === "undefined") {
this.hooks[key] = [];
}
if (this.hooks[key].indexOf(fn) == -1) {
this.hooks[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored)
}
}
return this;
};
PluginHookClass.prototype.once = function(key, fn){
if(Handsontable.helper.isArray(fn)){
for(var i = 0, len = fn.length; i < len; i++){
fn[i].runOnce = true;
this.add(key, fn[i]);
}
} else {
fn.runOnce = true;
this.add(key, fn);
}
};
PluginHookClass.prototype.remove = function (key, fn) {
var status = false;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
if (typeof this.hooks[key] !== 'undefined') {
for (var i = 0, leni = this.hooks[key].length; i < leni; i++) {
if (this.hooks[key][i] == fn) {
delete this.hooks[key][i].runOnce;
this.hooks[key].splice(i, 1);
status = true;
break;
}
}
}
return status;
};
PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (typeof this.hooks[key] !== 'undefined') {
//Make a copy of handler array
var handlers = Array.prototype.slice.call(this.hooks[key]);
for (var i = 0, leni = handlers.length; i < leni; i++) {
handlers[i].call(instance, p1, p2, p3, p4, p5);
if(handlers[i].runOnce){
this.remove(key, handlers[i]);
}
}
}
};
PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) {
var res, handlers;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (typeof this.hooks[key] !== 'undefined') {
handlers = Array.prototype.slice.call(this.hooks[key]);
for (var i = 0, leni = handlers.length; i < leni; i++) {
res = handlers[i].call(instance, p1, p2, p3, p4, p5);
if (res !== void 0) {
p1 = res;
}
if(handlers[i].runOnce){
this.remove(key, handlers[i]);
}
if(res === false){ //if any handler returned false
return false; //event has been cancelled and further execution of handler queue is being aborted
}
}
}
return p1;
};
return PluginHookClass;
})();
Handsontable.PluginHooks = new Handsontable.PluginHookClass();
(function (Handsontable) {
function HandsontableAutoColumnSize() {
var plugin = this
, sampleCount = 5; //number of samples to take of each value length
this.beforeInit = function () {
var instance = this;
instance.autoColumnWidths = [];
if (instance.getSettings().autoColumnSize !== false) {
if (!instance.autoColumnSizeTmp) {
instance.autoColumnSizeTmp = {
table: null,
tableStyle: null,
theadTh: null,
tbody: null,
container: null,
containerStyle: null,
determineBeforeNextRender: true
};
instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.addHook('afterGetColWidth', htAutoColumnSize.getColWidth);
instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy);
instance.determineColumnWidth = plugin.determineColumnWidth;
}
} else {
if (instance.autoColumnSizeTmp) {
instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.removeHook('afterGetColWidth', htAutoColumnSize.getColWidth);
instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy);
delete instance.determineColumnWidth;
plugin.afterDestroy.call(instance);
}
}
};
this.determineIfChanged = function (force) {
if (force) {
htAutoColumnSize.determineColumnsWidth.apply(this, arguments);
}
};
this.determineColumnWidth = function (col) {
var instance = this
, tmp = instance.autoColumnSizeTmp;
if (!tmp.container) {
createTmpContainer.call(tmp, instance);
}
tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize';
tmp.table.className = instance.$table[0].className;
var rows = instance.countRows();
var samples = {};
var maxLen = 0;
for (var r = 0; r < rows; r++) {
var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col));
var len = value.length;
if (len > maxLen) {
maxLen = len;
}
if (!samples[len]) {
samples[len] = {
needed: sampleCount,
strings: []
};
}
if (samples[len].needed) {
samples[len].strings.push({value: value, row: r});
samples[len].needed--;
}
}
var settings = instance.getSettings();
if (settings.colHeaders) {
instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML
}
instance.view.wt.wtDom.empty(tmp.tbody);
for (var i in samples) {
if (samples.hasOwnProperty(i)) {
for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) {
var row = samples[i].strings[j].row;
var cellProperties = instance.getCellMeta(row, col);
cellProperties.col = col;
cellProperties.row = row;
var renderer = instance.getCellRenderer(cellProperties);
var tr = document.createElement('tr');
var td = document.createElement('td');
renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties);
r++;
tr.appendChild(td);
tmp.tbody.appendChild(tr);
}
}
}
var parent = instance.rootElement[0].parentNode;
parent.appendChild(tmp.container);
var width = instance.view.wt.wtDom.outerWidth(tmp.table);
parent.removeChild(tmp.container);
if (!settings.nativeScrollbars) { //with native scrollbars a cell size can safely exceed the width of the viewport
var maxWidth = instance.view.wt.wtViewport.getViewportWidth() - 2; //2 is some overhead for cell border
if (width > maxWidth) {
width = maxWidth;
}
}
return width;
};
this.determineColumnsWidth = function () {
var instance = this;
var settings = this.getSettings();
if (settings.autoColumnSize || !settings.colWidths) {
var cols = this.countCols();
for (var c = 0; c < cols; c++) {
if (!instance._getColWidthFromSettings(c)) {
this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c);
}
}
}
};
this.getColWidth = function (col, response) {
if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) {
response.width = this.autoColumnWidths[col];
}
};
this.afterDestroy = function () {
var instance = this;
if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) {
instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container);
}
instance.autoColumnSizeTmp = null;
};
function createTmpContainer(instance) {
var d = document
, tmp = this;
tmp.table = d.createElement('table');
tmp.theadTh = d.createElement('th');
tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh);
tmp.tableStyle = tmp.table.style;
tmp.tableStyle.tableLayout = 'auto';
tmp.tableStyle.width = 'auto';
tmp.tbody = d.createElement('tbody');
tmp.table.appendChild(tmp.tbody);
tmp.container = d.createElement('div');
tmp.container.className = instance.rootElement[0].className + ' hidden';
tmp.containerStyle = tmp.container.style;
tmp.container.appendChild(tmp.table);
}
}
var htAutoColumnSize = new HandsontableAutoColumnSize();
Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit);
Handsontable.PluginHooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit);
})(Handsontable);
/**
* This plugin sorts the view by a column (but does not sort the data source!)
* @constructor
*/
function HandsontableColumnSorting() {
var plugin = this;
this.init = function (source) {
var instance = this;
var sortingSettings = instance.getSettings().columnSorting;
var sortingColumn, sortingOrder;
instance.sortingEnabled = !!(sortingSettings);
if (instance.sortingEnabled) {
instance.sortIndex = [];
var loadedSortingState = loadSortingState.call(instance);
if (typeof loadedSortingState != 'undefined') {
sortingColumn = loadedSortingState.sortColumn;
sortingOrder = loadedSortingState.sortOrder;
} else {
sortingColumn = sortingSettings.column;
sortingOrder = sortingSettings.sortOrder;
}
plugin.sortByColumn.call(instance, sortingColumn, sortingOrder);
instance.sort = function(){
var args = Array.prototype.slice.call(arguments);
return plugin.sortByColumn.apply(instance, args)
};
if (typeof instance.getSettings().observeChanges == 'undefined'){
enableObserveChangesPlugin.call(instance);
}
if (source == 'afterInit') {
bindColumnSortingAfterClick.call(instance);
instance.addHook('afterCreateRow', plugin.afterCreateRow);
instance.addHook('afterRemoveRow', plugin.afterRemoveRow);
instance.addHook('afterLoadData', plugin.init);
}
} else {
delete instance.sort;
instance.removeHook('afterCreateRow', plugin.afterCreateRow);
instance.removeHook('afterRemoveRow', plugin.afterRemoveRow);
instance.removeHook('afterLoadData', plugin.init);
}
};
this.setSortingColumn = function (col, order) {
var instance = this;
if (typeof col == 'undefined') {
delete instance.sortColumn;
delete instance.sortOrder;
return;
} else if (instance.sortColumn === col && typeof order == 'undefined') {
instance.sortOrder = !instance.sortOrder;
} else {
instance.sortOrder = typeof order != 'undefined' ? order : true;
}
instance.sortColumn = col;
};
this.sortByColumn = function (col, order) {
var instance = this;
plugin.setSortingColumn.call(instance, col, order);
if(typeof instance.sortColumn == 'undefined'){
return;
}
instance.PluginHooks.run('beforeColumnSort', instance.sortColumn, instance.sortOrder);
plugin.sort.call(instance);
instance.render();
saveSortingState.call(instance);
instance.PluginHooks.run('afterColumnSort', instance.sortColumn, instance.sortOrder);
};
var saveSortingState = function () {
var instance = this;
var sortingState = {};
if (typeof instance.sortColumn != 'undefined') {
sortingState.sortColumn = instance.sortColumn;
}
if (typeof instance.sortOrder != 'undefined') {
sortingState.sortOrder = instance.sortOrder;
}
if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) {
instance.PluginHooks.run('persistentStateSave', 'columnSorting', sortingState);
}
};
var loadSortingState = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'columnSorting', storedState);
return storedState.value;
};
var bindColumnSortingAfterClick = function () {
var instance = this;
instance.rootElement.on('click.handsontable', '.columnSorting', function (e) {
if (instance.view.wt.wtDom.hasClass(e.target, 'columnSorting')) {
var col = getColumn(e.target);
plugin.sortByColumn.call(instance, col);
}
});
function countRowHeaders() {
var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th');
return THs.length;
}
function getColumn(target) {
var TH = instance.view.wt.wtDom.closest(target, 'TH');
return instance.view.wt.wtDom.index(TH) - countRowHeaders();
}
};
function enableObserveChangesPlugin () {
var instance = this;
instance.registerTimeout('enableObserveChanges', function(){
instance.updateSettings({
observeChanges: true
});
}, 0);
}
function defaultSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
if (a[1] < b[1]) return sortOrder ? -1 : 1;
if (a[1] > b[1]) return sortOrder ? 1 : -1;
return 0;
}
}
function dateSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
var aDate = new Date(a[1]);
var bDate = new Date(b[1]);
if (aDate < bDate) return sortOrder ? -1 : 1;
if (aDate > bDate) return sortOrder ? 1 : -1;
return 0;
}
}
this.sort = function () {
var instance = this;
if (typeof instance.sortOrder == 'undefined') {
return;
}
instance.sortingEnabled = false; //this is required by translateRow plugin hook
instance.sortIndex.length = 0;
var colOffset = this.colOffset();
for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) {
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
var colMeta = instance.getCellMeta(0, instance.sortColumn);
var sortFunction;
switch (colMeta.type) {
case 'date':
sortFunction = dateSort;
break;
default:
sortFunction = defaultSort;
}
this.sortIndex.sort(sortFunction(instance.sortOrder));
//Append spareRows
for(var i = this.sortIndex.length; i < instance.countRows(); i++){
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
instance.sortingEnabled = true; //this is required by translateRow plugin hook
};
this.translateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) {
return instance.sortIndex[row][0];
}
return row;
};
this.onBeforeGetSet = function (getVars) {
var instance = this;
getVars.row = plugin.translateRow.call(instance, getVars.row);
};
this.untranslateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) {
for (var i = 0; i < instance.sortIndex.length; i++) {
if (instance.sortIndex[i][0] == row) {
return i;
}
}
}
};
this.getColHeader = function (col, TH) {
if (this.getSettings().columnSorting) {
this.view.wt.wtDom.addClass(TH.querySelector('.colHeader'), 'columnSorting');
}
};
function isSorted(instance){
return typeof instance.sortColumn != 'undefined';
}
this.afterCreateRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] >= index){
instance.sortIndex[i][0] += amount;
}
}
for(var i=0; i < amount; i++){
instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]);
}
saveSortingState.call(instance);
};
this.afterRemoveRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
var physicalRemovedIndex = plugin.translateRow.call(instance, index);
instance.sortIndex.splice(index, amount);
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] > physicalRemovedIndex){
instance.sortIndex[i][0] -= amount;
}
}
saveSortingState.call(instance);
};
this.afterChangeSort = function (changes/*, source*/) {
var instance = this;
var sortColumnChanged = false;
var selection = {};
if (!changes) {
return;
}
for (var i = 0; i < changes.length; i++) {
if (changes[i][1] == instance.sortColumn) {
sortColumnChanged = true;
selection.row = plugin.translateRow.call(instance, changes[i][0]);
selection.col = changes[i][1];
break;
}
}
if (sortColumnChanged) {
setTimeout(function () {
plugin.sort.call(instance);
instance.render();
instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col);
}, 0);
}
};
}
var htSortColumn = new HandsontableColumnSorting();
Handsontable.PluginHooks.add('afterInit', function () {
htSortColumn.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htSortColumn.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('beforeGet', htSortColumn.onBeforeGetSet);
Handsontable.PluginHooks.add('beforeSet', htSortColumn.onBeforeGetSet);
Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader);
(function (Handsontable) {
'use strict';
function ContextMenu(instance, customOptions){
this.instance = instance;
var contextMenu = this;
this.menu = createMenu();
this.enabled = true;
this.bindMouseEvents();
this.bindTableEvents();
this.instance.addHook('afterDestroy', function () {
contextMenu.destroy();
});
this.defaultOptions = {
items: {
'row_above': {
name: 'Insert row above',
callback: function(key, selection){
this.alter("insert_row", selection.start.row());
},
disabled: function () {
return this.countRows() >= this.getSettings().maxRows;
}
},
'row_below': {
name: 'Insert row below',
callback: function(key, selection){
this.alter("insert_row", selection.end.row() + 1);
},
disabled: function () {
return this.countRows() >= this.getSettings().maxRows;
}
},
"hsep1": ContextMenu.SEPARATOR,
'col_left': {
name: 'Insert column on the left',
callback: function(key, selection){
this.alter("insert_col", selection.start.col());
},
disabled: function () {
return this.countCols() >= this.getSettings().maxCols;
}
},
'col_right': {
name: 'Insert column on the right',
callback: function(key, selection){
this.alter("insert_col", selection.end.col() + 1);
},
disabled: function () {
return this.countCols() >= this.getSettings().maxCols;
}
},
"hsep2": ContextMenu.SEPARATOR,
'remove_row': {
name: 'Remove row',
callback: function(key, selection){
var amount = selection.end.row() - selection.start.row() + 1;
this.alter("remove_row", selection.start.row(), amount);
}
},
'remove_col': {
name: 'Remove column',
callback: function(key, selection){
var amount = selection.end.col() - selection.start.col() + 1;
this.alter("remove_col", selection.start.col(), amount);
}
},
"hsep3": ContextMenu.SEPARATOR,
'undo': {
name: 'Undo',
callback: function(){
this.undo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isUndoAvailable();
}
},
'redo': {
name: 'Redo',
callback: function(){
this.redo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isRedoAvailable();
}
}
}
};
this.options = {};
Handsontable.helper.extend(this.options, this.defaultOptions);
this.updateOptions(customOptions);
function createMenu(){
var menu = $('body > .htContextMenu')[0];
if(!menu){
menu = document.createElement('DIV');
Handsontable.Dom.addClass(menu, 'htContextMenu');
document.getElementsByTagName('body')[0].appendChild(menu);
}
return menu;
}
}
ContextMenu.prototype.bindMouseEvents = function (){
function contextMenuOpenListener(event){
event.preventDefault();
if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
return;
}
this.show(event.pageY, event.pageX);
$(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this));
}
this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this));
};
ContextMenu.prototype.bindTableEvents = function () {
var that = this;
this._afterScrollCallback = function () {
that.close();
};
this.instance.addHook('afterScrollVertically', this._afterScrollCallback);
this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback);
};
ContextMenu.prototype.unbindTableEvents = function () {
var that = this;
if(this._afterScrollCallback){
this.instance.removeHook('afterScrollVertically', this._afterScrollCallback);
this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback);
this._afterScrollCallback = null;
}
};
ContextMenu.prototype.performAction = function (){
var hot = $(this.menu).handsontable('getInstance');
var selectedItemIndex = hot.getSelected()[0];
var selectedItem = hot.getData()[selectedItemIndex];
if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){
return;
}
if(typeof selectedItem.callback != 'function'){
return;
}
var corners = this.instance.getSelected();
var normalizedSelection = ContextMenu.utils.normalizeSelection(corners);
selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection);
};
ContextMenu.prototype.unbindMouseEvents = function () {
this.instance.rootElement.off('contextmenu.htContextMenu');
$(document).off('mousedown.htContextMenu');
};
ContextMenu.prototype.show = function(top, left){
this.menu.style.display = 'block';
$(this.menu)
.off('mousedown.htContextMenu')
.on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this));
$(this.menu).handsontable({
data: ContextMenu.utils.convertItemsToArray(this.getItems()),
colHeaders: false,
colWidths: [160],
readOnly: true,
copyPaste: false,
columns: [
{
data: 'name',
renderer: Handsontable.helper.proxy(this.renderer, this)
}
],
beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this)
});
this.bindTableEvents();
this.setMenuPosition(top, left);
$(this.menu).handsontable('listen');
};
ContextMenu.prototype.close = function () {
this.hide();
$(document).off('mousedown.htContextMenu');
this.unbindTableEvents();
this.instance.listen();
};
ContextMenu.prototype.hide = function(){
this.menu.style.display = 'none';
$(this.menu).handsontable('destroy');
};
ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){
var contextMenu = this;
var item = instance.getData()[row];
var wrapper = document.createElement('DIV');
Handsontable.Dom.empty(TD);
TD.appendChild(wrapper);
if(itemIsSeparator(item)){
Handsontable.Dom.addClass(TD, 'htSeparator');
} else {
Handsontable.Dom.fastInnerText(wrapper, value);
}
if (itemIsDisabled(item, contextMenu.instance)){
Handsontable.Dom.addClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.deselectCell();
});
} else {
Handsontable.Dom.removeClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.selectCell(row, col);
});
}
function itemIsSeparator(item){
return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name);
}
function itemIsDisabled(item, instance){
return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true);
}
};
ContextMenu.prototype.onBeforeKeyDown = function (event) {
var contextMenu = this;
var instance = $(contextMenu.menu).handsontable('getInstance');
var selection = instance.getSelected();
switch(event.keyCode){
case Handsontable.helper.keyCode.ESCAPE:
contextMenu.close();
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ENTER:
if(instance.getSelected()){
contextMenu.performAction();
contextMenu.close();
}
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
if(!selection){
selectFirstCell(instance);
} else {
selectNextCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if(!selection){
selectLastCell(instance);
} else {
selectPrevCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
}
function selectFirstCell(instance) {
var firstCell = instance.getCell(0, 0);
if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){
selectNextCell(0, 0, instance);
} else {
instance.selectCell(0, 0);
}
}
function selectLastCell(instance) {
var lastRow = instance.countRows() - 1;
var lastCell = instance.getCell(lastRow, 0);
if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){
selectPrevCell(lastRow, 0, instance);
} else {
instance.selectCell(lastRow, 0);
}
}
function selectNextCell(row, col, instance){
var nextRow = row + 1;
var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null;
if(!nextCell){
return;
}
if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){
selectNextCell(nextRow, col, instance);
} else {
instance.selectCell(nextRow, col);
}
}
function selectPrevCell(row, col, instance) {
var prevRow = row - 1;
var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null;
if (!prevCell) {
return;
}
if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){
selectPrevCell(prevRow, col, instance);
} else {
instance.selectCell(prevRow, col);
}
}
};
ContextMenu.prototype.getItems = function () {
var items = {};
function Item(rawItem){
if(typeof rawItem == 'string'){
this.name = rawItem;
} else {
Handsontable.helper.extend(this, rawItem);
}
}
Item.prototype = this.options;
for(var itemName in this.options.items){
if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){
items[itemName] = new Item(this.options.items[itemName]);
}
}
return items;
};
ContextMenu.prototype.updateOptions = function(newOptions){
newOptions = newOptions || {};
if(newOptions.items){
for(var itemName in newOptions.items){
var item = {};
if(newOptions.items.hasOwnProperty(itemName)) {
if(this.defaultOptions.items.hasOwnProperty(itemName)
&& Handsontable.helper.isObject(newOptions.items[itemName])){
Handsontable.helper.extend(item, this.defaultOptions.items[itemName]);
Handsontable.helper.extend(item, newOptions.items[itemName]);
newOptions.items[itemName] = item;
}
}
}
}
Handsontable.helper.extend(this.options, newOptions);
};
ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) {
var cursor = {
top: cursorY,
topRelative: cursorY - document.documentElement.scrollTop,
left: cursorX,
leftRelative:cursorX - document.documentElement.scrollLeft
};
if(this.menuFitsBelowCursor(cursor)){
this.positionMenuBelowCursor(cursor);
} else {
this.positionMenuAboveCursor(cursor);
}
if(this.menuFitsOnRightOfCursor(cursor)){
this.positionMenuOnRightOfCursor(cursor);
} else {
this.positionMenuOnLeftOfCursor(cursor);
}
};
ContextMenu.prototype.menuFitsBelowCursor = function (cursor) {
return cursor.topRelative + this.menu.offsetHeight <= document.documentElement.scrollTop + document.documentElement.clientHeight;
};
ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) {
return cursor.leftRelative + this.menu.offsetWidth <= document.documentElement.scrollLeft + document.documentElement.clientWidth;
};
ContextMenu.prototype.positionMenuBelowCursor = function (cursor) {
this.menu.style.top = cursor.top + 'px';
};
ContextMenu.prototype.positionMenuAboveCursor = function (cursor) {
this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px';
};
ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) {
this.menu.style.left = cursor.left + 'px';
};
ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) {
this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px';
};
ContextMenu.utils = {};
ContextMenu.utils.convertItemsToArray = function (items) {
var itemArray = [];
var item;
for(var itemName in items){
if(items.hasOwnProperty(itemName)){
if(typeof items[itemName] == 'string'){
item = {name: items[itemName]};
} else if (items[itemName].visible !== false) {
item = items[itemName];
} else {
continue;
}
item.key = itemName;
itemArray.push(item);
}
}
return itemArray;
};
ContextMenu.utils.normalizeSelection = function(corners){
var selection = {
start: new Handsontable.SelectionPoint(),
end: new Handsontable.SelectionPoint()
};
selection.start.row(Math.min(corners[0], corners[2]));
selection.start.col(Math.min(corners[1], corners[3]));
selection.end.row(Math.max(corners[0], corners[2]));
selection.end.col(Math.max(corners[1], corners[3]));
return selection;
};
ContextMenu.utils.isSeparator = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htSeparator');
};
ContextMenu.utils.isDisabled = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htDisabled');
};
ContextMenu.prototype.enable = function () {
if(!this.enabled){
this.enabled = true;
this.bindMouseEvents();
}
};
ContextMenu.prototype.disable = function () {
if(this.enabled){
this.enabled = false;
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
}
};
ContextMenu.prototype.destroy = function () {
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
if(!this.isMenuEnabledByOtherHotInstance()){
this.removeMenu();
}
};
ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () {
var hotContainers = $('.handsontable');
var menuEnabled = false;
for(var i = 0, len = hotContainers.length; i < len; i++){
var instance = $(hotContainers[i]).handsontable('getInstance');
if(instance && instance.getSettings().contextMenu){
menuEnabled = true;
break;
}
}
return menuEnabled;
};
ContextMenu.prototype.removeMenu = function () {
if(this.menu.parentNode){
this.menu.parentNode.removeChild(this.menu);
}
}
ContextMenu.prototype.filterItems = function(itemsToLeave){
this.itemsFilter = itemsToLeave;
};
ContextMenu.SEPARATOR = "---------";
function init(){
var instance = this;
var contextMenuSetting = instance.getSettings().contextMenu;
var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {};
if(contextMenuSetting){
if(!instance.contextMenu){
instance.contextMenu = new ContextMenu(instance, customOptions);
}
instance.contextMenu.enable();
if(Handsontable.helper.isArray(contextMenuSetting)){
instance.contextMenu.filterItems(contextMenuSetting);
}
} else if(instance.contextMenu){
instance.contextMenu.destroy();
delete instance.contextMenu;
}
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
Handsontable.ContextMenu = ContextMenu;
})(Handsontable);
/**
* This plugin adds support for legacy features, deprecated APIs, etc.
*/
/**
* Support for old autocomplete syntax
* For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete
*/
Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) {
//isWritable - deprecated since 0.8.0
cellProperties.isWritable = !cellProperties.readOnly;
//autocomplete - deprecated since 0.7.1 (see CHANGELOG.md)
if (cellProperties.autoComplete) {
throw new Error("Support for legacy autocomplete syntax was removed in Handsontable 0.10.0. Please remove the property named 'autoComplete' from your config. For replacement instructions, see wiki page https://github.com/warpech/jquery-handsontable/wiki/Migration-guide-to-0.10.x");
}
});
function HandsontableManualColumnMove() {
var pressed
, startCol
, endCol
, startX
, startOffset;
var ghost = document.createElement('DIV')
, ghostStyle = ghost.style;
ghost.className = 'ghost';
ghostStyle.position = 'absolute';
ghostStyle.top = '25px';
ghostStyle.left = 0;
ghostStyle.width = '10px';
ghostStyle.height = '10px';
ghostStyle.backgroundColor = '#CCC';
ghostStyle.opacity = 0.7;
var saveManualColumnPositions = function () {
var instance = this;
instance.PluginHooks.run('persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions);
};
var loadManualColumnPositions = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'manualColumnPositions', storedState);
return storedState.value;
};
var bindMoveColEvents = function () {
var instance = this;
instance.rootElement.on('mousemove.manualColumnMove', function (e) {
if (pressed) {
ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px';
if (ghostStyle.display === 'none') {
ghostStyle.display = 'block';
}
}
});
instance.rootElement.on('mouseup.manualColumnMove', function () {
if (pressed) {
if (startCol < endCol) {
endCol--;
}
if (instance.getSettings().rowHeaders) {
startCol--;
endCol--;
}
instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]);
$('.manualColumnMover.active').removeClass('active');
pressed = false;
instance.forceFullRender = true;
instance.view.render(); //updates all
ghostStyle.display = 'none';
saveManualColumnPositions.call(instance);
instance.PluginHooks.run('afterColumnMove', startCol, endCol);
}
});
instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) {
var mover = e.currentTarget;
var TH = instance.view.wt.wtDom.closest(mover, 'TH');
startCol = instance.view.wt.wtDom.index(TH) + instance.colOffset();
endCol = startCol;
pressed = true;
startX = e.pageX;
var TABLE = instance.$table[0];
TABLE.parentNode.appendChild(ghost);
ghostStyle.width = instance.view.wt.wtDom.outerWidth(TH) + 'px';
ghostStyle.height = instance.view.wt.wtDom.outerHeight(TABLE) + 'px';
startOffset = parseInt(instance.view.wt.wtDom.offset(TH).left - instance.view.wt.wtDom.offset(TABLE).left, 10);
ghostStyle.left = startOffset + 6 + 'px';
});
instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () {
if (pressed) {
var active = instance.view.THEAD.querySelector('.manualColumnMover.active');
if (active) {
instance.view.wt.wtDom.removeClass(active, 'active');
}
endCol = instance.view.wt.wtDom.index(this) + instance.colOffset();
var THs = instance.view.THEAD.querySelectorAll('th');
var mover = THs[endCol].querySelector('.manualColumnMover');
instance.view.wt.wtDom.addClass(mover, 'active');
}
});
instance.addHook('afterDestroy', unbindMoveColEvents);
};
var unbindMoveColEvents = function(){
var instance = this;
instance.rootElement.off('mouseup.manualColumnMove');
instance.rootElement.off('mousemove.manualColumnMove');
instance.rootElement.off('mousedown.manualColumnMove');
instance.rootElement.off('mouseenter.manualColumnMove');
};
this.beforeInit = function () {
this.manualColumnPositions = [];
};
this.init = function (source) {
var instance = this;
var manualColMoveEnabled = !!(this.getSettings().manualColumnMove);
if (manualColMoveEnabled) {
var initialManualColumnPositions = this.getSettings().manualColumnMove;
var loadedManualColumnPositions = loadManualColumnPositions.call(instance);
if (typeof loadedManualColumnPositions != 'undefined') {
this.manualColumnPositions = loadedManualColumnPositions;
} else if (initialManualColumnPositions instanceof Array) {
this.manualColumnPositions = initialManualColumnPositions;
} else {
this.manualColumnPositions = [];
}
instance.forceFullRender = true;
if (source == 'afterInit') {
bindMoveColEvents.call(this);
if (this.manualColumnPositions.length > 0) {
this.forceFullRender = true;
this.render();
}
}
} else {
unbindMoveColEvents.call(this);
this.manualColumnPositions = [];
}
};
this.modifyCol = function (col) {
//TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2
if (this.getSettings().manualColumnMove) {
if (typeof this.manualColumnPositions[col] === 'undefined') {
this.manualColumnPositions[col] = col;
}
return this.manualColumnPositions[col];
}
return col;
};
this.getColHeader = function (col, TH) {
if (this.getSettings().manualColumnMove) {
var DIV = document.createElement('DIV');
DIV.className = 'manualColumnMover';
TH.firstChild.appendChild(DIV);
}
};
}
var htManualColumnMove = new HandsontableManualColumnMove();
Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit);
Handsontable.PluginHooks.add('afterInit', function () {
htManualColumnMove.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htManualColumnMove.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader);
Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol);
function HandsontableManualColumnResize() {
var pressed
, currentTH
, currentCol
, currentWidth
, instance
, newSize
, startX
, startWidth
, startOffset
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualColumnResizer';
handle.className = 'manualColumnResizerHandle';
resizer.appendChild(handle);
line.className = 'manualColumnResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentWidth = startWidth + (e.pageX - startX);
newSize = setManualSize(currentCol, currentWidth); //save col width
resizer.style.left = startOffset + currentWidth + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
instance.view.wt.wtDom.removeClass(resizer, 'active');
pressed = false;
if(newSize != startWidth){
instance.forceFullRender = true;
instance.view.render(); //updates all
saveManualColumnWidths.call(instance);
instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualColumnWidths = function () {
var instance = this;
instance.PluginHooks.run('persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths);
};
var loadManualColumnWidths = function () {
var instance = this;
var storedState = {};
instance.PluginHooks.run('persistentStateLoad', 'manualColumnWidths', storedState);
return storedState.value;
};
function refreshResizerPosition(TH) {
instance = this;
currentTH = TH;
var col = this.view.wt.wtTable.getCoords(TH)[1]; //getCoords returns array [row, col]
if (col >= 0) { //if not row header
currentCol = col;
var rootOffset = this.view.wt.wtDom.offset(this.rootElement[0]).left;
var thOffset = this.view.wt.wtDom.offset(TH).left;
startOffset = (thOffset - rootOffset) - 6;
resizer.style.left = startOffset + parseInt(this.view.wt.wtDom.outerWidth(TH), 10) + 'px';
this.rootElement[0].appendChild(resizer);
}
}
function refreshLinePosition() {
var instance = this;
startWidth = parseInt(this.view.wt.wtDom.outerWidth(currentTH), 10);
instance.view.wt.wtDom.addClass(resizer, 'active');
lineStyle.height = instance.view.wt.wtDom.outerHeight(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualColumnWidthEvents = function () {
var instance = this;
var dblclick = 0;
var autoresizeTimeout = null;
this.rootElement.on('mouseenter.handsontable', 'th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
newSize = instance.determineColumnWidth.call(instance, currentCol);
setManualSize(currentCol, newSize);
instance.forceFullRender = true;
instance.view.render(); //updates all
instance.PluginHooks.run('afterColumnResize', currentCol, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 500);
}
dblclick++;
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
startX = e.pageX;
refreshLinePosition.call(instance);
newSize = startWidth;
});
};
this.beforeInit = function () {
this.manualColumnWidths = [];
};
this.init = function (source) {
var instance = this;
var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize);
if (manualColumnWidthEnabled) {
var initialColumnWidths = this.getSettings().manualColumnResize;
var loadedManualColumnWidths = loadManualColumnWidths.call(instance);
if (typeof loadedManualColumnWidths != 'undefined') {
this.manualColumnWidths = loadedManualColumnWidths;
} else if (initialColumnWidths instanceof Array) {
this.manualColumnWidths = initialColumnWidths;
} else {
this.manualColumnWidths = [];
}
if (source == 'afterInit') {
bindManualColumnWidthEvents.call(this);
instance.forceFullRender = true;
instance.render();
}
}
};
var setManualSize = function (col, width) {
width = Math.max(width, 20);
/**
* We need to run col through modifyCol hook, in case the order of displayed columns is different than the order
* in data source. For instance, this order can be modified by manualColumnMove plugin.
*/
col = instance.PluginHooks.execute('modifyCol', col);
instance.manualColumnWidths[col] = width;
return width;
};
this.getColWidth = function (col, response) {
if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) {
response.width = this.manualColumnWidths[col];
}
};
}
var htManualColumnResize = new HandsontableManualColumnResize();
Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit);
Handsontable.PluginHooks.add('afterInit', function () {
htManualColumnResize.init.call(this, 'afterInit')
});
Handsontable.PluginHooks.add('afterUpdateSettings', function () {
htManualColumnResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth);
(function HandsontableObserveChanges() {
Handsontable.PluginHooks.add('afterLoadData', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().observeChanges;
if (pluginEnabled) {
if(instance.observer) {
destroy.call(instance); //destroy observer for old data object
}
createObserver.call(instance);
bindEvents.call(instance);
} else if (!pluginEnabled){
destroy.call(instance);
}
}
function createObserver(){
var instance = this;
instance.observeChangesActive = true;
instance.pauseObservingChanges = function(){
instance.observeChangesActive = false;
};
instance.resumeObservingChanges = function(){
instance.observeChangesActive = true;
};
instance.observedData = instance.getData();
instance.observer = jsonpatch.observe(instance.observedData, function (patches) {
if(instance.observeChangesActive){
runHookForOperation.call(instance, patches);
instance.render();
}
instance.runHooks('afterChangesObserved');
});
}
function runHookForOperation(rawPatches){
var instance = this;
var patches = cleanPatches(rawPatches);
for(var i = 0, len = patches.length; i < len; i++){
var patch = patches[i];
var parsedPath = parsePath(patch.path);
switch(patch.op){
case 'add':
if(isNaN(parsedPath.col)){
instance.runHooks('afterCreateRow', parsedPath.row);
} else {
instance.runHooks('afterCreateCol', parsedPath.col);
}
break;
case 'remove':
if(isNaN(parsedPath.col)){
instance.runHooks('afterRemoveRow', parsedPath.row, 1);
} else {
instance.runHooks('afterRemoveCol', parsedPath.col, 1);
}
break;
case 'replace':
instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external');
break;
}
}
function cleanPatches(rawPatches){
var patches;
patches = removeLengthRelatedPatches(rawPatches);
patches = removeMultipleAddOrRemoveColPatches(patches);
return patches;
}
/**
* Removing or adding column will produce one patch for each table row.
* This function leaves only one patch for each column add/remove operation
*/
function removeMultipleAddOrRemoveColPatches(rawPatches){
var newOrRemovedColumns = [];
return rawPatches.filter(function(patch){
var parsedPath = parsePath(patch.path);
if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){
if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){
return false;
} else {
newOrRemovedColumns.push(parsedPath.col);
}
}
return true;
});
}
/**
* If observeChanges uses native Object.observe method, then it produces patches for length property.
* This function removes them.
*/
function removeLengthRelatedPatches(rawPatches){
return rawPatches.filter(function(patch){
return !/[/]length/ig.test(patch.path);
})
}
function parsePath(path){
var match = path.match(/^\/(\d+)\/?(.*)?$/);
return {
row: parseInt(match[1], 10),
col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2]
}
}
}
function destroy(){
var instance = this;
if (instance.observer){
destroyObserver.call(instance);
unbindEvents.call(instance);
}
}
function destroyObserver(){
var instance = this;
jsonpatch.unobserve(instance.observedData, instance.observer);
delete instance.observeChangesActive;
delete instance.pauseObservingChanges;
delete instance.resumeObservingChanges;
}
function bindEvents(){
var instance = this;
instance.addHook('afterDestroy', destroy);
instance.addHook('afterCreateRow', afterTableAlter);
instance.addHook('afterRemoveRow', afterTableAlter);
instance.addHook('afterCreateCol', afterTableAlter);
instance.addHook('afterRemoveCol', afterTableAlter);
instance.addHook('afterChange', function(changes, source){
if(source != 'loadData'){
afterTableAlter.call(this);
}
});
}
function unbindEvents(){
var instance = this;
instance.removeHook('afterDestroy', destroy);
instance.removeHook('afterCreateRow', afterTableAlter);
instance.removeHook('afterRemoveRow', afterTableAlter);
instance.removeHook('afterCreateCol', afterTableAlter);
instance.removeHook('afterRemoveCol', afterTableAlter);
instance.removeHook('afterChange', afterTableAlter);
}
function afterTableAlter(){
var instance = this;
instance.pauseObservingChanges();
instance.addHookOnce('afterChangesObserved', function(){
instance.resumeObservingChanges();
});
}
})();
/*
*
* Plugin enables saving table state
*
* */
function Storage(prefix) {
var savedKeys;
var saveSavedKeys = function () {
window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys);
};
var loadSavedKeys = function () {
var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys'];
var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0;
savedKeys = keys ? keys : [];
};
var clearSavedKeys = function () {
savedKeys = [];
saveSavedKeys();
};
loadSavedKeys();
this.saveValue = function (key, value) {
window.localStorage[prefix + '_' + key] = JSON.stringify(value);
if (savedKeys.indexOf(key) == -1) {
savedKeys.push(key);
saveSavedKeys();
}
};
this.loadValue = function (key, defaultValue) {
key = typeof key != 'undefined' ? key : defaultValue;
var value = window.localStorage[prefix + '_' + key];
return typeof value == "undefined" ? void 0 : JSON.parse(value);
};
this.reset = function (key) {
window.localStorage.removeItem(prefix + '_' + key);
};
this.resetAll = function () {
for (var index = 0; index < savedKeys.length; index++) {
window.localStorage.removeItem(prefix + '_' + savedKeys[index]);
}
clearSavedKeys();
};
}
(function (StorageClass) {
function HandsontablePersistentState() {
var plugin = this;
this.init = function () {
var instance = this,
pluginSettings = instance.getSettings()['persistentState'];
plugin.enabled = !!(pluginSettings);
if (!plugin.enabled) {
removeHooks.call(instance);
return;
}
if (!instance.storage) {
instance.storage = new StorageClass(instance.rootElement[0].id);
}
instance.resetState = plugin.resetValue;
addHooks.call(instance);
};
this.saveValue = function (key, value) {
var instance = this;
instance.storage.saveValue(key, value);
};
this.loadValue = function (key, saveTo) {
var instance = this;
saveTo.value = instance.storage.loadValue(key);
};
this.resetValue = function (key) {
var instance = this;
if (typeof key != 'undefined') {
instance.storage.reset(key);
} else {
instance.storage.resetAll();
}
};
var hooks = {
'persistentStateSave': plugin.saveValue,
'persistentStateLoad': plugin.loadValue,
'persistentStateReset': plugin.resetValue
};
function addHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName) && !hookExists.call(instance, hookName)) {
instance.PluginHooks.add(hookName, hooks[hookName]);
}
}
}
function removeHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName) && hookExists.call(instance, hookName)) {
instance.PluginHooks.remove(hookName, hooks[hookName]);
}
}
}
function hookExists(hookName) {
var instance = this;
return instance.PluginHooks.hooks.hasOwnProperty(hookName);
}
}
var htPersistentState = new HandsontablePersistentState();
Handsontable.PluginHooks.add('beforeInit', htPersistentState.init);
Handsontable.PluginHooks.add('afterUpdateSettings', htPersistentState.init);
})(Storage);
/**
* Handsontable UndoRedo class
*/
(function(Handsontable){
Handsontable.UndoRedo = function (instance) {
var plugin = this;
this.instance = instance;
this.doneActions = [];
this.undoneActions = [];
this.ignoreNewActions = false;
instance.addHook("afterChange", function (changes, origin) {
if(changes){
var action = new Handsontable.UndoRedo.ChangeAction(changes);
plugin.done(action);
}
});
instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateRowAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveRow", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( originalData.length + index ) % originalData.length;
var removedData = originalData.slice(index, index + amount);
var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData);
plugin.done(action);
});
instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveCol", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols();
var removedData = [];
for (var i = 0, len = originalData.length; i < len; i++) {
removedData[i] = originalData[i].slice(index, index + amount);
}
var headers;
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
headers = instance.getSettings().colHeaders.slice(index, index + removedData.length);
}
var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers);
plugin.done(action);
});
};
Handsontable.UndoRedo.prototype.done = function (action) {
if (!this.ignoreNewActions) {
this.doneActions.push(action);
this.undoneActions.length = 0;
}
};
/**
* Undo operation from current revision
*/
Handsontable.UndoRedo.prototype.undo = function () {
if (this.isUndoAvailable()) {
var action = this.doneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.undo(this.instance, function () {
that.ignoreNewActions = false;
that.undoneActions.push(action);
});
}
};
/**
* Redo operation from current revision
*/
Handsontable.UndoRedo.prototype.redo = function () {
if (this.isRedoAvailable()) {
var action = this.undoneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.redo(this.instance, function () {
that.ignoreNewActions = false;
that.doneActions.push(action);
});
}
};
/**
* Returns true if undo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isUndoAvailable = function () {
return this.doneActions.length > 0;
};
/**
* Returns true if redo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isRedoAvailable = function () {
return this.undoneActions.length > 0;
};
/**
* Clears undo history
*/
Handsontable.UndoRedo.prototype.clear = function () {
this.doneActions.length = 0;
this.undoneActions.length = 0;
};
Handsontable.UndoRedo.Action = function () {
};
Handsontable.UndoRedo.Action.prototype.undo = function () {
};
Handsontable.UndoRedo.Action.prototype.redo = function () {
};
Handsontable.UndoRedo.ChangeAction = function (changes) {
this.changes = changes;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance, undoneCallback) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(3, 1);
}
instance.addHookOnce('afterChange', undoneCallback);
instance.setDataAtRowProp(data, null, null, 'undo');
};
Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance, onFinishCallback) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(2, 1);
}
instance.addHookOnce('afterChange', onFinishCallback);
instance.setDataAtRowProp(data, null, null, 'redo');
};
Handsontable.UndoRedo.CreateRowAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveRow', undoneCallback);
instance.alter('remove_row', this.index, this.amount);
};
Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateRow', redoneCallback);
instance.alter('insert_row', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveRowAction = function (index, data) {
this.index = index;
this.data = data;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance, undoneCallback) {
var spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data);
Array.prototype.splice.apply(instance.getData(), spliceArgs);
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveRow', redoneCallback);
instance.alter('remove_row', this.index, this.data.length);
};
Handsontable.UndoRedo.CreateColumnAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveCol', undoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateCol', redoneCallback);
instance.alter('insert_col', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) {
this.index = index;
this.data = data;
this.amount = this.data[0].length;
this.headers = headers;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance, undoneCallback) {
var row, spliceArgs;
for (var i = 0, len = instance.getData().length; i < len; i++) {
row = instance.getDataAtRow(i);
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data[i]);
Array.prototype.splice.apply(row, spliceArgs);
}
if(typeof this.headers != 'undefined'){
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.headers);
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs);
}
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveCol', redoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
})(Handsontable);
(function(Handsontable){
function init(){
var instance = this;
var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo;
if(pluginEnabled){
if(!instance.undoRedo){
instance.undoRedo = new Handsontable.UndoRedo(instance);
exposeUndoRedoMethods(instance);
instance.addHook('beforeKeyDown', onBeforeKeyDown);
instance.addHook('afterChange', onAfterChange);
}
} else {
if(instance.undoRedo){
delete instance.undoRedo;
removeExposedUndoRedoMethods(instance);
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
instance.removeHook('afterChange', onAfterChange);
}
}
}
function onBeforeKeyDown(event){
var instance = this;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if(ctrlDown){
if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z
instance.undoRedo.redo();
event.stopImmediatePropagation();
}
else if (event.keyCode === 90) { //CTRL + Z
instance.undoRedo.undo();
event.stopImmediatePropagation();
}
}
}
function onAfterChange(changes, source){
var instance = this;
if (source == 'loadData'){
return instance.undoRedo.clear();
}
}
function exposeUndoRedoMethods(instance){
instance.undo = function(){
return instance.undoRedo.undo();
};
instance.redo = function(){
return instance.undoRedo.redo();
};
instance.isUndoAvailable = function(){
return instance.undoRedo.isUndoAvailable();
};
instance.isRedoAvailable = function(){
return instance.undoRedo.isRedoAvailable();
};
instance.clearUndo = function(){
return instance.undoRedo.clear();
};
}
function removeExposedUndoRedoMethods(instance){
delete instance.undo;
delete instance.redo;
delete instance.isUndoAvailable;
delete instance.isRedoAvailable;
delete instance.clearUndo;
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
})(Handsontable);
/**
* Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport
* @constructor
*/
function DragToScroll() {
this.boundaries = null;
this.callback = null;
}
/**
* @param boundaries {Object} compatible with getBoundingClientRect
*/
DragToScroll.prototype.setBoundaries = function (boundaries) {
this.boundaries = boundaries;
};
/**
* @param callback {Function}
*/
DragToScroll.prototype.setCallback = function (callback) {
this.callback = callback;
};
/**
* Check if mouse position (x, y) is outside of the viewport
* @param x
* @param y
*/
DragToScroll.prototype.check = function (x, y) {
var diffX = 0;
var diffY = 0;
if (y < this.boundaries.top) {
//y is less than top
diffY = y - this.boundaries.top;
}
else if (y > this.boundaries.bottom) {
//y is more than bottom
diffY = y - this.boundaries.bottom;
}
if (x < this.boundaries.left) {
//x is less than left
diffX = x - this.boundaries.left;
}
else if (x > this.boundaries.right) {
//x is more than right
diffX = x - this.boundaries.right;
}
this.callback(diffX, diffY);
};
var listening = false;
var dragToScroll;
var instance;
if (typeof Handsontable !== 'undefined') {
var setupListening = function (instance) {
var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll
dragToScroll = new DragToScroll();
if (scrollHandler === window) {
//not much we can do currently
return;
}
else if (scrollHandler) {
dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect());
}
else {
dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect());
}
dragToScroll.setCallback(function (scrollX, scrollY) {
if (scrollX < 0) {
if (scrollHandler) {
scrollHandler.scrollLeft -= 50;
}
else {
instance.view.wt.scrollHorizontal(-1).draw();
}
}
else if (scrollX > 0) {
if (scrollHandler) {
scrollHandler.scrollLeft += 50;
}
else {
instance.view.wt.scrollHorizontal(1).draw();
}
}
if (scrollY < 0) {
if (scrollHandler) {
scrollHandler.scrollTop -= 20;
}
else {
instance.view.wt.scrollVertical(-1).draw();
}
}
else if (scrollY > 0) {
if (scrollHandler) {
scrollHandler.scrollTop += 20;
}
else {
instance.view.wt.scrollVertical(1).draw();
}
}
});
listening = true;
};
Handsontable.PluginHooks.add('afterInit', function () {
$(document).on('mouseup.' + this.guid, function () {
listening = false;
});
$(document).on('mousemove.' + this.guid, function (event) {
if (listening) {
dragToScroll.check(event.clientX, event.clientY);
}
});
});
Handsontable.PluginHooks.add('destroy', function () {
$(document).off('.' + this.guid);
});
Handsontable.PluginHooks.add('afterOnCellMouseDown', function () {
setupListening(this);
});
Handsontable.PluginHooks.add('afterOnCellCornerMouseDown', function () {
setupListening(this);
});
Handsontable.plugins.DragToScroll = DragToScroll;
}
(function (Handsontable, CopyPaste, SheetClip) {
function CopyPastePlugin(instance) {
this.copyPasteInstance = CopyPaste.getInstance();
this.copyPasteInstance.onCut(onCut);
this.copyPasteInstance.onPaste(onPaste);
var plugin = this;
instance.addHook('beforeKeyDown', onBeforeKeyDown);
function onCut() {
if (!instance.isListening()) {
return;
}
instance.selection.empty();
}
function onPaste(str) {
if (!instance.isListening() || !instance.selection.isSelected()) {
return;
}
var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input
, inputArray = SheetClip.parse(input)
, selected = instance.getSelected()
, coords = instance.getCornerCoords([{row: selected[0], col: selected[1]}, {row: selected[2], col: selected[3]}])
, areaStart = coords.TL
, areaEnd = {
row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row),
col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col)
};
instance.PluginHooks.once('afterChange', function (changes, source) {
if (changes && changes.length) {
this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col);
}
});
instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode);
};
function onBeforeKeyDown (event) {
if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) {
//when CTRL is pressed, prepare selectable text in textarea
//http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript
plugin.setCopyableText();
event.stopImmediatePropagation();
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) {
setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin));
}
}
this.destroy = function () {
this.copyPasteInstance.removeCallback(onCut);
this.copyPasteInstance.removeCallback(onPaste);
this.copyPasteInstance.destroy();
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this));
this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance);
this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance);
/**
* Prepares copyable text in the invisible textarea
*/
this.setCopyableText = function () {
var selection = instance.getSelected();
var settings = instance.getSettings();
var copyRowsLimit = settings.copyRowsLimit;
var copyColsLimit = settings.copyColsLimit;
var startRow = Math.min(selection[0], selection[2]);
var startCol = Math.min(selection[1], selection[3]);
var endRow = Math.max(selection[0], selection[2]);
var endCol = Math.max(selection[1], selection[3]);
var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1);
var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1);
instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol));
if (endRow !== finalEndRow || endCol !== finalEndCol) {
instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit);
}
};
}
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().copyPaste !== false;
if(pluginEnabled && !instance.copyPaste){
instance.copyPaste = new CopyPastePlugin(instance);
} else if (!pluginEnabled && instance.copyPaste) {
instance.copyPaste.destroy();
delete instance.copyPaste;
}
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
})(Handsontable, CopyPaste, SheetClip);
(function (Handsontable) {
'use strict';
Handsontable.Search = function Search(instance) {
this.query = function (queryStr, callback, queryMethod) {
var rowCount = instance.countRows();
var colCount = instance.countCols();
var queryResult = [];
if (!callback) {
callback = Handsontable.Search.global.getDefaultCallback();
}
if (!queryMethod) {
queryMethod = Handsontable.Search.global.getDefaultQueryMethod();
}
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
for (var colIndex = 0; colIndex < colCount; colIndex++) {
var cellData = instance.getDataAtCell(rowIndex, colIndex);
var cellProperties = instance.getCellMeta(rowIndex, colIndex);
var cellCallback = cellProperties.search.callback || callback;
var cellQueryMethod = cellProperties.search.queryMethod || queryMethod;
var testResult = cellQueryMethod(queryStr, cellData);
if (testResult) {
var singleResult = {
row: rowIndex,
col: colIndex,
data: cellData
};
queryResult.push(singleResult);
}
if (cellCallback) {
cellCallback(instance, rowIndex, colIndex, cellData, testResult);
}
}
}
return queryResult;
};
};
Handsontable.Search.DEFAULT_CALLBACK = function (instance, row, col, data, testResult) {
instance.getCellMeta(row, col).isSearchResult = testResult;
};
Handsontable.Search.DEFAULT_QUERY_METHOD = function (query, value) {
if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length == 0){
return false;
}
return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1;
};
Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult';
Handsontable.Search.global = (function () {
var defaultCallback = Handsontable.Search.DEFAULT_CALLBACK;
var defaultQueryMethod = Handsontable.Search.DEFAULT_QUERY_METHOD;
var defaultSearchResultClass = Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS;
return {
getDefaultCallback: function () {
return defaultCallback;
},
setDefaultCallback: function (newDefaultCallback) {
defaultCallback = newDefaultCallback;
},
getDefaultQueryMethod: function () {
return defaultQueryMethod;
},
setDefaultQueryMethod: function (newDefaultQueryMethod) {
defaultQueryMethod = newDefaultQueryMethod;
},
getDefaultSearchResultClass: function () {
return defaultSearchResultClass;
},
setDefaultSearchResultClass: function (newSearchResultClass) {
defaultSearchResultClass = newSearchResultClass;
}
}
})();
Handsontable.SearchCellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
var searchResultClass = (typeof cellProperties.search == 'object' && cellProperties.search.searchResultClass) || Handsontable.Search.global.getDefaultSearchResultClass();
if(cellProperties.isSearchResult){
Handsontable.Dom.addClass(TD, searchResultClass);
} else {
Handsontable.Dom.removeClass(TD, searchResultClass);
}
};
var originalDecorator = Handsontable.renderers.cellDecorator;
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
originalDecorator.apply(this, arguments);
Handsontable.SearchCellDecorator.apply(this, arguments);
};
function init() {
var instance = this;
var pluginEnabled = !!instance.getSettings().search;
if (pluginEnabled) {
instance.search = new Handsontable.Search(instance);
} else {
delete instance.search;
}
}
Handsontable.PluginHooks.add('afterInit', init);
Handsontable.PluginHooks.add('afterUpdateSettings', init);
})(Handsontable);
/**
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
* and (optionally) implements behavior needed for native horizontal and vertical scrolling
*/
function WalkontableOverlay() {
this.maxOuts = 10; //max outs in one direction (before and after table)
}
/*
Possible optimizations:
[x] don't rerender if scroll delta is smaller than the fragment outside of the viewport
[ ] move .style.top change before .draw()
[ ] put .draw() in requestAnimationFrame
[ ] don't rerender rows that remain visible after the scroll
*/
WalkontableOverlay.prototype.init = function () {
this.TABLE = this.instance.wtTable.TABLE;
this.fixed = this.instance.wtTable.hider;
this.fixedContainer = this.instance.wtTable.holder;
this.fixed.style.position = 'absolute';
this.fixed.style.left = '0';
this.scrollHandler = this.getScrollableElement(this.TABLE);
this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here
};
WalkontableOverlay.prototype.makeClone = function (direction) {
var clone = document.createElement('DIV');
clone.className = 'ht_clone_' + direction + ' handsontable';
clone.style.position = 'fixed';
clone.style.overflow = 'hidden';
var table2 = document.createElement('TABLE');
table2.className = this.instance.wtTable.TABLE.className;
clone.appendChild(table2);
this.instance.wtTable.holder.parentNode.appendChild(clone);
return new Walkontable({
cloneSource: this.instance,
cloneOverlay: this,
table: table2
});
};
WalkontableOverlay.prototype.getScrollableElement = function (TABLE) {
var el = TABLE.parentNode;
while (el && el.style) {
if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
return el;
}
if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') {
return el;
}
el = el.parentNode;
}
return window;
};
WalkontableOverlay.prototype.prepare = function () {
};
WalkontableOverlay.prototype.onScroll = function (forcePosition) {
this.windowScrollPosition = this.getScrollPosition();
this.readSettings(); //read window scroll position
if (forcePosition) {
this.windowScrollPosition = forcePosition;
}
this.resetFixedPosition(); //may be redundant
};
WalkontableOverlay.prototype.availableSize = function () {
var availableSize;
if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) {
availableSize = this.instance.wtDom.outerHeight(this.TABLE);
}
else {
availableSize = this.windowSize;
}
}
else {
availableSize = this.windowSize - (this.tableParentOffset);
}
return availableSize;
};
WalkontableOverlay.prototype.refresh = function (selectionsOnly) {
var last = this.getLastCell();
this.measureBefore = this.sumCellSizes(0, this.offset);
if (last === -1) { //last -1 means that viewport is scrolled behind the table
this.measureAfter = 0;
}
else {
this.measureAfter = this.sumCellSizes(last, this.total - last);
}
this.applyToDOM();
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableOverlay.prototype.destroy = function () {
this.$scrollHandler.off('.' + this.instance.guid);
$(window).off('.' + this.instance.guid);
$(document).off('.' + this.instance.guid);
};
function WalkontableBorder(instance, settings) {
var style;
//reference to instance
this.instance = instance;
this.settings = settings;
this.wtDom = this.instance.wtDom;
this.main = document.createElement("div");
style = this.main.style;
style.position = 'absolute';
style.top = 0;
style.left = 0;
// style.visibility = 'hidden';
for (var i = 0; i < 5; i++) {
var DIV = document.createElement('DIV');
DIV.className = 'wtBorder ' + (settings.className || '');
style = DIV.style;
style.backgroundColor = settings.border.color;
style.height = settings.border.width + 'px';
style.width = settings.border.width + 'px';
this.main.appendChild(DIV);
}
this.top = this.main.childNodes[0];
this.left = this.main.childNodes[1];
this.bottom = this.main.childNodes[2];
this.right = this.main.childNodes[3];
/*$(this.top).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.left).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.bottom).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});
$(this.right).on(sss, function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$(this).hide();
});*/
this.topStyle = this.top.style;
this.leftStyle = this.left.style;
this.bottomStyle = this.bottom.style;
this.rightStyle = this.right.style;
this.corner = this.main.childNodes[4];
this.corner.className += ' corner';
this.cornerStyle = this.corner.style;
this.cornerStyle.width = '5px';
this.cornerStyle.height = '5px';
this.cornerStyle.border = '2px solid #FFF';
this.disappear();
if (!instance.wtTable.bordersHolder) {
instance.wtTable.bordersHolder = document.createElement('div');
instance.wtTable.bordersHolder.className = 'htBorders';
instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder);
}
instance.wtTable.bordersHolder.appendChild(this.main);
var down = false;
var $body = $(document.body);
$body.on('mousedown.walkontable.' + instance.guid, function () {
down = true;
});
$body.on('mouseup.walkontable.' + instance.guid, function () {
down = false
});
$(this.main.childNodes).on('mouseenter', function (event) {
if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
var bounds = this.getBoundingClientRect();
var $this = $(this);
$this.hide();
var isOutside = function (event) {
if (event.clientY < Math.floor(bounds.top)) {
return true;
}
if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
return true;
}
if (event.clientX < Math.floor(bounds.left)) {
return true;
}
if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
return true;
}
};
$body.on('mousemove.border.' + instance.guid, function (event) {
if (isOutside(event)) {
$body.off('mousemove.border.' + instance.guid);
$this.show();
}
});
});
}
/**
* Show border around one or many cells
* @param {Array} corners
*/
WalkontableBorder.prototype.appear = function (corners) {
var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width;
if (this.disabled) {
return;
}
var instance = this.instance
, fromRow
, fromColumn
, toRow
, toColumn
, hideTop = false
, hideLeft = false
, hideBottom = false
, hideRight = false
, i
, ilen
, s;
if (!instance.wtTable.isRowInViewport(corners[0])) {
hideTop = true;
}
if (!instance.wtTable.isRowInViewport(corners[2])) {
hideBottom = true;
}
ilen = instance.wtTable.rowStrategy.countVisible();
for (i = 0; i < ilen; i++) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
fromRow = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
toRow = s;
break;
}
}
if (hideTop && hideBottom) {
hideLeft = true;
hideRight = true;
}
else {
if (!instance.wtTable.isColumnInViewport(corners[1])) {
hideLeft = true;
}
if (!instance.wtTable.isColumnInViewport(corners[3])) {
hideRight = true;
}
ilen = instance.wtTable.columnStrategy.countVisible();
for (i = 0; i < ilen; i++) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
fromColumn = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
toColumn = s;
break;
}
}
}
if (fromRow !== void 0 && fromColumn !== void 0) {
isMultiple = (fromRow !== toRow || fromColumn !== toColumn);
fromTD = instance.wtTable.getCell([fromRow, fromColumn]);
toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD;
fromOffset = this.wtDom.offset(fromTD);
toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset;
containerOffset = this.wtDom.offset(instance.wtTable.TABLE);
minTop = fromOffset.top;
height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop;
minLeft = fromOffset.left;
width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft;
top = minTop - containerOffset.top - 1;
left = minLeft - containerOffset.left - 1;
var style = this.wtDom.getComputedStyle(fromTD);
if (parseInt(style['borderTopWidth'], 10) > 0) {
top += 1;
height = height > 0 ? height - 1 : 0;
}
if (parseInt(style['borderLeftWidth'], 10) > 0) {
left += 1;
width = width > 0 ? width - 1 : 0;
}
}
else {
this.disappear();
return;
}
if (hideTop) {
this.topStyle.display = 'none';
}
else {
this.topStyle.top = top + 'px';
this.topStyle.left = left + 'px';
this.topStyle.width = width + 'px';
this.topStyle.display = 'block';
}
if (hideLeft) {
this.leftStyle.display = 'none';
}
else {
this.leftStyle.top = top + 'px';
this.leftStyle.left = left + 'px';
this.leftStyle.height = height + 'px';
this.leftStyle.display = 'block';
}
var delta = Math.floor(this.settings.border.width / 2);
if (hideBottom) {
this.bottomStyle.display = 'none';
}
else {
this.bottomStyle.top = top + height - delta + 'px';
this.bottomStyle.left = left + 'px';
this.bottomStyle.width = width + 'px';
this.bottomStyle.display = 'block';
}
if (hideRight) {
this.rightStyle.display = 'none';
}
else {
this.rightStyle.top = top + 'px';
this.rightStyle.left = left + width - delta + 'px';
this.rightStyle.height = height + 1 + 'px';
this.rightStyle.display = 'block';
}
if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) {
this.cornerStyle.display = 'none';
}
else {
this.cornerStyle.top = top + height - 4 + 'px';
this.cornerStyle.left = left + width - 4 + 'px';
this.cornerStyle.display = 'block';
}
};
/**
* Hide border
*/
WalkontableBorder.prototype.disappear = function () {
this.topStyle.display = 'none';
this.leftStyle.display = 'none';
this.bottomStyle.display = 'none';
this.rightStyle.display = 'none';
this.cornerStyle.display = 'none';
};
WalkontableBorder.prototype.hasSetting = function (setting) {
if (typeof setting === 'function') {
return setting();
}
return !!setting;
};
/**
* WalkontableCellFilter
* @constructor
*/
function WalkontableCellFilter() {
this.offset = 0;
this.total = 0;
this.fixedCount = 0;
}
WalkontableCellFilter.prototype.source = function (n) {
return n;
};
WalkontableCellFilter.prototype.offsetted = function (n) {
return n + this.offset;
};
WalkontableCellFilter.prototype.unOffsetted = function (n) {
return n - this.offset;
};
WalkontableCellFilter.prototype.fixed = function (n) {
if (n < this.fixedCount) {
return n - this.offset;
}
else {
return n;
}
};
WalkontableCellFilter.prototype.unFixed = function (n) {
if (n < this.fixedCount) {
return n + this.offset;
}
else {
return n;
}
};
WalkontableCellFilter.prototype.visibleToSource = function (n) {
return this.source(this.offsetted(this.fixed(n)));
};
WalkontableCellFilter.prototype.sourceToVisible = function (n) {
return this.source(this.unOffsetted(this.unFixed(n)));
};
/**
* WalkontableCellStrategy
* @constructor
*/
function WalkontableCellStrategy(instance) {
this.instance = instance;
}
WalkontableCellStrategy.prototype.getSize = function (index) {
return this.cellSizes[index];
};
WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) {
return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn;
};
WalkontableCellStrategy.prototype.countVisible = function () {
return this.cellCount;
};
WalkontableCellStrategy.prototype.isLastIncomplete = function () {
if(this.instance.getSetting('nativeScrollbars')){
var nativeScrollbar = this.instance.cloneFrom ? this.instance.cloneFrom.wtScrollbars.vertical : this.instance.wtScrollbars.vertical;
return this.remainingSize > nativeScrollbar.sumCellSizes(nativeScrollbar.offset, nativeScrollbar.offset + nativeScrollbar.curOuts + 1);
} else {
return this.remainingSize > 0;
}
};
/**
* WalkontableClassNameList
* @constructor
*/
function WalkontableClassNameCache() {
this.cache = [];
}
WalkontableClassNameCache.prototype.add = function (r, c, cls) {
if (!this.cache[r]) {
this.cache[r] = [];
}
if (!this.cache[r][c]) {
this.cache[r][c] = [];
}
this.cache[r][c][cls] = true;
};
WalkontableClassNameCache.prototype.test = function (r, c, cls) {
return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]);
};
/**
* WalkontableColumnFilter
* @constructor
*/
function WalkontableColumnFilter() {
this.countTH = 0;
}
WalkontableColumnFilter.prototype = new WalkontableCellFilter();
WalkontableColumnFilter.prototype.readSettings = function (instance) {
this.offset = instance.wtSettings.settings.offsetColumn;
this.total = instance.getSetting('totalColumns');
this.fixedCount = instance.getSetting('fixedColumnsLeft');
this.countTH = instance.getSetting('rowHeaders').length;
};
WalkontableColumnFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableColumnFilter.prototype.unOffsettedTH = function (n) {
return n + this.countTH;
};
WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableColumnStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @param strategy - all, last, none
* @constructor
*/
function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) {
var size
, i = 0;
WalkontableCellStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellStretch = [];
this.cellCount = 0;
this.remainingSize = 0;
this.strategy = strategy;
//step 1 - determine cells that fit containerSize and cache their widths
while (true) {
size = sizeAtIndex(i);
if (size === void 0) {
break; //total columns exceeded
}
if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) {
break; //total width exceeded
}
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
i++;
}
var containerSize = this.getContainerSize(this.cellSizesSum);
this.remainingSize = this.cellSizesSum - containerSize;
//negative value means the last cell is fully visible and there is some space left for stretching
//positive value means the last cell is not fully visible
}
WalkontableColumnStrategy.prototype = new WalkontableCellStrategy();
WalkontableColumnStrategy.prototype.getSize = function (index) {
return this.cellSizes[index] + (this.cellStretch[index] || 0);
};
WalkontableColumnStrategy.prototype.stretch = function () {
//step 2 - apply stretching strategy
var containerSize = this.getContainerSize(this.cellSizesSum)
, i = 0;
this.remainingSize = this.cellSizesSum - containerSize;
this.cellStretch.length = 0; //clear previous stretch
if (this.strategy === 'all') {
if (this.remainingSize < 0) {
var ratio = containerSize / this.cellSizesSum;
var newSize;
while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop
newSize = Math.floor(ratio * this.cellSizes[i]);
this.remainingSize += newSize - this.cellSizes[i];
this.cellStretch[i] = newSize - this.cellSizes[i];
i++;
}
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
else if (this.strategy === 'last') {
if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test)
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
};
function Walkontable(settings) {
var that = this,
originalHeaders = [];
this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events
//bootstrap from settings
this.wtDom = new WalkontableDom();
if (settings.cloneSource) {
this.cloneSource = settings.cloneSource;
this.cloneOverlay = settings.cloneOverlay;
this.wtSettings = settings.cloneSource.wtSettings;
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = settings.cloneSource.wtViewport;
}
else {
this.wtSettings = new WalkontableSettings(this, settings);
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = new WalkontableViewport(this);
this.wtScrollbars = new WalkontableScrollbars(this);
this.wtWheel = new WalkontableWheel(this);
this.wtEvent = new WalkontableEvent(this);
}
//find original headers
if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
}
if (!this.getSetting('columnHeaders').length) {
this.update('columnHeaders', [function (column, TH) {
that.wtDom.fastInnerText(TH, originalHeaders[column]);
}]);
}
}
//initialize selections
this.selections = {};
var selectionsSettings = this.getSetting('selections');
if (selectionsSettings) {
for (var i in selectionsSettings) {
if (selectionsSettings.hasOwnProperty(i)) {
this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]);
}
}
}
this.drawn = false;
this.drawInterrupted = false;
//at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
/*if (window.Handsontable) {
Handsontable.PluginHooks.add('beforeChange', function () {
if (that.rowHeightCache) {
that.rowHeightCache.length = 0;
}
});
}*/
}
Walkontable.prototype.draw = function (selectionsOnly) {
this.drawInterrupted = false;
if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) {
this.drawInterrupted = true; //draw interrupted because TABLE is not visible
return;
}
this.getSetting('beforeDraw', !selectionsOnly);
selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn;
if (this.drawn) { //fix offsets that might have changed
this.scrollVertical(0);
this.scrollHorizontal(0);
}
this.lastOffsetRow = this.getSetting('offsetRow');
this.lastOffsetColumn = this.getSetting('offsetColumn');
this.wtTable.draw(selectionsOnly);
if (!this.cloneSource) {
this.getSetting('onDraw', !selectionsOnly);
}
return this;
};
Walkontable.prototype.update = function (settings, value) {
return this.wtSettings.update(settings, value);
};
Walkontable.prototype.scrollVertical = function (delta) {
var result = this.wtScroll.scrollVertical(delta);
this.getSetting('onScrollVertically');
return result;
};
Walkontable.prototype.scrollHorizontal = function (delta) {
var result = this.wtScroll.scrollHorizontal(delta);
this.getSetting('onScrollHorizontally');
return result;
};
Walkontable.prototype.scrollViewport = function (coords) {
this.wtScroll.scrollViewport(coords);
return this;
};
Walkontable.prototype.getViewport = function () {
return [
this.wtTable.rowFilter.visibleToSource(0),
this.wtTable.columnFilter.visibleToSource(0),
this.wtTable.getLastVisibleRow(),
this.wtTable.getLastVisibleColumn()
];
};
Walkontable.prototype.getSetting = function (key, param1, param2, param3) {
return this.wtSettings.getSetting(key, param1, param2, param3);
};
Walkontable.prototype.hasSetting = function (key) {
return this.wtSettings.has(key);
};
Walkontable.prototype.destroy = function () {
$(document.body).off('.' + this.guid);
this.wtScrollbars.destroy();
clearTimeout(this.wheelTimeout);
this.wtEvent && this.wtEvent.destroy();
};
/**
* A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays.
* Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly
* @param instance
* @constructor
*/
function WalkontableDebugOverlay(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('debug');
this.clone.wtTable.holder.style.opacity = 0.4;
this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000';
var that = this;
var lastTimeout;
var lastX = 0;
var lastY = 0;
var overlayContainer = that.clone.wtTable.holder.parentNode;
$(document.body).on('mousemove.' + this.instance.guid, function (event) {
if (!that.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) {
return; //ignore minor mouse movement
}
lastX = event.clientX;
lastY = event.clientY;
WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden');
WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible');
clearTimeout(lastTimeout);
lastTimeout = setTimeout(function () {
WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden');
WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible');
}, 1000);
});
}
WalkontableDebugOverlay.prototype = new WalkontableOverlay();
WalkontableDebugOverlay.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box = this.instance.wtTable.holder.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
};
WalkontableDebugOverlay.prototype.prepare = function () {
};
WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) {
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableDebugOverlay.prototype.getScrollPosition = function () {
};
WalkontableDebugOverlay.prototype.getLastCell = function () {
};
WalkontableDebugOverlay.prototype.applyToDOM = function () {
};
WalkontableDebugOverlay.prototype.scrollTo = function () {
};
WalkontableDebugOverlay.prototype.readWindowSize = function () {
};
WalkontableDebugOverlay.prototype.readSettings = function () {
};
function WalkontableDom() {
}
//goes up the DOM tree (including given element) until it finds an element that matches the nodeName
WalkontableDom.prototype.closest = function (elem, nodeNames, until) {
while (elem != null && elem !== until) {
if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) {
return elem;
}
elem = elem.parentNode;
}
return null;
};
//goes up the DOM tree and checks if element is child of another element
WalkontableDom.prototype.isChildOf = function (child, parent) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Counts index of element within its parent
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
* Otherwise would need to check for nodeType or use previousElementSibling
* @see http://jsperf.com/sibling-index/10
* @param {Element} elem
* @return {Number}
*/
WalkontableDom.prototype.index = function (elem) {
var i = 0;
while (elem = elem.previousSibling) {
++i
}
return i;
};
if (document.documentElement.classList) {
// HTML5 classList API
WalkontableDom.prototype.hasClass = function (ele, cls) {
return ele.classList.contains(cls);
};
WalkontableDom.prototype.addClass = function (ele, cls) {
ele.classList.add(cls);
};
WalkontableDom.prototype.removeClass = function (ele, cls) {
ele.classList.remove(cls);
};
}
else {
//http://snipplr.com/view/3561/addclass-removeclass-hasclass/
WalkontableDom.prototype.hasClass = function (ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
WalkontableDom.prototype.addClass = function (ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
};
WalkontableDom.prototype.removeClass = function (ele, cls) {
if (this.hasClass(ele, cls)) { //is this really needed?
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js
}
};
}
/*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
WalkontableDom.prototype.addEvent = (function () {
var that = this;
if (document.addEventListener) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.addEventListener(type, cb, false);
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
else {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.attachEvent('on' + type, function () {
//normalize
//http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
var e = window['event'];
e.target = e.srcElement;
//e.offsetX = e.layerX;
//e.offsetY = e.layerY;
e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
return cb.call(elem, e)
});
}
else if (elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
})();
WalkontableDom.prototype.triggerEvent = function (element, eventName, target) {
var event;
if (document.createEvent) {
event = document.createEvent("MouseEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.target = target;
if (document.createEvent) {
target.dispatchEvent(event);
} else {
target.fireEvent("on" + event.eventType, event);
}
};*/
WalkontableDom.prototype.removeTextNodes = function (elem, parent) {
if (elem.nodeType === 3) {
parent.removeChild(elem); //bye text nodes!
}
else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) {
var childs = elem.childNodes;
for (var i = childs.length - 1; i >= 0; i--) {
this.removeTextNodes(childs[i], elem);
}
}
};
/**
* Remove childs function
* WARNING - this doesn't unload events and data attached by jQuery
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
* @param element
* @returns {void}
*/
//
WalkontableDom.prototype.empty = function (element) {
var child;
while (child = element.lastChild) {
element.removeChild(child);
}
};
WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
/**
* Insert content into element trying avoid innerHTML method.
* @return {void}
*/
WalkontableDom.prototype.fastInnerHTML = function (element, content) {
if (this.HTML_CHARACTERS.test(content)) {
element.innerHTML = content;
}
else {
this.fastInnerText(element, content);
}
};
/**
* Insert text content into element
* @return {void}
*/
if (document.createTextNode('test').textContent) { //STANDARDS
WalkontableDom.prototype.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.textContent = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
else { //IE8
WalkontableDom.prototype.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.data = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
/**
* Returns true/false depending if element has offset parent
* @param elem
* @returns {boolean}
*/
/*if (document.createTextNode('test').textContent) { //STANDARDS
WalkontableDom.prototype.hasOffsetParent = function (elem) {
return !!elem.offsetParent;
}
}
else {
WalkontableDom.prototype.hasOffsetParent = function (elem) {
try {
if (!elem.offsetParent) {
return false;
}
}
catch (e) {
return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here
}
return true;
}
}*/
/**
* Returns true if element is attached to the DOM and visible, false otherwise
* @param elem
* @returns {boolean}
*/
WalkontableDom.prototype.isVisible = function (elem) {
//fast method according to benchmarks, but requires layout so slow in our case
/*
if (!WalkontableDom.prototype.hasOffsetParent(elem)) {
return false; //fixes problem with UI Bootstrap <tabs> directive
}
// if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here
if (elem.offsetWidth > 0) {
return true;
}
*/
//slow method
var next = elem;
while (next !== document.documentElement) { //until <html> reached
if (next === null) { //parent detached from DOM
return false;
}
else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE
if (next.host) { //this is Web Components Shadow DOM
//see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
//according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
return WalkontableDom.prototype.isVisible(next.host.impl);
}
else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
return WalkontableDom.prototype.isVisible(next.host);
}
else {
throw new Error("Lost in Web Components world");
}
}
else {
return false; //this is a node detached from document in IE8
}
}
else if (next.style.display === 'none') {
return false;
}
next = next.parentNode;
}
return true;
};
/**
* Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster
* @param {HTMLElement} elem
* @return {Object}
*/
WalkontableDom.prototype.offset = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE offset (see also WalkontableDom.prototype.outerHeight)
//http://jsperf.com/offset-vs-getboundingclientrect/8
var box = elem.getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0),
left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)
};
}
var offsetLeft = elem.offsetLeft
, offsetTop = elem.offsetTop
, lastElem = elem;
while (elem = elem.offsetParent) {
if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0
break;
}
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
lastElem = elem;
}
if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6
//if(lastElem !== document.body) { //faster but does gives false positive in Firefox
offsetLeft += window.pageXOffset || document.documentElement.scrollLeft;
offsetTop += window.pageYOffset || document.documentElement.scrollTop;
}
return {
left: offsetLeft,
top: offsetTop
};
};
WalkontableDom.prototype.getComputedStyle = function (elem) {
return elem.currentStyle || document.defaultView.getComputedStyle(elem);
};
WalkontableDom.prototype.outerWidth = function (elem) {
return elem.offsetWidth;
};
WalkontableDom.prototype.outerHeight = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight
//jQuery (1.10.1) still has this unsolved
//may be better to just switch to getBoundingClientRect
//http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
//http://bugs.jquery.com/ticket/2196
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
return elem.offsetHeight + elem.firstChild.offsetHeight;
}
else {
return elem.offsetHeight;
}
};
(function () {
var hasCaptionProblem;
function detectCaptionProblem() {
var TABLE = document.createElement('TABLE');
TABLE.style.borderSpacing = 0;
TABLE.style.borderWidth = 0;
TABLE.style.padding = 0;
var TBODY = document.createElement('TBODY');
TABLE.appendChild(TBODY);
TBODY.appendChild(document.createElement('TR'));
TBODY.firstChild.appendChild(document.createElement('TD'));
TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>';
var CAPTION = document.createElement('CAPTION');
CAPTION.innerHTML = 'c<br>c<br>c<br>c';
CAPTION.style.padding = 0;
CAPTION.style.margin = 0;
TABLE.insertBefore(CAPTION, TBODY);
document.body.appendChild(TABLE);
hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean
document.body.removeChild(TABLE);
}
WalkontableDom.prototype.hasCaptionProblem = function () {
if (hasCaptionProblem === void 0) {
detectCaptionProblem();
}
return hasCaptionProblem;
};
/**
* Returns caret position in text input
* @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
* @return {Number}
*/
WalkontableDom.prototype.getCaretPosition = function (el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) { //IE8
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
/**
* Sets caret position in text input
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
* @param {Element} el
* @param {Number} pos
* @param {Number} endPos
*/
WalkontableDom.prototype.setCaretPosition = function (el, pos, endPos) {
if (endPos === void 0) {
endPos = pos;
}
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, endPos);
}
else if (el.createTextRange) { //IE8
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', endPos);
range.moveStart('character', pos);
range.select();
}
};
var cachedScrollbarWidth;
//http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
(document.body || document.documentElement).removeChild(outer);
return (w1 - w2);
}
/**
* Returns the computed width of the native browser scroll bar
* @return {Number} width
*/
WalkontableDom.prototype.getScrollbarWidth = function () {
if (cachedScrollbarWidth === void 0) {
cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
}
return cachedScrollbarWidth;
}
})();
function WalkontableEvent(instance) {
var that = this;
//reference to instance
this.instance = instance;
this.wtDom = this.instance.wtDom;
var dblClickOrigin = [null, null];
var dblClickTimeout = [null, null];
var onMouseDown = function (event) {
var cell = that.parentCell(event.target);
if (that.wtDom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerMouseDown', event, event.target);
}
else if (cell.TD && cell.TD.nodeName === 'TD') {
if (that.instance.hasSetting('onCellMouseDown')) {
that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD);
}
}
if (event.button !== 2) { //if not right mouse button
if (cell.TD && cell.TD.nodeName === 'TD') {
dblClickOrigin[0] = cell.TD;
clearTimeout(dblClickTimeout[0]);
dblClickTimeout[0] = setTimeout(function () {
dblClickOrigin[0] = null;
}, 1000);
}
}
};
var lastMouseOver;
var onMouseOver = function (event) {
if (that.instance.hasSetting('onCellMouseOver')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) {
lastMouseOver = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};
/* var lastMouseOut;
var onMouseOut = function (event) {
if (that.instance.hasSetting('onCellMouseOut')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) {
lastMouseOut = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};*/
var onMouseUp = function (event) {
if (event.button !== 2) { //if not right mouse button
var cell = that.parentCell(event.target);
if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
if (that.wtDom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD);
}
else if (cell.TD) {
that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD);
}
dblClickOrigin[0] = null;
dblClickOrigin[1] = null;
}
else if (cell.TD === dblClickOrigin[0]) {
dblClickOrigin[1] = cell.TD;
clearTimeout(dblClickTimeout[1]);
dblClickTimeout[1] = setTimeout(function () {
dblClickOrigin[1] = null;
}, 500);
}
}
};
$(this.instance.wtTable.holder).on('mousedown', onMouseDown);
$(this.instance.wtTable.TABLE).on('mouseover', onMouseOver);
// $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut);
$(this.instance.wtTable.holder).on('mouseup', onMouseUp);
}
WalkontableEvent.prototype.parentCell = function (elem) {
var cell = {};
var TABLE = this.instance.wtTable.TABLE;
var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE);
if (TD && this.wtDom.isChildOf(TD, TABLE)) {
cell.coords = this.instance.wtTable.getCoords(TD);
cell.TD = TD;
}
else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current')) {
cell.coords = this.instance.selections.current.selected[0];
cell.TD = this.instance.wtTable.getCell(cell.coords);
}
return cell;
};
WalkontableEvent.prototype.destroy = function () {
clearTimeout(this.dblClickTimeout0);
clearTimeout(this.dblClickTimeout1);
};
function walkontableRangesIntersect() {
var from = arguments[0];
var to = arguments[1];
for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) {
if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) {
return true;
}
}
return false;
}
/**
* Generates a random hex string. Used as namespace for Walkontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
function walkontableRandomString() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4();
}
/**
* http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
*/
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
})();
//http://snipplr.com/view/13523/
//modified for speed
//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
if (!window.getComputedStyle) {
(function () {
var elem;
var styleObj = {
getPropertyValue: function getPropertyValue(prop) {
if (prop == 'float') prop = 'styleFloat';
return elem.currentStyle[prop.toUpperCase()] || null;
}
};
window.getComputedStyle = function (el) {
elem = el;
return styleObj;
}
})();
}
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
*/
if (!String.prototype.trim) {
var trimRegex = /^\s+|\s+$/g;
String.prototype.trim = function () {
return this.replace(trimRegex, '');
};
}
/**
* WalkontableRowFilter
* @constructor
*/
function WalkontableRowFilter() {
}
WalkontableRowFilter.prototype = new WalkontableCellFilter();
WalkontableRowFilter.prototype.readSettings = function (instance) {
if (instance.cloneOverlay instanceof WalkontableDebugOverlay) {
this.offset = 0;
}
else {
this.offset = instance.wtSettings.settings.offsetRow;
}
this.total = instance.getSetting('totalRows');
this.fixedCount = instance.getSetting('fixedRowsTop');
};
/**
* WalkontableRowStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @constructor
*/
function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) {
WalkontableCellStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.sizeAtIndex = sizeAtIndex;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellCount = 0;
this.remainingSize = -Infinity;
}
WalkontableRowStrategy.prototype = new WalkontableCellStrategy();
WalkontableRowStrategy.prototype.add = function (i, TD, reverse) {
if (!this.isLastIncomplete() && this.remainingSize != 0) {
var size = this.sizeAtIndex(i, TD);
if (size === void 0) {
return false; //total rows exceeded
}
var containerSize = this.getContainerSize(this.cellSizesSum + size);
if (reverse) {
this.cellSizes.unshift(size);
}
else {
this.cellSizes.push(size);
}
this.cellSizesSum += size;
this.cellCount++;
this.remainingSize = this.cellSizesSum - containerSize;
if (reverse && this.isLastIncomplete()) { //something is outside of the screen, maybe even some full rows?
return false;
}
return true;
}
return false;
};
WalkontableRowStrategy.prototype.remove = function () {
var size = this.cellSizes.pop();
this.cellSizesSum -= size;
this.cellCount--;
this.remainingSize -= size;
};
WalkontableRowStrategy.prototype.removeOutstanding = function () {
while (this.cellCount > 0 && this.cellSizes[this.cellCount - 1] < this.remainingSize) { //this row is completely off screen!
this.remove();
}
};
function WalkontableScroll(instance) {
this.instance = instance;
}
WalkontableScroll.prototype.scrollVertical = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollVertical can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetRow')
, fixedCount = instance.getSetting('fixedRowsTop')
, total = instance.getSetting('totalRows')
, maxSize = instance.wtViewport.getViewportHeight();
if (total > 0) {
newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) {
if (row - offset < fixedCount && row - offset >= 0) {
return instance.getSetting('rowHeight', row - offset);
}
else {
return instance.getSetting('rowHeight', row);
}
}, function (isReverse) {
instance.wtTable.verticalRenderReverse = isReverse;
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.vertical.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollHorizontal = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollHorizontal can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetColumn')
, fixedCount = instance.getSetting('fixedColumnsLeft')
, total = instance.getSetting('totalColumns')
, maxSize = instance.wtViewport.getViewportWidth();
if (total > 0) {
newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) {
if (col - offset < fixedCount && col - offset >= 0) {
return instance.getSetting('columnWidth', col - offset);
}
else {
return instance.getSetting('columnWidth', col);
}
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.horizontal.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) {
var newOffset = offset + delta;
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
setReverseRenderFn(true);
}
if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta
, sum = 0
, col;
if (newOffset > fixedCount) {
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
col = newOffset;
while (sum < maxSize && col < total) {
sum += cellSizeFn(col);
col++;
}
if (sum < maxSize) {
while (newOffset > 0) {
//if sum still less than available width, we cannot scroll that far (must move offset to the left)
sum += cellSizeFn(newOffset - 1);
if (sum < maxSize) {
newOffset--;
}
else {
break;
}
}
}
}
else if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
/**
* Scrolls viewport to a cell by minimum number of cells
*/
WalkontableScroll.prototype.scrollViewport = function (coords) {
if (!this.instance.drawn) {
return;
}
var offsetRow = this.instance.getSetting('offsetRow')
, offsetColumn = this.instance.getSetting('offsetColumn')
, lastVisibleRow = this.instance.wtTable.getLastVisibleRow()
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, fixedRowsTop = this.instance.getSetting('fixedRowsTop')
, fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
if (this.instance.getSetting('nativeScrollbars')) {
var TD = this.instance.wtTable.getCell(coords);
if (typeof TD === 'object') {
var offset = WalkontableDom.prototype.offset(TD);
var outerWidth = WalkontableDom.prototype.outerWidth(TD);
var outerHeight = WalkontableDom.prototype.outerHeight(TD);
var scrollX = this.instance.wtScrollbars.horizontal.getScrollPosition();
var scrollY = this.instance.wtScrollbars.vertical.getScrollPosition();
var clientWidth = WalkontableDom.prototype.outerWidth(this.instance.wtScrollbars.horizontal.scrollHandler);
var clientHeight = WalkontableDom.prototype.outerHeight(this.instance.wtScrollbars.vertical.scrollHandler);
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
offset.left = offset.left - WalkontableDom.prototype.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left;
}
if (this.instance.wtScrollbars.vertical.scrollHandler !== window) {
offset.top = offset.top - WalkontableDom.prototype.offset(this.instance.wtScrollbars.vertical.scrollHandler).top;
}
clientWidth -= 20;
clientHeight -= 20;
if (outerWidth < clientWidth) {
if (offset.left < scrollX) {
this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left);
}
else if (offset.left + outerWidth > scrollX + clientWidth) {
this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left - clientWidth + outerWidth);
}
}
if (outerHeight < clientHeight) {
if (offset.top < scrollY) {
this.instance.wtScrollbars.vertical.setScrollPosition(offset.top);
}
else if (offset.top + outerHeight > scrollY + clientHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(offset.top - clientHeight + outerHeight);
}
}
return;
}
}
if (coords[0] < 0 || coords[0] > totalRows - 1) {
throw new Error('row ' + coords[0] + ' does not exist');
}
else if (coords[1] < 0 || coords[1] > totalColumns - 1) {
throw new Error('column ' + coords[1] + ' does not exist');
}
if (coords[0] > lastVisibleRow) {
// this.scrollVertical(coords[0] - lastVisibleRow + 1);
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
this.instance.wtTable.verticalRenderReverse = true;
}
else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
// this.scrollVertical(coords[0] - lastVisibleRow + 1);
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
this.instance.wtTable.verticalRenderReverse = true;
}
else if (coords[0] - fixedRowsTop < offsetRow) {
this.scrollVertical(coords[0] - fixedRowsTop - offsetRow);
}
else {
this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed
}
if (this.instance.wtTable.isColumnBeforeViewport(coords[1])) {
//scroll left
this.instance.wtScrollbars.horizontal.scrollTo(coords[1] - fixedColumnsLeft);
}
else if (this.instance.wtTable.isColumnAfterViewport(coords[1]) || (this.instance.wtTable.getLastVisibleColumn() === coords[1] && !this.instance.wtTable.isLastColumnFullyVisible())) {
//scroll right
var sum = 0;
for (var i = 0; i < fixedColumnsLeft; i++) {
sum += this.instance.getSetting('columnWidth', i);
}
var scrollTo = coords[1];
sum += this.instance.getSetting('columnWidth', scrollTo);
var available = this.instance.wtViewport.getViewportWidth();
if (sum < available) {
var next = this.instance.getSetting('columnWidth', scrollTo - 1);
while (sum + next <= available && scrollTo >= fixedColumnsLeft) {
scrollTo--;
sum += next;
next = this.instance.getSetting('columnWidth', scrollTo - 1);
}
}
this.instance.wtScrollbars.horizontal.scrollTo(scrollTo - fixedColumnsLeft);
}
/*else {
//no scroll
}*/
return this.instance;
};
function WalkontableScrollbar() {
}
WalkontableScrollbar.prototype.init = function () {
var that = this;
//reference to instance
this.$table = $(this.instance.wtTable.TABLE);
//create elements
this.slider = document.createElement('DIV');
this.sliderStyle = this.slider.style;
this.sliderStyle.position = 'absolute';
this.sliderStyle.top = '0';
this.sliderStyle.left = '0';
this.sliderStyle.display = 'none';
this.slider.className = 'dragdealer ' + this.type;
this.handle = document.createElement('DIV');
this.handleStyle = this.handle.style;
this.handle.className = 'handle';
this.slider.appendChild(this.handle);
this.container = this.instance.wtTable.holder;
this.container.appendChild(this.slider);
var firstRun = true;
this.dragTimeout = null;
var dragDelta;
var dragRender = function () {
that.onScroll(dragDelta);
};
this.dragdealer = new Dragdealer(this.slider, {
vertical: (this.type === 'vertical'),
horizontal: (this.type === 'horizontal'),
slide: false,
speed: 100,
animationCallback: function (x, y) {
if (firstRun) {
firstRun = false;
return;
}
that.skipRefresh = true;
dragDelta = that.type === 'vertical' ? y : x;
if (that.dragTimeout === null) {
that.dragTimeout = setInterval(dragRender, 100);
dragRender();
}
},
callback: function (x, y) {
that.skipRefresh = false;
clearInterval(that.dragTimeout);
that.dragTimeout = null;
dragDelta = that.type === 'vertical' ? y : x;
that.onScroll(dragDelta);
}
});
this.skipRefresh = false;
};
WalkontableScrollbar.prototype.onScroll = function (delta) {
if (this.instance.drawn) {
this.readSettings();
if (this.total > this.visibleCount) {
var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize);
if (delta === 1) {
if (this.type === 'vertical') {
this.instance.scrollVertical(Infinity).draw();
}
else {
this.instance.scrollHorizontal(Infinity).draw();
}
}
else if (newOffset !== this.offset) { //is new offset different than old offset
if (this.type === 'vertical') {
this.instance.scrollVertical(newOffset - this.offset).draw();
}
else {
this.instance.scrollHorizontal(newOffset - this.offset).draw();
}
}
else {
this.refresh();
}
}
}
};
/**
* Returns what part of the scroller should the handle take
* @param viewportCount {Number} number of visible rows or columns
* @param totalCount {Number} total number of rows or columns
* @return {Number} 0..1
*/
WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) {
if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) {
return 1;
}
return 1 / totalCount;
};
WalkontableScrollbar.prototype.prepare = function () {
if (this.skipRefresh) {
return;
}
var ratio = this.getHandleSizeRatio(this.visibleCount, this.total);
if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') {
//isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0
this.visible = false;
}
else {
this.visible = true;
}
};
WalkontableScrollbar.prototype.refresh = function () {
if (this.skipRefresh) {
return;
}
else if (!this.visible) {
this.sliderStyle.display = 'none';
return;
}
var ratio
, sliderSize
, handleSize
, handlePosition
, visibleCount = this.visibleCount
, tableWidth = this.instance.wtViewport.getWorkspaceWidth()
, tableHeight = this.instance.wtViewport.getWorkspaceHeight();
if (tableWidth === Infinity) {
tableWidth = this.instance.wtViewport.getWorkspaceActualWidth();
}
if (tableHeight === Infinity) {
tableHeight = this.instance.wtViewport.getWorkspaceActualHeight();
}
if (this.type === 'vertical') {
if (this.instance.wtTable.rowStrategy.isLastIncomplete()) {
visibleCount--;
}
sliderSize = tableHeight - 2; //2 is sliders border-width
this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px';
this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width
this.sliderStyle.height = Math.max(sliderSize, 0) + 'px';
}
else { //horizontal
sliderSize = tableWidth - 2; //2 is sliders border-width
this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px';
this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width
this.sliderStyle.width = Math.max(sliderSize, 0) + 'px';
}
ratio = this.getHandleSizeRatio(visibleCount, this.total);
handleSize = Math.round(sliderSize * ratio);
if (handleSize < 10) {
handleSize = 15;
}
handlePosition = Math.floor(sliderSize * (this.offset / this.total));
if (handleSize + handlePosition > sliderSize) {
handlePosition = sliderSize - handleSize;
}
if (this.type === 'vertical') {
this.handleStyle.height = handleSize + 'px';
this.handleStyle.top = handlePosition + 'px';
}
else { //horizontal
this.handleStyle.width = handleSize + 'px';
this.handleStyle.left = handlePosition + 'px';
}
this.sliderStyle.display = 'block';
};
WalkontableScrollbar.prototype.destroy = function () {
clearInterval(this.dragdealer.interval);
};
///
var WalkontableVerticalScrollbar = function (instance) {
this.instance = instance;
this.type = 'vertical';
this.init();
};
WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar();
WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) {
this.instance.update('offsetRow', cell);
};
WalkontableVerticalScrollbar.prototype.readSettings = function () {
this.scrollMode = this.instance.getSetting('scrollV');
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
this.visibleCount = this.instance.wtTable.rowStrategy.countVisible();
if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) {
this.visibleCount--;
}
this.handlePosition = parseInt(this.handleStyle.top, 10);
this.sliderSize = parseInt(this.sliderStyle.height, 10);
this.fixedCount = this.instance.getSetting('fixedRowsTop');
};
///
var WalkontableHorizontalScrollbar = function (instance) {
this.instance = instance;
this.type = 'horizontal';
this.init();
};
WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar();
WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) {
this.instance.update('offsetColumn', cell);
};
WalkontableHorizontalScrollbar.prototype.readSettings = function () {
this.scrollMode = this.instance.getSetting('scrollH');
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
this.visibleCount = this.instance.wtTable.columnStrategy.countVisible();
if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) {
this.visibleCount--;
}
this.handlePosition = parseInt(this.handleStyle.left, 10);
this.sliderSize = parseInt(this.sliderStyle.width, 10);
this.fixedCount = this.instance.getSetting('fixedColumnsLeft');
};
WalkontableHorizontalScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) {
if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) {
return 1;
}
return viewportCount / totalCount;
};
function WalkontableCornerScrollbarNative(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('corner');
}
WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay();
WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
elem.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px';
elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
WalkontableCornerScrollbarNative.prototype.prepare = function () {
};
WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () {
};
WalkontableCornerScrollbarNative.prototype.getLastCell = function () {
};
WalkontableCornerScrollbarNative.prototype.applyToDOM = function () {
};
WalkontableCornerScrollbarNative.prototype.scrollTo = function () {
};
WalkontableCornerScrollbarNative.prototype.readWindowSize = function () {
};
WalkontableCornerScrollbarNative.prototype.readSettings = function () {
};
function WalkontableHorizontalScrollbarNative(instance) {
this.instance = instance;
this.type = 'horizontal';
this.cellSize = 50;
this.init();
this.clone = this.makeClone('left');
}
WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.vertical.scrollHandler === window) {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.top = Math.ceil(box.top, 10) + 'px';
overlayContainer.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 'px';
}
else {
this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px';
overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px'
}
overlayContainer.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow
};
WalkontableHorizontalScrollbarNative.prototype.prepare = function () {
};
WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () {
if (this.scrollHandler === window) {
return this.scrollHandler.scrollX;
}
else {
return this.scrollHandler.scrollLeft;
}
};
WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) {
this.scrollHandler.scrollLeft = pos;
};
WalkontableHorizontalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.apply(this, arguments);
this.instance.getSetting('onScrollHorizontally');
};
WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () {
return this.instance.wtTable.getLastVisibleColumn();
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
this.fixedContainer.style.paddingLeft = this.measureBefore + 'px';
this.fixedContainer.style.paddingRight = this.measureAfter + 'px';
};
WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) {
this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientWidth;
this.tableParentOffset = this.instance.wtTable.holderOffset.left;
}
else {
this.windowSize = WalkontableDom.prototype.outerWidth(this.scrollHandler);
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readSettings = function () {
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
};
function WalkontableVerticalScrollbarNative(instance) {
this.instance = instance;
this.type = 'vertical';
this.cellSize = 23;
this.init();
this.clone = this.makeClone('top');
}
WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
}
else {
box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
}
else {
elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
}
elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
var elem = this.clone.wtTable.holder.parentNode;
elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
}
};
WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
if (this.scrollHandler === window) {
return this.scrollHandler.scrollY;
}
else {
return this.scrollHandler.scrollTop;
}
};
WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
this.scrollHandler.scrollTop = pos;
};
WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) {
WalkontableOverlay.prototype.onScroll.apply(this, arguments);
var scrollDelta;
var newOffset = 0;
if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) {
scrollDelta = this.windowScrollPosition - this.tableParentOffset;
partialOffset = 0;
if (scrollDelta > 0) {
var sum = 0;
var last;
for (var i = 0; i < this.total; i++) {
last = this.instance.getSetting('rowHeight', i);
sum += last;
if (sum > scrollDelta) {
break;
}
}
if (this.offset > 0) {
partialOffset = (sum - scrollDelta);
}
newOffset = i;
newOffset = Math.min(newOffset, this.total);
}
}
this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset;
newOffset -= this.curOuts;
this.instance.update('offsetRow', newOffset);
this.readSettings(); //read new offset
this.instance.draw();
this.instance.getSetting('onScrollVertically');
};
WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};
var partialOffset = 0;
WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
var sum = 0;
while (from < length) {
sum += this.instance.getSetting('rowHeight', from);
from++;
}
return sum;
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
this.fixed.style.top = this.measureBefore + 'px';
this.fixed.style.bottom = '';
};
WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
var newY = this.tableParentOffset + cell * this.cellSize;
this.$scrollHandler.scrollTop(newY);
this.onScroll(newY);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientHeight;
this.tableParentOffset = this.instance.wtTable.holderOffset.top;
}
else {
//this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler);
this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
};
function WalkontableScrollbars(instance) {
this.instance = instance;
if (instance.getSetting('nativeScrollbars')) {
instance.update('scrollbarWidth', instance.wtDom.getScrollbarWidth());
instance.update('scrollbarHeight', instance.wtDom.getScrollbarWidth());
this.vertical = new WalkontableVerticalScrollbarNative(instance);
this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
this.corner = new WalkontableCornerScrollbarNative(instance);
if (instance.getSetting('debug')) {
this.debug = new WalkontableDebugOverlay(instance);
}
this.registerListeners();
}
else {
this.vertical = new WalkontableVerticalScrollbar(instance);
this.horizontal = new WalkontableHorizontalScrollbar(instance);
}
}
WalkontableScrollbars.prototype.registerListeners = function () {
var that = this;
var oldVerticalScrollPosition
, oldHorizontalScrollPosition
, oldBoxTop
, oldBoxLeft
, oldBoxWidth
, oldBoxHeight;
function refreshAll() {
if (!that.instance.wtTable.holder.parentNode) {
//Walkontable was detached from DOM, but this handler was not removed
that.destroy();
return;
}
that.vertical.windowScrollPosition = that.vertical.getScrollPosition();
that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition();
that.box = that.instance.wtTable.hider.getBoundingClientRect();
if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) {
//that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
oldBoxWidth = that.box.width;
oldBoxHeight = that.box.height;
that.instance.draw();
}
if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) {
that.vertical.onScroll();
that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles
that.vertical.react();
that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles
oldVerticalScrollPosition = that.vertical.windowScrollPosition;
oldHorizontalScrollPosition = that.horizontal.windowScrollPosition;
oldBoxTop = that.box.top;
oldBoxLeft = that.box.left;
}
}
var $window = $(window);
this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) {
this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
}
if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) {
$window.on('scroll.' + this.instance.guid, refreshAll);
}
$window.on('load.' + this.instance.guid, refreshAll);
$window.on('resize.' + this.instance.guid, refreshAll);
$(document).on('ready.' + this.instance.guid, refreshAll);
setInterval(refreshAll, 100); //Marcin - only idea I have to reposition scrollbars on CSS change of the container (container was moved using some styles after page was loaded)
};
WalkontableScrollbars.prototype.destroy = function () {
this.vertical && this.vertical.destroy();
this.horizontal && this.horizontal.destroy();
};
WalkontableScrollbars.prototype.refresh = function (selectionsOnly) {
this.horizontal && this.horizontal.readSettings();
this.vertical && this.vertical.readSettings();
this.horizontal && this.horizontal.prepare();
this.vertical && this.vertical.prepare();
this.horizontal && this.horizontal.refresh(selectionsOnly);
this.vertical && this.vertical.refresh(selectionsOnly);
this.corner && this.corner.refresh(selectionsOnly);
this.debug && this.debug.refresh(selectionsOnly);
};
function WalkontableSelection(instance, settings) {
this.instance = instance;
this.settings = settings;
this.selected = [];
if (settings.border) {
this.border = new WalkontableBorder(instance, settings);
}
}
WalkontableSelection.prototype.add = function (coords) {
this.selected.push(coords);
};
WalkontableSelection.prototype.clear = function () {
this.selected.length = 0; //http://jsperf.com/clear-arrayxxx
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @returns {Object}
*/
WalkontableSelection.prototype.getCorners = function () {
var minRow
, minColumn
, maxRow
, maxColumn
, i
, ilen = this.selected.length;
if (ilen > 0) {
minRow = maxRow = this.selected[0][0];
minColumn = maxColumn = this.selected[0][1];
if (ilen > 1) {
for (i = 1; i < ilen; i++) {
if (this.selected[i][0] < minRow) {
minRow = this.selected[i][0];
}
else if (this.selected[i][0] > maxRow) {
maxRow = this.selected[i][0];
}
if (this.selected[i][1] < minColumn) {
minColumn = this.selected[i][1];
}
else if (this.selected[i][1] > maxColumn) {
maxColumn = this.selected[i][1];
}
}
}
}
return [minRow, minColumn, maxRow, maxColumn];
};
WalkontableSelection.prototype.draw = function () {
var corners, r, c, source_r, source_c;
var visibleRows = this.instance.wtTable.rowStrategy.countVisible()
, visibleColumns = this.instance.wtTable.columnStrategy.countVisible();
if (this.selected.length) {
corners = this.getCorners();
for (r = 0; r < visibleRows; r++) {
for (c = 0; c < visibleColumns; c++) {
source_r = this.instance.wtTable.rowFilter.visibleToSource(r);
source_c = this.instance.wtTable.columnFilter.visibleToSource(c);
if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
//selected cell
this.instance.wtTable.currentCellCache.add(r, c, this.settings.className);
}
else if (source_r >= corners[0] && source_r <= corners[2]) {
//selection is in this row
this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
}
else if (source_c >= corners[1] && source_c <= corners[3]) {
//selection is in this column
this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
}
}
}
this.border && this.border.appear(corners); //warning! border.appear modifies corners!
}
else {
this.border && this.border.disappear();
}
};
function WalkontableSettings(instance, settings) {
var that = this;
this.instance = instance;
//default settings. void 0 means it is required, null means it can be empty
this.defaults = {
table: void 0,
debug: false, //shows WalkontableDebugOverlay
//presentation mode
scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar)
scrollV: 'auto', //values: see above
nativeScrollbars: false, //values: false (dragdealer), true (native)
stretchH: 'hybrid', //values: hybrid, all, last, none
currentRowClassName: null,
currentColumnClassName: null,
//data source
data: void 0,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: 0,
fixedRowsTop: 0,
rowHeaders: function () {
return []
}, //this must be array of functions: [function (row, TH) {}]
columnHeaders: function () {
return []
}, //this must be array of functions: [function (column, TH) {}]
totalRows: void 0,
totalColumns: void 0,
width: null,
height: null,
cellRenderer: function (row, column, TD) {
var cellData = that.getSetting('data', row, column);
that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData);
},
columnWidth: 50,
selections: null,
hideBorderOnMouseDownOver: false,
//callbacks
onCellMouseDown: null,
onCellMouseOver: null,
// onCellMouseOut: null,
onCellDblClick: null,
onCellCornerMouseDown: null,
onCellCornerDblClick: null,
beforeDraw: null,
onDraw: null,
onScrollVertically: null,
onScrollHorizontally: null,
//constants
scrollbarWidth: 10,
scrollbarHeight: 10
};
//reference to settings
this.settings = {};
for (var i in this.defaults) {
if (this.defaults.hasOwnProperty(i)) {
if (settings[i] !== void 0) {
this.settings[i] = settings[i];
}
else if (this.defaults[i] === void 0) {
throw new Error('A required setting "' + i + '" was not provided');
}
else {
this.settings[i] = this.defaults[i];
}
}
}
}
/**
* generic methods
*/
WalkontableSettings.prototype.update = function (settings, value) {
if (value === void 0) { //settings is object
for (var i in settings) {
if (settings.hasOwnProperty(i)) {
this.settings[i] = settings[i];
}
}
}
else { //if value is defined then settings is the key
this.settings[settings] = value;
}
return this.instance;
};
WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) {
if (this[key]) {
return this[key](param1, param2, param3);
}
else {
return this._getSetting(key, param1, param2, param3);
}
};
WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) {
if (typeof this.settings[key] === 'function') {
return this.settings[key](param1, param2, param3);
}
else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') {
return this.settings[key][param1];
}
else {
return this.settings[key];
}
};
WalkontableSettings.prototype.has = function (key) {
return !!this.settings[key]
};
/**
* specific methods
*/
WalkontableSettings.prototype.rowHeight = function (row, TD) {
if (!this.instance.rowHeightCache) {
this.instance.rowHeightCache = []; //hack. This cache is being invalidated in WOT core.js
}
if (this.instance.rowHeightCache[row] === void 0) {
var size = 23; //guess
if (TD) {
size = this.instance.wtDom.outerHeight(TD); //measure
this.instance.rowHeightCache[row] = size; //cache only something we measured
}
return size;
}
else {
return this.instance.rowHeightCache[row];
}
};
function WalkontableTable(instance, table) {
//reference to instance
this.instance = instance;
this.TABLE = table;
this.wtDom = this.instance.wtDom;
this.wtDom.removeTextNodes(this.TABLE);
//wtSpreader
var parent = this.TABLE.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var spreader = document.createElement('DIV');
spreader.className = 'wtSpreader';
if (parent) {
parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
spreader.appendChild(this.TABLE);
}
this.spreader = this.TABLE.parentNode;
//wtHider
parent = this.spreader.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var hider = document.createElement('DIV');
hider.className = 'wtHider';
if (parent) {
parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
hider.appendChild(this.spreader);
}
this.hider = this.spreader.parentNode;
this.hiderStyle = this.hider.style;
this.hiderStyle.position = 'relative';
//wtHolder
parent = this.hider.parentNode;
if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) {
var holder = document.createElement('DIV');
holder.style.position = 'relative';
holder.className = 'wtHolder';
if (parent) {
parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
holder.appendChild(this.hider);
}
this.holder = this.hider.parentNode;
//bootstrap from settings
this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0];
if (!this.TBODY) {
this.TBODY = document.createElement('TBODY');
this.TABLE.appendChild(this.TBODY);
}
this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0];
if (!this.THEAD) {
this.THEAD = document.createElement('THEAD');
this.TABLE.insertBefore(this.THEAD, this.TBODY);
}
this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0];
if (!this.COLGROUP) {
this.COLGROUP = document.createElement('COLGROUP');
this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
}
if (this.instance.getSetting('columnHeaders').length) {
if (!this.THEAD.childNodes.length) {
var TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
}
this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
this.tbodyChildrenLength = this.TBODY.childNodes.length;
this.oldCellCache = new WalkontableClassNameCache();
this.currentCellCache = new WalkontableClassNameCache();
this.rowFilter = new WalkontableRowFilter();
this.columnFilter = new WalkontableColumnFilter();
this.verticalRenderReverse = false;
}
WalkontableTable.prototype.refreshHiderDimensions = function () {
var height = this.instance.wtViewport.getWorkspaceHeight();
var width = this.instance.wtViewport.getWorkspaceWidth();
var spreaderStyle = this.spreader.style;
if ((height !== Infinity || width !== Infinity) && !this.instance.getSetting('nativeScrollbars')) {
if (height === Infinity) {
height = this.instance.wtViewport.getWorkspaceActualHeight();
}
if (width === Infinity) {
width = this.instance.wtViewport.getWorkspaceActualWidth();
}
this.hiderStyle.overflow = 'hidden';
spreaderStyle.position = 'absolute';
spreaderStyle.top = '0';
spreaderStyle.left = '0';
if (!this.instance.getSetting('nativeScrollbars')) {
spreaderStyle.height = '4000px';
spreaderStyle.width = '4000px';
}
if (height < 0) { //this happens with WalkontableOverlay and causes "Invalid argument" error in IE8
height = 0;
}
this.hiderStyle.height = height + 'px';
this.hiderStyle.width = width + 'px';
}
else {
spreaderStyle.position = 'relative';
spreaderStyle.width = 'auto';
spreaderStyle.height = 'auto';
}
};
WalkontableTable.prototype.refreshStretching = function () {
if (this.instance.cloneSource) {
return;
}
var instance = this.instance
, stretchH = instance.getSetting('stretchH')
, totalRows = instance.getSetting('totalRows')
, totalColumns = instance.getSetting('totalColumns')
, offsetColumn = instance.getSetting('offsetColumn');
var containerWidthFn = function (cacheWidth) {
var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth);
if (viewportWidth < cacheWidth && that.instance.getSetting('nativeScrollbars')) {
return Infinity; //disable stretching when viewport is bigger than sum of the cell widths
}
return viewportWidth;
};
var that = this;
var columnWidthFn = function (i) {
var source_c = that.columnFilter.visibleToSource(i);
if (source_c < totalColumns) {
return instance.getSetting('columnWidth', source_c);
}
};
if (stretchH === 'hybrid') {
if (offsetColumn > 0) {
stretchH = 'last';
}
else {
stretchH = 'none';
}
}
var containerHeightFn = function (cacheHeight) {
if (that.instance.getSetting('nativeScrollbars')) {
if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay) {
return Infinity;
}
else {
return 2 * that.instance.wtViewport.getViewportHeight(cacheHeight);
}
}
return that.instance.wtViewport.getViewportHeight(cacheHeight);
};
var rowHeightFn = function (i, TD) {
if (that.instance.getSetting('nativeScrollbars')) {
return 20;
}
var source_r = that.rowFilter.visibleToSource(i);
if (source_r < totalRows) {
if (that.verticalRenderReverse && i === 0) {
return that.instance.getSetting('rowHeight', source_r, TD) - 1;
}
else {
return that.instance.getSetting('rowHeight', source_r, TD);
}
}
};
this.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH);
this.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn);
};
WalkontableTable.prototype.adjustAvailableNodes = function () {
var displayTds
, rowHeaders = this.instance.getSetting('rowHeaders')
, displayThs = rowHeaders.length
, columnHeaders = this.instance.getSetting('columnHeaders')
, TR
, TD
, c;
//adjust COLGROUP
while (this.colgroupChildrenLength < displayThs) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.colgroupChildrenLength++;
}
this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug
if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
displayTds = this.instance.getSetting('fixedColumnsLeft');
}
else {
displayTds = this.columnStrategy.cellCount;
}
//adjust COLGROUP
while (this.colgroupChildrenLength < displayTds + displayThs) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.colgroupChildrenLength++;
}
while (this.colgroupChildrenLength > displayTds + displayThs) {
this.COLGROUP.removeChild(this.COLGROUP.lastChild);
this.colgroupChildrenLength--;
}
//adjust THEAD
TR = this.THEAD.firstChild;
if (columnHeaders.length) {
if (!TR) {
TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
this.theadChildrenLength = TR.childNodes.length;
while (this.theadChildrenLength < displayTds + displayThs) {
TR.appendChild(document.createElement('TH'));
this.theadChildrenLength++;
}
while (this.theadChildrenLength > displayTds + displayThs) {
TR.removeChild(TR.lastChild);
this.theadChildrenLength--;
}
}
else if (TR) {
this.wtDom.empty(TR);
}
//draw COLGROUP
for (c = 0; c < this.colgroupChildrenLength; c++) {
if (c < displayThs) {
this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader');
}
else {
this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader');
}
}
//draw THEAD
if (columnHeaders.length) {
TR = this.THEAD.firstChild;
if (displayThs) {
TD = TR.firstChild; //actually it is TH but let's reuse single variable
for (c = 0; c < displayThs; c++) {
rowHeaders[c](-displayThs + c, TD);
TD = TD.nextSibling;
}
}
}
for (c = 0; c < displayTds; c++) {
if (columnHeaders.length) {
columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]);
}
}
};
WalkontableTable.prototype.adjustColumns = function (TR, desiredCount) {
var count = TR.childNodes.length;
while (count < desiredCount) {
var TD = document.createElement('TD');
TR.appendChild(TD);
count++;
}
while (count > desiredCount) {
TR.removeChild(TR.lastChild);
count--;
}
};
WalkontableTable.prototype.draw = function (selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
this.verticalRenderReverse = false; //this is only supported in dragdealer mode, not in native
}
this.rowFilter.readSettings(this.instance);
this.columnFilter.readSettings(this.instance);
if (!selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
if (this.instance.cloneSource) {
this.tableOffset = this.instance.cloneSource.wtTable.tableOffset;
}
else {
this.holderOffset = this.wtDom.offset(this.holder);
this.tableOffset = this.wtDom.offset(this.TABLE);
this.instance.wtScrollbars.vertical.readWindowSize();
this.instance.wtScrollbars.horizontal.readWindowSize();
this.instance.wtViewport.resetSettings();
}
}
else {
this.tableOffset = this.wtDom.offset(this.TABLE);
this.instance.wtViewport.resetSettings();
}
this._doDraw();
}
else {
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true);
}
this.refreshPositions(selectionsOnly);
if (!selectionsOnly) {
if (this.instance.getSetting('nativeScrollbars')) {
if (!this.instance.cloneSource) {
this.instance.wtScrollbars.vertical.resetFixedPosition();
this.instance.wtScrollbars.horizontal.resetFixedPosition();
this.instance.wtScrollbars.corner.resetFixedPosition();
this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition();
}
}
}
this.instance.drawn = true;
return this;
};
WalkontableTable.prototype._doDraw = function () {
var r = 0
, source_r
, c
, source_c
, offsetRow = this.instance.getSetting('offsetRow')
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, displayTds
, rowHeaders = this.instance.getSetting('rowHeaders')
, displayThs = rowHeaders.length
, TR
, TD
, TH
, adjusted = false
, workspaceWidth
, mustBeInViewport
, res;
if (this.verticalRenderReverse) {
mustBeInViewport = offsetRow;
}
var noPartial = false;
if (this.verticalRenderReverse) {
if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) {
noPartial = true;
}
else {
this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse
this.rowFilter.readSettings(this.instance);
}
}
if (this.instance.cloneSource) {
this.columnStrategy = this.instance.cloneSource.wtTable.columnStrategy;
this.rowStrategy = this.instance.cloneSource.wtTable.rowStrategy;
}
//draw TBODY
if (totalColumns > 0) {
source_r = this.rowFilter.visibleToSource(r);
var fixedRowsTop = this.instance.getSetting('fixedRowsTop');
var cloneLimit;
if (this.instance.cloneSource) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined
if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
cloneLimit = fixedRowsTop;
}
else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) {
cloneLimit = this.rowStrategy.countVisible();
}
//else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows
}
this.adjustAvailableNodes();
adjusted = true;
if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
displayTds = this.instance.getSetting('fixedColumnsLeft');
}
else {
displayTds = this.columnStrategy.cellCount;
}
if (!this.instance.cloneSource) {
workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
this.columnStrategy.stretch();
}
for (c = 0; c < displayTds; c++) {
this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
}
while (source_r < totalRows && source_r >= 0) {
if (r > 1000) {
throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.');
}
if (cloneLimit !== void 0 && r === cloneLimit) {
break; //we have as much rows as needed for this clone
}
if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) {
TR = document.createElement('TR');
for (c = 0; c < displayThs; c++) {
TR.appendChild(document.createElement('TH'));
}
if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild);
}
else {
this.TBODY.appendChild(TR);
}
this.tbodyChildrenLength++;
}
else if (r === 0) {
TR = this.TBODY.firstChild;
}
else {
TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//TH
TH = TR.firstChild;
for (c = 0; c < displayThs; c++) {
//If the number of row headers increased we need to replace TD with TH
if (TH.nodeName == 'TD') {
TD = TH;
TH = document.createElement('TH');
TR.insertBefore(TH, TD);
TR.removeChild(TD);
}
rowHeaders[c](source_r, TH); //actually TH
TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
this.adjustColumns(TR, displayTds + displayThs);
for (c = 0; c < displayTds; c++) {
source_c = this.columnFilter.visibleToSource(c);
if (c === 0) {
TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)];
}
else {
TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//If the number of headers has been reduced, we need to replace excess TH with TD
if (TD.nodeName == 'TH') {
TH = TD;
TD = document.createElement('TD');
TR.insertBefore(TD, TH);
TR.removeChild(TH);
}
TD.className = '';
TD.removeAttribute('style');
this.instance.getSetting('cellRenderer', source_r, source_c, TD);
}
offsetRow = this.instance.getSetting('offsetRow'); //refresh the value
//after last column is rendered, check if last cell is fully displayed
if (this.verticalRenderReverse && noPartial) {
if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) {
this.TBODY.removeChild(TR);
this.instance.update('offsetRow', offsetRow + 1);
this.tbodyChildrenLength--;
this.rowFilter.readSettings(this.instance);
break;
}
else if (!this.instance.cloneSource) {
res = this.rowStrategy.add(r, TD, this.verticalRenderReverse);
if (res === false) {
this.rowStrategy.removeOutstanding();
}
}
}
else if (!this.instance.cloneSource) {
res = this.rowStrategy.add(r, TD, this.verticalRenderReverse);
if (res === false) {
if (!this.instance.getSetting('nativeScrollbars')) {
this.rowStrategy.removeOutstanding();
}
}
if (this.rowStrategy.isLastIncomplete()) {
if (this.verticalRenderReverse && !this.isRowInViewport(mustBeInViewport)) {
//we failed because one of the cells was by far too large. Recover by rendering from top
this.verticalRenderReverse = false;
this.instance.update('offsetRow', mustBeInViewport);
this.draw();
return;
}
break;
}
}
if (this.instance.getSetting('nativeScrollbars')) {
if (this.instance.cloneSource) {
TR.style.height = this.instance.getSetting('rowHeight', source_r) + 'px'; //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height
}
else {
this.instance.getSetting('rowHeight', source_r, TD); //this trick saves rowHeight in rowHeightCache. It is then read in WalkontableVerticalScrollbarNative.prototype.sumCellSizes and reset in Walkontable constructor
}
}
if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) {
if (offsetRow === 0) {
break;
}
this.instance.update('offsetRow', offsetRow - 1);
this.rowFilter.readSettings(this.instance);
}
else {
r++;
}
source_r = this.rowFilter.visibleToSource(r);
}
}
if (!adjusted) {
this.adjustAvailableNodes();
}
if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) {
r = this.rowStrategy.countVisible();
while (this.tbodyChildrenLength > r) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.tbodyChildrenLength--;
}
}
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(false);
if (!this.instance.cloneSource) {
if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) {
//workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
this.columnStrategy.stretch();
for (c = 0; c < this.columnStrategy.cellCount; c++) {
this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px';
}
}
}
this.verticalRenderReverse = false;
};
WalkontableTable.prototype.refreshPositions = function (selectionsOnly) {
this.refreshHiderDimensions();
this.refreshSelections(selectionsOnly);
};
WalkontableTable.prototype.refreshSelections = function (selectionsOnly) {
var vr
, r
, vc
, c
, s
, slen
, classNames = []
, visibleRows = this.rowStrategy.countVisible()
, visibleColumns = this.columnStrategy.countVisible();
this.oldCellCache = this.currentCellCache;
this.currentCellCache = new WalkontableClassNameCache();
if (this.instance.selections) {
for (r in this.instance.selections) {
if (this.instance.selections.hasOwnProperty(r)) {
this.instance.selections[r].draw();
if (this.instance.selections[r].settings.className) {
classNames.push(this.instance.selections[r].settings.className);
}
if (this.instance.selections[r].settings.highlightRowClassName) {
classNames.push(this.instance.selections[r].settings.highlightRowClassName);
}
if (this.instance.selections[r].settings.highlightColumnClassName) {
classNames.push(this.instance.selections[r].settings.highlightColumnClassName);
}
}
}
}
slen = classNames.length;
for (vr = 0; vr < visibleRows; vr++) {
for (vc = 0; vc < visibleColumns; vc++) {
r = this.rowFilter.visibleToSource(vr);
c = this.columnFilter.visibleToSource(vc);
for (s = 0; s < slen; s++) {
if (this.currentCellCache.test(vr, vc, classNames[s])) {
this.wtDom.addClass(this.getCell([r, c]), classNames[s]);
}
else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) {
this.wtDom.removeClass(this.getCell([r, c]), classNames[s]);
}
}
}
}
};
/**
* getCell
* @param {Array} coords
* @return {Object} HTMLElement on success or {Number} one of the exit codes on error:
* -1 row before viewport
* -2 row after viewport
* -3 column before viewport
* -4 column after viewport
*
*/
WalkontableTable.prototype.getCell = function (coords) {
if (this.isRowBeforeViewport(coords[0])) {
return -1; //row before viewport
}
else if (this.isRowAfterViewport(coords[0])) {
return -2; //row after viewport
}
else {
if (this.isColumnBeforeViewport(coords[1])) {
return -3; //column before viewport
}
else if (this.isColumnAfterViewport(coords[1])) {
return -4; //column after viewport
}
else {
return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])];
}
}
};
WalkontableTable.prototype.getCoords = function (TD) {
return [
this.rowFilter.visibleToSource(this.wtDom.index(TD.parentNode)),
this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)
];
};
//returns -1 if no row is visible
WalkontableTable.prototype.getLastVisibleRow = function () {
return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1);
};
//returns -1 if no column is visible
WalkontableTable.prototype.getLastVisibleColumn = function () {
return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1);
};
WalkontableTable.prototype.isRowBeforeViewport = function (r) {
return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount);
};
WalkontableTable.prototype.isRowAfterViewport = function (r) {
return (r > this.getLastVisibleRow());
};
WalkontableTable.prototype.isColumnBeforeViewport = function (c) {
return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount);
};
WalkontableTable.prototype.isColumnAfterViewport = function (c) {
return (c > this.getLastVisibleColumn());
};
WalkontableTable.prototype.isRowInViewport = function (r) {
return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r));
};
WalkontableTable.prototype.isColumnInViewport = function (c) {
return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c));
};
WalkontableTable.prototype.isLastRowFullyVisible = function () {
return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete());
};
WalkontableTable.prototype.isLastColumnFullyVisible = function () {
return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete());
};
function WalkontableViewport(instance) {
this.instance = instance;
this.resetSettings();
if (this.instance.getSetting('nativeScrollbars')) {
var that = this;
$(window).on('resize', function () {
that.clientHeight = that.getWorkspaceHeight();
});
}
}
/*WalkontableViewport.prototype.isInSightVertical = function () {
//is table outside viewport bottom edge
if (tableTop > windowHeight + scrollTop) {
return -1;
}
//is table outside viewport top edge
else if (scrollTop > tableTop + tableFakeHeight) {
return -2;
}
//table is in viewport but how much exactly?
else {
}
};*/
//used by scrollbar
WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) {
if (this.instance.getSetting('nativeScrollbars')) {
return this.instance.wtScrollbars.vertical.windowSize;
}
var height = this.instance.getSetting('height');
if (height === Infinity || height === void 0 || height === null || height < 1) {
if (this.instance.wtScrollbars.vertical instanceof WalkontableOverlay) {
height = this.instance.wtScrollbars.vertical.availableSize();
}
else {
height = Infinity;
}
}
if (height !== Infinity) {
if (proposedHeight >= height) {
height -= this.instance.getSetting('scrollbarHeight');
}
else if (this.instance.wtScrollbars.horizontal.visible) {
height -= this.instance.getSetting('scrollbarHeight');
}
}
return height;
};
WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) {
var width = this.instance.getSetting('width');
if (width === Infinity || width === void 0 || width === null || width < 1) {
if (this.instance.wtScrollbars.horizontal instanceof WalkontableOverlay) {
width = this.instance.wtScrollbars.horizontal.availableSize();
}
else {
width = Infinity;
}
}
if (width !== Infinity) {
if (proposedWidth >= width) {
width -= this.instance.getSetting('scrollbarWidth');
}
else if (this.instance.wtScrollbars.vertical.visible) {
width -= this.instance.getSetting('scrollbarWidth');
}
}
return width;
};
WalkontableViewport.prototype.getWorkspaceActualHeight = function () {
return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualWidth = function () {
return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth;
};
WalkontableViewport.prototype.getColumnHeaderHeight = function () {
if (isNaN(this.columnHeaderHeight)) {
var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY)
, tableOffset = this.instance.wtTable.tableOffset;
this.columnHeaderHeight = cellOffset.top - tableOffset.top;
}
return this.columnHeaderHeight;
};
WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) {
var containerHeight = this.getWorkspaceHeight(proposedHeight);
if (containerHeight === Infinity) {
return containerHeight;
}
var columnHeaderHeight = this.getColumnHeaderHeight();
if (columnHeaderHeight > 0) {
return containerHeight - columnHeaderHeight;
}
else {
return containerHeight;
}
};
WalkontableViewport.prototype.getRowHeaderWidth = function () {
if (this.instance.cloneSource) {
return this.instance.cloneSource.wtViewport.getRowHeaderWidth();
}
if (isNaN(this.rowHeaderWidth)) {
var rowHeaders = this.instance.getSetting('rowHeaders');
if (rowHeaders.length) {
var TH = this.instance.wtTable.TABLE.querySelector('TH');
this.rowHeaderWidth = 0;
for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) {
if (TH) {
this.rowHeaderWidth += this.instance.wtDom.outerWidth(TH);
TH = TH.nextSibling;
}
else {
this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix
}
}
}
else {
this.rowHeaderWidth = 0;
}
}
return this.rowHeaderWidth;
};
WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) {
var containerWidth = this.getWorkspaceWidth(proposedWidth);
if (containerWidth === Infinity) {
return containerWidth;
}
var rowHeaderWidth = this.getRowHeaderWidth();
if (rowHeaderWidth > 0) {
return containerWidth - rowHeaderWidth;
}
else {
return containerWidth;
}
};
WalkontableViewport.prototype.resetSettings = function () {
this.rowHeaderWidth = NaN;
this.columnHeaderHeight = NaN;
};
function WalkontableWheel(instance) {
if (instance.getSetting('nativeScrollbars')) {
return;
}
//spreader === instance.wtTable.TABLE.parentNode
$(instance.wtTable.spreader).on('mousewheel', function (event, delta, deltaX, deltaY) {
if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53
deltaY = delta;
}
if (!deltaX && !deltaY) { //this happens in IE8 test case
return;
}
if (deltaY > 0 && instance.getSetting('offsetRow') === 0) {
return; //attempt to scroll up when it's already showing first row
}
else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) {
return; //attempt to scroll down when it's already showing last row
}
else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) {
return; //attempt to scroll left when it's already showing first column
}
else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) {
return; //attempt to scroll right when it's already showing last column
}
//now we are sure we really want to scroll
clearTimeout(instance.wheelTimeout);
instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second
if (deltaY) {
//ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll
//see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers
if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar
instance.scrollVertical(-Math.ceil(deltaY)).draw();
}
}
else if (deltaX) {
if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar
instance.scrollHorizontal(Math.ceil(deltaX)).draw();
}
}
}, 0);
event.preventDefault();
});
}
/**
* Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340
* http://code.ovidiu.ch/dragdealer-js
*
* Copyright (c) 2010, Ovidiu Chereches
* MIT License
* http://legal.ovidiu.ch/licenses/MIT
*/
/* Cursor */
var Cursor =
{
x: 0, y: 0,
init: function()
{
this.setEvent('mouse');
this.setEvent('touch');
},
setEvent: function(type)
{
var moveHandler = document['on' + type + 'move'] || function(){};
document['on' + type + 'move'] = function(e)
{
moveHandler(e);
Cursor.refresh(e);
}
},
refresh: function(e)
{
if(!e)
{
e = window.event;
}
if(e.type == 'mousemove')
{
this.set(e);
}
else if(e.touches)
{
this.set(e.touches[0]);
}
},
set: function(e)
{
if(e.pageX || e.pageY)
{
this.x = e.pageX;
this.y = e.pageY;
}
else if(document.body && (e.clientX || e.clientY)) //need to check whether body exists, because of IE8 issue (#1084)
{
this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
}
};
Cursor.init();
/* Position */
var Position =
{
get: function(obj)
{
var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope
if(obj.offsetParent)
{
do
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
while((obj = obj.offsetParent));
}
return [curleft, curtop];
}
};
/* Dragdealer */
var Dragdealer = function(wrapper, options)
{
if(typeof(wrapper) == 'string')
{
wrapper = document.getElementById(wrapper);
}
if(!wrapper)
{
return;
}
var handle = wrapper.getElementsByTagName('div')[0];
if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1)
{
return;
}
this.init(wrapper, handle, options || {});
this.setup();
};
Dragdealer.prototype =
{
init: function(wrapper, handle, options)
{
this.wrapper = wrapper;
this.handle = handle;
this.options = options;
this.disabled = this.getOption('disabled', false);
this.horizontal = this.getOption('horizontal', true);
this.vertical = this.getOption('vertical', false);
this.slide = this.getOption('slide', true);
this.steps = this.getOption('steps', 0);
this.snap = this.getOption('snap', false);
this.loose = this.getOption('loose', false);
this.speed = this.getOption('speed', 10) / 100;
this.xPrecision = this.getOption('xPrecision', 0);
this.yPrecision = this.getOption('yPrecision', 0);
this.callback = options.callback || null;
this.animationCallback = options.animationCallback || null;
this.bounds = {
left: options.left || 0, right: -(options.right || 0),
top: options.top || 0, bottom: -(options.bottom || 0),
x0: 0, x1: 0, xRange: 0,
y0: 0, y1: 0, yRange: 0
};
this.value = {
prev: [-1, -1],
current: [options.x || 0, options.y || 0],
target: [options.x || 0, options.y || 0]
};
this.offset = {
wrapper: [0, 0],
mouse: [0, 0],
prev: [-999999, -999999],
current: [0, 0],
target: [0, 0]
};
this.change = [0, 0];
this.activity = false;
this.dragging = false;
this.tapping = false;
},
getOption: function(name, defaultValue)
{
return this.options[name] !== undefined ? this.options[name] : defaultValue;
},
setup: function()
{
this.setWrapperOffset();
this.setBoundsPadding();
this.setBounds();
this.setSteps();
this.addListeners();
},
setWrapperOffset: function()
{
this.offset.wrapper = Position.get(this.wrapper);
},
setBoundsPadding: function()
{
if(!this.bounds.left && !this.bounds.right)
{
this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0];
this.bounds.right = -this.bounds.left;
}
if(!this.bounds.top && !this.bounds.bottom)
{
this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1];
this.bounds.bottom = -this.bounds.top;
}
},
setBounds: function()
{
this.bounds.x0 = this.bounds.left;
this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right;
this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth;
this.bounds.y0 = this.bounds.top;
this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom;
this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight;
this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth));
this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight));
},
setSteps: function()
{
if(this.steps > 1)
{
this.stepRatios = [];
for(var i = 0; i <= this.steps - 1; i++)
{
this.stepRatios[i] = i / (this.steps - 1);
}
}
},
addListeners: function()
{
var self = this;
this.wrapper.onselectstart = function()
{
return false;
}
this.handle.onmousedown = this.handle.ontouchstart = function(e)
{
self.handleDownHandler(e);
};
this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e)
{
self.wrapperDownHandler(e);
};
var mouseUpHandler = document.onmouseup || function(){};
document.onmouseup = function(e)
{
mouseUpHandler(e);
self.documentUpHandler(e);
};
var touchEndHandler = document.ontouchend || function(){};
document.ontouchend = function(e)
{
touchEndHandler(e);
self.documentUpHandler(e);
};
var resizeHandler = window.onresize || function(){};
window.onresize = function(e)
{
resizeHandler(e);
self.documentResizeHandler(e);
};
this.wrapper.onmousemove = function(e)
{
self.activity = true;
}
this.wrapper.onclick = function(e)
{
return !self.activity;
}
this.interval = setInterval(function(){ self.animate() }, 25);
self.animate(false, true);
},
handleDownHandler: function(e)
{
this.activity = false;
Cursor.refresh(e);
this.preventDefaults(e, true);
this.startDrag();
},
wrapperDownHandler: function(e)
{
Cursor.refresh(e);
this.preventDefaults(e, true);
this.startTap();
},
documentUpHandler: function(e)
{
this.stopDrag();
this.stopTap();
},
documentResizeHandler: function(e)
{
this.setWrapperOffset();
this.setBounds();
this.update();
},
enable: function()
{
this.disabled = false;
this.handle.className = this.handle.className.replace(/\s?disabled/g, '');
},
disable: function()
{
this.disabled = true;
this.handle.className += ' disabled';
},
setStep: function(x, y, snap)
{
this.setValue(
this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0,
this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0,
snap
);
},
setValue: function(x, y, snap)
{
this.setTargetValue([x, y || 0]);
if(snap)
{
this.groupCopy(this.value.current, this.value.target);
}
},
startTap: function(target)
{
if(this.disabled)
{
return;
}
this.tapping = true;
this.setWrapperOffset();
this.setBounds();
if(target === undefined)
{
target = [
Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2),
Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2)
];
}
this.setTargetOffset(target);
},
stopTap: function()
{
if(this.disabled || !this.tapping)
{
return;
}
this.tapping = false;
this.setTargetValue(this.value.current);
this.result();
},
startDrag: function()
{
if(this.disabled)
{
return;
}
this.setWrapperOffset();
this.setBounds();
this.offset.mouse = [
Cursor.x - Position.get(this.handle)[0],
Cursor.y - Position.get(this.handle)[1]
];
this.dragging = true;
},
stopDrag: function()
{
if(this.disabled || !this.dragging)
{
return;
}
this.dragging = false;
var target = this.groupClone(this.value.current);
if(this.slide)
{
var ratioChange = this.change;
target[0] += ratioChange[0] * 4;
target[1] += ratioChange[1] * 4;
}
this.setTargetValue(target);
this.result();
},
feedback: function()
{
var value = this.value.current;
if(this.snap && this.steps > 1)
{
value = this.getClosestSteps(value);
}
if(!this.groupCompare(value, this.value.prev))
{
if(typeof(this.animationCallback) == 'function')
{
this.animationCallback(value[0], value[1]);
}
this.groupCopy(this.value.prev, value);
}
},
result: function()
{
if(typeof(this.callback) == 'function')
{
this.callback(this.value.target[0], this.value.target[1]);
}
},
animate: function(direct, first)
{
if(direct && !this.dragging)
{
return;
}
if(this.dragging)
{
var prevTarget = this.groupClone(this.value.target);
var offset = [
Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0],
Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1]
];
this.setTargetOffset(offset, this.loose);
this.change = [
this.value.target[0] - prevTarget[0],
this.value.target[1] - prevTarget[1]
];
}
if(this.dragging || first)
{
this.groupCopy(this.value.current, this.value.target);
}
if(this.dragging || this.glide() || first)
{
this.update();
this.feedback();
}
},
glide: function()
{
var diff = [
this.value.target[0] - this.value.current[0],
this.value.target[1] - this.value.current[1]
];
if(!diff[0] && !diff[1])
{
return false;
}
if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep)
{
this.value.current[0] += diff[0] * this.speed;
this.value.current[1] += diff[1] * this.speed;
}
else
{
this.groupCopy(this.value.current, this.value.target);
}
return true;
},
update: function()
{
if(!this.snap)
{
this.offset.current = this.getOffsetsByRatios(this.value.current);
}
else
{
this.offset.current = this.getOffsetsByRatios(
this.getClosestSteps(this.value.current)
);
}
this.show();
},
show: function()
{
if(!this.groupCompare(this.offset.current, this.offset.prev))
{
if(this.horizontal)
{
this.handle.style.left = String(this.offset.current[0]) + 'px';
}
if(this.vertical)
{
this.handle.style.top = String(this.offset.current[1]) + 'px';
}
this.groupCopy(this.offset.prev, this.offset.current);
}
},
setTargetValue: function(value, loose)
{
var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
this.groupCopy(this.value.target, target);
this.offset.target = this.getOffsetsByRatios(target);
},
setTargetOffset: function(offset, loose)
{
var value = this.getRatiosByOffsets(offset);
var target = loose ? this.getLooseValue(value) : this.getProperValue(value);
this.groupCopy(this.value.target, target);
this.offset.target = this.getOffsetsByRatios(target);
},
getLooseValue: function(value)
{
var proper = this.getProperValue(value);
return [
proper[0] + ((value[0] - proper[0]) / 4),
proper[1] + ((value[1] - proper[1]) / 4)
];
},
getProperValue: function(value)
{
var proper = this.groupClone(value);
proper[0] = Math.max(proper[0], 0);
proper[1] = Math.max(proper[1], 0);
proper[0] = Math.min(proper[0], 1);
proper[1] = Math.min(proper[1], 1);
if((!this.dragging && !this.tapping) || this.snap)
{
if(this.steps > 1)
{
proper = this.getClosestSteps(proper);
}
}
return proper;
},
getRatiosByOffsets: function(group)
{
return [
this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0),
this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0)
];
},
getRatioByOffset: function(offset, range, padding)
{
return range ? (offset - padding) / range : 0;
},
getOffsetsByRatios: function(group)
{
return [
this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0),
this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0)
];
},
getOffsetByRatio: function(ratio, range, padding)
{
return Math.round(ratio * range) + padding;
},
getClosestSteps: function(group)
{
return [
this.getClosestStep(group[0]),
this.getClosestStep(group[1])
];
},
getClosestStep: function(value)
{
var k = 0;
var min = 1;
for(var i = 0; i <= this.steps - 1; i++)
{
if(Math.abs(this.stepRatios[i] - value) < min)
{
min = Math.abs(this.stepRatios[i] - value);
k = i;
}
}
return this.stepRatios[k];
},
groupCompare: function(a, b)
{
return a[0] == b[0] && a[1] == b[1];
},
groupCopy: function(a, b)
{
a[0] = b[0];
a[1] = b[1];
},
groupClone: function(a)
{
return [a[0], a[1]];
},
preventDefaults: function(e, selection)
{
if(!e)
{
e = window.event;
}
if(e.preventDefault)
{
e.preventDefault();
}
e.returnValue = false;
if(selection && document.selection)
{
document.selection.empty();
}
},
cancelEvent: function(e)
{
if(!e)
{
e = window.event;
}
if(e.stopPropagation)
{
e.stopPropagation();
}
e.cancelBubble = true;
}
};
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.3
*
* Requires: 1.2.2+
*/
(function (factory) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS style for Browserify
module.exports = factory;
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
var lowestDelta, lowestDeltaXY;
if ( $.event.fixHooks ) {
for ( var i = toFix.length; i; ) {
$.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i = toBind.length; i; ) {
this.addEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i = toBind.length; i; ) {
this.removeEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event,
args = [].slice.call(arguments, 1),
delta = 0,
deltaX = 0,
deltaY = 0,
absDelta = 0,
absDeltaXY = 0,
fn;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
// New school wheel delta (wheel event)
if ( orgEvent.deltaY ) {
deltaY = orgEvent.deltaY * -1;
delta = deltaY;
}
if ( orgEvent.deltaX ) {
deltaX = orgEvent.deltaX;
delta = deltaX * -1;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }
// Look for lowest delta to normalize the delta values
absDelta = Math.abs(delta);
if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
// Get a whole value for the deltas
fn = delta > 0 ? 'floor' : 'ceil';
delta = Math[fn](delta / lowestDelta);
deltaX = Math[fn](deltaX / lowestDeltaXY);
deltaY = Math[fn](deltaY / lowestDeltaXY);
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
}));
})(jQuery, window, Handsontable);
|
eis4vn/eis4vn.github.io
|
src/handsontable/jquery.handsontable.js
|
JavaScript
|
gpl-3.0
| 421,284
|
///////////////////////////////////////////////////////////////////////////////
/// \file complex.hpp
///
// Copyright 2005 Eric Niebler. 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 BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
#define BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
# error Include this file before boost/accumulators/numeric/functional.hpp
#endif
#include <complex>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/typeof/std/complex.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
namespace boost { namespace numeric { namespace operators
{
// So that the stats compile when Sample type is std::complex
template<typename T, typename U>
typename
disable_if<
mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
, std::complex<T>
>::type
operator *(std::complex<T> ri, U const &u)
{
// BUGBUG promote result to typeof(T()*u) ?
return ri *= static_cast<T>(u);
}
template<typename T, typename U>
typename
disable_if<
mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
, std::complex<T>
>::type
operator /(std::complex<T> ri, U const &u)
{
// BUGBUG promote result to typeof(T()*u) ?
return ri /= static_cast<T>(u);
}
}}} // namespace boost::numeric::operators
namespace boost { namespace numeric
{
namespace detail
{
template<typename T>
struct one_complex
{
static std::complex<T> const value;
};
template<typename T>
std::complex<T> const one_complex<T>::value
= std::complex<T>(numeric::one<T>::value, numeric::one<T>::value);
}
/// INTERNAL ONLY
///
template<typename T>
struct one<std::complex<T> >
: detail::one_complex<T>
{
typedef one type;
typedef std::complex<T> value_type;
operator value_type const & () const
{
return detail::one_complex<T>::value;
}
};
}} // namespace boost::numeric
#endif
|
hpl1nk/nonamegame
|
xray/SDK/include/boost/accumulators/numeric/functional/complex.hpp
|
C++
|
gpl-3.0
| 2,316
|
/*
* # Semantic UI
* https://github.com/Semantic-Org/Semantic-UI
* http://www.semantic-ui.com/
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*******************************
Standard
*******************************/
/*--------------
Menu
---------------*/
.ui.menu {
margin: 1rem 0rem;
background: #ffffff;
font-size: 0px;
font-weight: normal;
box-shadow: 0px 0px 0px 1px rgba(39, 41, 43, 0.15), 0px 1px 2px 0 rgba(0, 0, 0, 0.05);
border-radius: 0.2857rem;
}
.ui.menu:after {
content: '';
display: block;
height: 0px;
clear: both;
visibility: hidden;
}
.ui.menu:first-child {
margin-top: 0rem;
}
.ui.menu:last-child {
margin-bottom: 0rem;
}
/*--------------
Colors
---------------*/
/* Text Color */
.ui.menu .item {
color: rgba(0, 0, 0, 0.8);
}
.ui.menu .item .item {
color: rgba(0, 0, 0, 0.5);
}
/* Hover */
.ui.menu .item .menu a.item:hover,
.ui.menu .item .menu .link.item:hover {
color: rgba(0, 0, 0, 0.85);
}
/*--------------
Items
---------------*/
.ui.menu .item {
position: relative;
display: inline-block;
padding: 0.78571em 0.95em;
border-top: 0em solid transparent;
background: none;
vertical-align: middle;
line-height: 1;
text-decoration: none;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-transition: opacity 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;
transition: opacity 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;
}
.ui.menu .menu {
margin: 0em;
}
/* Floated Content */
.ui.menu > .item:first-child {
border-radius: 0.2857rem 0px 0px 0.2857rem;
}
.ui.menu:not(.vertical) .item.left,
.ui.menu:not(.vertical) .menu.left {
float: left;
}
.ui.menu:not(.vertical) .item.right,
.ui.menu:not(.vertical) .menu.right {
float: right;
}
/*--------------
Borders
---------------*/
.ui.menu .item:before {
position: absolute;
content: '';
top: 0%;
right: 0px;
width: 1px;
height: 100%;
background: -webkit-linear-gradient(rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.1) 50%, rgba(0, 0, 0, 0.05) 100%);
background: linear-gradient(rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.1) 50%, rgba(0, 0, 0, 0.05) 100%);
}
.ui.menu > .right.menu:first-child {
display: none;
}
.ui.menu .menu.right .item:before,
.ui.menu .item.right:before {
right: auto;
left: 0px;
}
/*--------------
Text Content
---------------*/
.ui.menu .text.item > *,
.ui.menu .item > a:not(.ui),
.ui.menu .item > p:only-child {
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
line-height: 1.3;
color: rgba(0, 0, 0, 0.8);
}
.ui.menu .item > p:first-child {
margin-top: 0;
}
.ui.menu .item > p:last-child {
margin-bottom: 0;
}
/*--------------
Icons
---------------*/
.ui.menu .item > i.icon {
opacity: 0.75;
float: none;
margin: 0em 0.25em 0em 0em;
}
.ui.menu .item > i.dropdown.icon {
float: right;
margin-left: 1em;
}
/*--------------
Button
---------------*/
.ui.menu:not(.vertical) .item > .button {
position: relative;
top: -0.05em;
margin: -0.55em 0;
padding-bottom: 0.55em;
padding-top: 0.55em;
font-size: 0.875em;
}
/*--------------
Inputs
---------------*/
.ui.menu .item > .input {
width: 100%;
}
.ui.menu:not(.vertical) .item > .input {
position: relative;
top: 0em;
margin: -0.6em 0em;
}
.ui.menu .item > .input input {
font-size: 1em;
padding-top: 0.4em;
padding-bottom: 0.4em;
}
.ui.menu .item > .input .button,
.ui.menu .item > .input .label {
padding-top: 0.4em;
padding-bottom: 0.4em;
}
/* Resizes */
.ui.small.menu .item > .input input {
top: 0em;
padding-top: 0.4em;
padding-bottom: 0.4em;
}
.ui.small.menu .item > .input .button,
.ui.small.menu .item > .input .label {
padding-top: 0.4em;
padding-bottom: 0.4em;
}
.ui.large.menu .item > .input input {
top: -0.125em;
padding-bottom: 0.6em;
padding-top: 0.6em;
}
.ui.large.menu .item > .input .button,
.ui.large.menu .item > .input .label {
padding-top: 0.6em;
padding-bottom: 0.6em;
}
/*--------------
Header
---------------*/
.ui.menu .header.item,
.ui.vertical.menu .header.item {
background: rgba(0, 0, 0, 0.04);
margin: 0em;
text-transform: normal;
font-weight: bold;
}
/*--------------
Dropdowns
---------------*/
/* Dropdown */
.ui.menu .ui.dropdown.item.visible {
background: rgba(0, 0, 0, 0.03);
border-bottom-right-radius: 0em;
border-bottom-left-radius: 0em;
}
.ui.menu .ui.dropdown.active {
box-shadow: none;
}
/* Menu Position */
.ui.menu .dropdown.item .menu {
background: #ffffff;
left: 0px;
margin: 0px 0px 0px;
min-width: -webkit-calc(100% - 1px);
min-width: calc(100% - 1px);
box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.08);
}
.ui.menu:not(.secondary) .pointing.dropdown.item .menu {
margin-top: 0px;
border-top-left-radius: 0em;
border-top-right-radius: 0em;
}
.ui.menu .simple.dropdown.item .menu {
margin: 0px !important;
}
/* Secondary Menu Dropdown */
.ui.secondary.menu > .menu > .active.dropdown.item {
background-color: transparent;
}
.ui.secondary.menu .dropdown.item .menu {
left: 0px;
min-width: 100%;
}
/* Even Width Menu Dropdown */
.ui.item.menu .dropdown .menu .item {
width: 100%;
}
/*--------------
Labels
---------------*/
.ui.menu .item > .label {
background: rgba(0, 0, 0, 0.35);
color: #ffffff;
margin: -0.15em 0em -0.15em 0.5em;
padding: 0.3em 0.8em;
vertical-align: baseline;
}
.ui.menu .item > .floating.label {
padding: 0.3em 0.8em;
}
/*--------------
Images
---------------*/
.ui.menu .item > img:only-child {
display: block;
max-width: 100%;
margin: 0em auto;
}
/*******************************
States
*******************************/
/*--------------
Hover
---------------*/
.ui.link.menu > .item:hover,
.ui.menu > .link.item:hover,
.ui.menu > a.item:hover,
.ui.link.menu .menu > .item:hover,
.ui.menu .menu > .link.item:hover,
.ui.menu .menu > a.item:hover {
cursor: pointer;
background: rgba(0, 0, 0, 0.03);
color: rgba(0, 0, 0, 0.8);
}
/*--------------
Pressed
---------------*/
.ui.link.menu .item:active,
.ui.menu .link.item:active,
.ui.menu a.item:active {
background: rgba(0, 0, 0, 0.03);
color: rgba(0, 0, 0, 0.8);
}
/*--------------
Active
---------------*/
.ui.menu .active.item {
background: rgba(0, 0, 0, 0.03);
color: rgba(0, 0, 0, 0.8);
font-weight: normal;
box-shadow: 0em 2px 0em inset;
}
.ui.menu .active.item > i.icon {
opacity: 1;
}
/* Vertical */
.ui.vertical.menu .active.item {
background: rgba(0, 0, 0, 0.03);
border-radius: 0em;
box-shadow: 2px 0em 0em inset;
}
.ui.vertical.menu > .active.item:first-child {
border-radius: 0em 0.2857rem 0em 0em;
}
.ui.vertical.menu > .active.item:last-child {
border-radius: 0em 0em 0.2857rem 0em;
}
.ui.vertical.menu > .active.item:only-child {
border-radius: 0em 0.2857rem 0.2857rem 0em;
}
.ui.vertical.menu .active.item .menu .active.item {
border-left: none;
}
.ui.vertical.menu .item .menu .active.item {
background-color: transparent;
box-shadow: none;
}
/*--------------
Active Hover
---------------*/
.ui.vertical.menu .active.item:hover,
.ui.menu .active.item:hover {
background-color: rgba(0, 0, 0, 0.03);
}
/*--------------
Disabled
---------------*/
.ui.menu .item.disabled,
.ui.menu .item.disabled:hover {
cursor: default;
color: rgba(40, 40, 40, 0.3);
background-color: transparent !important;
}
/*******************************
Types
*******************************/
/*--------------
Vertical
---------------*/
.ui.vertical.menu {
background: #ffffff;
}
/*--- Item ---*/
.ui.vertical.menu .item {
background: none;
display: block;
height: auto !important;
border-top: none;
border-left: 0em solid transparent;
border-right: none;
}
.ui.vertical.menu > .item:first-child {
border-radius: 0.2857rem 0.2857rem 0px 0px;
}
.ui.vertical.menu > .item:last-child {
border-radius: 0px 0px 0.2857rem 0.2857rem;
}
/*--- Label ---*/
.ui.vertical.menu .item > .label {
float: right;
text-align: center;
}
/*--- Icon ---*/
.ui.vertical.menu .item > i.icon {
width: 1.18em;
float: right;
margin: 0em 0em 0em 0.5em;
}
.ui.vertical.menu .item > .label + i.icon {
float: none;
margin: 0em 0.5em 0em 0em;
}
/*--- Border ---*/
.ui.vertical.menu .item:before {
position: absolute;
content: '';
top: 0%;
left: 0px;
width: 100%;
background: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.03) 0%, rgba(0, 0, 0, 0.1) 1.5em, rgba(0, 0, 0, 0.03) 100%);
background: linear-gradient(to right, rgba(0, 0, 0, 0.03) 0%, rgba(0, 0, 0, 0.1) 1.5em, rgba(0, 0, 0, 0.03) 100%);
height: 1px;
}
.ui.vertical.menu .item:first-child:before {
background: none !important;
}
/*--- Dropdown ---*/
.ui.vertical.menu .dropdown.item > .icon {
float: right;
content: "\f0da";
margin-left: 1em;
}
.ui.vertical.menu .active.dropdown.item {
border-top-right-radius: 0em;
border-bottom-right-radius: 0em;
}
.ui.vertical.menu .dropdown.item .menu {
top: 0% !important;
left: 100%;
margin: 0px 0px 0px 0px;
box-shadow: 0 1px 3px 0px rgba(0, 0, 0, 0.08);
border-radius: 0em 0.2857rem 0.2857rem 0.2857rem;
}
.ui.vertical.menu .dropdown.item .menu .item {
font-size: 1rem;
}
.ui.vertical.menu .dropdown.item .menu .item i.icon {
margin-right: 0em;
}
.ui.vertical.menu .dropdown.item.active {
box-shadow: none;
}
/*--- Sub Menu ---*/
.ui.vertical.menu .item:not(.dropdown) > .menu {
margin: 0.5em -0.95em 0em;
}
.ui.vertical.menu .item:not(.dropdown) > .menu > .item {
background: none;
padding: 0.5rem 1.5rem;
font-size: 0.875rem;
}
.ui.vertical.menu .item > .menu > .item:before {
display: none;
}
/*--------------
Tiered
---------------*/
.ui.tiered.menu > .menu > .item:hover {
color: rgba(0, 0, 0, 0.8);
}
.ui.tiered.menu .active.item {
background: #fcfcfc;
}
.ui.tiered.menu > .menu .item.active:after {
position: absolute;
content: '';
margin-top: -1px;
top: 100%;
left: 0px;
width: 100%;
height: 2px;
background-color: #fcfcfc;
}
/* Sub Menu */
.ui.tiered.menu .sub.menu {
background-color: #fcfcfc;
border-radius: 0em;
border-top: 1px solid rgba(39, 41, 43, 0.15);
box-shadow: none;
}
.ui.tiered.menu > .sub.menu > .item {
color: rgba(0, 0, 0, 0.4);
font-weight: normal;
text-transform: normal;
font-size: 0.875rem;
}
/* Sub Menu Divider */
.ui.tiered.menu .sub.menu .item:before {
background: none;
}
/* Sub Menu Hover */
.ui.tiered.menu .sub.menu .item:hover {
background: none transparent;
color: rgba(0, 0, 0, 0.8);
}
/* Sub Menu Active */
.ui.tiered.menu .sub.menu .active.item {
padding-top: 0.78571em;
background: none transparent;
border-radius: 0;
border-top: medium none;
box-shadow: none;
color: rgba(0, 0, 0, 0.8) !important;
}
.ui.tiered.menu .sub.menu .active.item:after {
display: none;
}
/* Inverted Tiered Menu */
.ui.inverted.tiered.menu > .menu > .item {
color: rgba(255, 255, 255, 0.5);
}
.ui.inverted.tiered.menu .sub.menu {
background-color: rgba(0, 0, 0, 0.2);
}
.ui.inverted.tiered.menu .sub.menu .item {
color: rgba(255, 255, 255, 0.8);
}
.ui.inverted.tiered.menu > .menu > .item:hover {
color: #ffffff;
}
.ui.inverted.tiered.menu .active.item:after {
display: none;
}
.ui.inverted.tiered.menu > .sub.menu > .active.item,
.ui.inverted.tiered.menu > .menu > .active.item {
color: #ffffff !important;
box-shadow: none;
}
/* Tiered Pointing */
.ui.pointing.tiered.menu > .menu > .item:after {
display: none;
}
.ui.pointing.tiered.menu > .sub.menu > .item:after {
display: block;
}
/*--------------
Tabular
---------------*/
.ui.tabular.menu {
background-color: transparent;
border-bottom: 1px solid #d4d4d5;
border-radius: 0em;
box-shadow: none !important;
}
.ui.tabular.menu .item {
background-color: transparent;
border-left: 1px solid transparent;
border-right: 1px solid transparent;
border-top: 1px solid transparent;
padding-left: 1.4em;
padding-right: 1.4em;
color: rgba(0, 0, 0, 0.8);
}
.ui.tabular.menu .item:before {
display: none;
}
/* Hover */
.ui.tabular.menu .item:hover {
background-color: transparent;
color: rgba(0, 0, 0, 0.8);
}
/* Active */
.ui.tabular.menu .active.item {
position: relative;
background-color: #ffffff;
color: rgba(0, 0, 0, 0.8);
border-color: #d4d4d5;
font-weight: bold;
margin-bottom: -1px;
border-bottom: 1px solid #ffffff;
box-shadow: none;
border-radius: 5px 5px 0px 0px;
}
/* Coupling with segment for attachment */
.ui.attached.tabular.menu {
position: relative;
z-index: 2;
}
.ui.tabular.menu ~ .bottom.attached.segment {
margin: -1px 0px 0px;
}
/*--------------
Pagination
---------------*/
.ui.pagination.menu {
margin: 0em;
display: inline-block;
vertical-align: middle;
}
.ui.pagination.menu .item {
min-width: 3em;
text-align: center;
}
.ui.pagination.menu .icon.item i.icon {
vertical-align: top;
}
.ui.pagination.menu.floated {
display: block;
}
/* Active */
.ui.pagination.menu .active.item {
border-top: none;
padding-top: 0.78571em;
background-color: rgba(0, 0, 0, 0.03);
box-shadow: none;
}
/*--------------
Secondary
---------------*/
.ui.secondary.menu {
background: none;
border-radius: 0em;
box-shadow: none;
}
.ui.secondary.menu > .menu > .item,
.ui.secondary.menu > .item {
box-shadow: none;
border: none;
height: auto !important;
background: none;
margin: 0em 0.25em;
padding: 0.5em 0.8em;
border-radius: 0.2857rem;
}
.ui.secondary.menu > .menu > .item:before,
.ui.secondary.menu > .item:before {
display: none !important;
}
.ui.secondary.menu .item > .input input {
background-color: transparent;
border: none;
}
.ui.secondary.menu .link.item,
.ui.secondary.menu a.item {
opacity: 0.8;
-webkit-transition: none;
transition: none;
}
.ui.secondary.menu .header.item {
border-right: 0.1em solid rgba(0, 0, 0, 0.1);
background: none transparent;
border-radius: 0em;
}
/* Hover */
.ui.secondary.menu .link.item:hover,
.ui.secondary.menu a.item:hover {
opacity: 1;
}
/* Active */
.ui.secondary.menu > .menu > .active.item,
.ui.secondary.menu > .active.item {
background: rgba(0, 0, 0, 0.05);
opacity: 1;
box-shadow: none;
}
.ui.secondary.vertical.menu > .active.item {
border-radius: 0.2857rem;
}
/* Inverted */
.ui.secondary.inverted.menu .link.item,
.ui.secondary.inverted.menu a.item {
color: rgba(255, 255, 255, 0.8);
}
.ui.secondary.inverted.menu .link.item:hover,
.ui.secondary.inverted.menu a.item:hover {
color: #ffffff;
}
.ui.secondary.inverted.menu .active.item {
background-color: rgba(255, 255, 255, 0.05);
}
/* Disable variations */
.ui.secondary.item.menu > .item {
margin: 0em;
}
.ui.secondary.attached.menu {
box-shadow: none;
}
/*---------------------
Secondary Vertical
-----------------------*/
.ui.secondary.vertical.menu > .item {
border: none;
margin: 0em 0em 0.3em;
border-radius: 0.2857rem;
}
.ui.secondary.vertical.menu > .header.item {
border-radius: 0em;
}
/* Inverted */
.ui.secondary.inverted.menu {
background-color: transparent;
}
.ui.secondary.inverted.pointing.menu {
border-bottom: 3px solid rgba(255, 255, 255, 0.1);
}
.ui.secondary.inverted.pointing.menu > .item {
color: rgba(255, 255, 255, 0.7);
}
.ui.secondary.inverted.pointing.menu > .header.item {
color: #FFFFFF !important;
}
/* Hover */
.ui.secondary.inverted.pointing.menu > .menu > .item:hover,
.ui.secondary.inverted.pointing.menu > .item:hover {
color: rgba(255, 255, 255, 0.85);
}
/* Pressed */
.ui.secondary.inverted.pointing.menu > .menu > .item:active,
.ui.secondary.inverted.pointing.menu > .item:active {
border-color: rgba(255, 255, 255, 0.4);
}
/* Active */
.ui.secondary.inverted.pointing.menu > .menu > .item.active,
.ui.secondary.inverted.pointing.menu > .item.active {
border-color: rgba(255, 255, 255, 0.8);
color: #ffffff;
}
/*---------------------
Secondary Pointing
-----------------------*/
.ui.secondary.pointing.menu {
border-bottom: 3px solid rgba(0, 0, 0, 0.1);
}
.ui.secondary.pointing.menu > .menu > .item,
.ui.secondary.pointing.menu > .item {
margin: 0em 0em -3px;
padding: 0.6em 0.95em;
border-bottom: 3px solid transparent;
border-radius: 0em;
-webkit-transition: color 0.2s ease;
transition: color 0.2s ease;
}
/* Item Types */
.ui.secondary.pointing.menu .header.item {
margin-bottom: -3px;
background-color: transparent !important;
border-right-width: 0px !important;
font-weight: bold !important;
color: rgba(0, 0, 0, 0.85) !important;
}
.ui.secondary.pointing.menu .text.item {
box-shadow: none !important;
}
.ui.secondary.pointing.menu > .menu > .item:after,
.ui.secondary.pointing.menu > .item:after {
display: none;
}
/* Hover */
.ui.secondary.pointing.menu > .menu > .link.item:hover,
.ui.secondary.pointing.menu > .link.item:hover,
.ui.secondary.pointing.menu > .menu > a.item:hover,
.ui.secondary.pointing.menu > a.item:hover {
background-color: transparent;
color: rgba(0, 0, 0, 0.8);
}
/* Pressed */
.ui.secondary.pointing.menu > .menu > .link.item:active,
.ui.secondary.pointing.menu > .link.item:active,
.ui.secondary.pointing.menu > .menu > a.item:active,
.ui.secondary.pointing.menu > a.item:active {
background-color: transparent;
border-color: rgba(0, 0, 0, 0.2);
}
/* Active */
.ui.secondary.pointing.menu > .menu > .item.active,
.ui.secondary.pointing.menu > .item.active {
background-color: transparent;
border-color: rgba(0, 0, 0, 0.4);
box-shadow: none;
color: rgba(0, 0, 0, 0.8);
}
/* Secondary Vertical Pointing */
.ui.secondary.vertical.pointing.menu {
border: none;
border-right: 3px solid rgba(0, 0, 0, 0.1);
}
.ui.secondary.vertical.pointing.menu > .item {
margin: 0em -3px 0em 0em;
border-bottom: none;
border-right: 3px solid transparent;
border-radius: 0em;
}
/* Hover */
.ui.secondary.vertical.pointing.menu > .item:hover {
background-color: transparent;
color: rgba(0, 0, 0, 0.7);
}
/* Pressed */
.ui.secondary.vertical.pointing.menu > .item:active {
background-color: transparent;
border-color: rgba(0, 0, 0, 0.2);
}
/* Active */
.ui.secondary.vertical.pointing.menu > .item.active {
background-color: transparent;
border-color: rgba(0, 0, 0, 0.4);
color: rgba(0, 0, 0, 0.85);
}
/* Inverted Vertical Pointing Secondary */
.ui.secondary.inverted.vertical.pointing.menu {
border-right: 3px solid rgba(255, 255, 255, 0.1);
border-bottom: none;
}
/*--------------
Text Menu
---------------*/
.ui.text.menu {
display: inline-block;
background: none transparent;
margin: 1rem -1rem;
border-radius: 0px;
box-shadow: none;
}
.ui.text.menu > .item {
opacity: 0.8;
margin: 0em 1em;
padding: 0em;
height: auto !important;
border-radius: 0px;
box-shadow: none;
-webkit-transition: opacity 0.2s ease;
transition: opacity 0.2s ease;
}
.ui.text.menu > .item:before {
display: none !important;
}
.ui.text.menu .header.item {
background-color: transparent;
opacity: 1;
color: rgba(50, 50, 50, 0.8);
font-size: 0.875rem;
padding: 0em;
text-transform: uppercase;
font-weight: bold;
}
.ui.text.menu .text.item {
opacity: 1;
color: rgba(50, 50, 50, 0.8);
font-weight: bold;
}
/*--- fluid text ---*/
.ui.text.item.menu .item {
margin: 0em;
}
/*--- vertical text ---*/
.ui.vertical.text.menu {
margin: 1rem 0em;
}
.ui.vertical.text.menu:first-child {
margin-top: 0rem;
}
.ui.vertical.text.menu:last-child {
margin-bottom: 0rem;
}
.ui.vertical.text.menu .item {
float: left;
clear: left;
margin: 0.5em 0em;
}
.ui.vertical.text.menu .item > i.icon {
float: none;
margin: 0em 0.78571em 0em 0em;
}
.ui.vertical.text.menu .header.item {
margin: 0.8em 0em;
}
/*--- hover ---*/
.ui.text.menu .item:hover {
opacity: 1;
background-color: transparent;
}
/*--- active ---*/
.ui.text.menu .active.item {
background-color: transparent;
padding: 0em;
border: none;
opacity: 1;
font-weight: bold;
box-shadow: none;
}
/* disable variations */
.ui.text.pointing.menu .active.item:after {
box-shadow: none;
}
.ui.text.attached.menu {
box-shadow: none;
}
.ui.inverted.text.menu,
.ui.inverted.text.menu .item,
.ui.inverted.text.menu .item:hover,
.ui.inverted.text.menu .item.active {
background-color: transparent;
}
/*--------------
Icon Only
---------------*/
.ui.icon.menu,
.ui.vertical.icon.menu {
width: auto;
display: inline-block;
height: auto;
}
.ui.icon.menu > .item {
height: auto;
text-align: center;
color: rgba(60, 60, 60, 0.7);
}
.ui.icon.menu > .item > .icon {
display: block;
float: none !important;
opacity: 1;
margin: 0em auto !important;
}
.ui.icon.menu .icon:before {
opacity: 1;
}
/* Item Icon Only */
.ui.menu .icon.item .icon {
margin: 0em;
}
.ui.vertical.icon.menu {
float: none;
}
/*--- inverted ---*/
.ui.inverted.icon.menu .item {
color: rgba(255, 255, 255, 0.8);
}
.ui.inverted.icon.menu .icon {
color: #ffffff;
}
/*--------------
Labeled Icon
---------------*/
.ui.labeled.icon.menu {
text-align: center;
}
.ui.labeled.icon.menu > .item {
min-width: 6em;
}
.ui.labeled.icon.menu > .item > .icon {
display: block;
font-size: 1.5em !important;
margin: 0em auto 0.5em !important;
}
/*******************************
Variations
*******************************/
/*--------------
Colors
---------------*/
/*--- Light Colors ---*/
.ui.menu .blue.active.item,
.ui.blue.menu .active.item {
border-color: #3b83c0 !important;
color: #3b83c0 !important;
}
.ui.menu .green.active.item,
.ui.green.menu .active.item {
border-color: #5bbd72 !important;
color: #5bbd72 !important;
}
.ui.menu .orange.active.item,
.ui.orange.menu .active.item {
border-color: #e07b53 !important;
color: #e07b53 !important;
}
.ui.menu .pink.active.item,
.ui.pink.menu .active.item {
border-color: #d9499a !important;
color: #d9499a !important;
}
.ui.menu .purple.active.item,
.ui.purple.menu .active.item {
border-color: #564f8a !important;
color: #564f8a !important;
}
.ui.menu .red.active.item,
.ui.red.menu .active.item {
border-color: #d95c5c !important;
color: #d95c5c !important;
}
.ui.menu .teal.active.item,
.ui.teal.menu .active.item {
border-color: #00b5ad !important;
color: #00b5ad !important;
}
.ui.menu .yellow.active.item,
.ui.yellow.menu .active.item {
border-color: #f2c61f !important;
color: #f2c61f !important;
}
/*--------------
Inverted
---------------*/
.ui.inverted.menu {
background: #1b1c1d;
box-shadow: none;
}
.ui.inverted.menu .header.item {
margin: 0em;
background: rgba(0, 0, 0, 0.3);
box-shadow: none;
}
.ui.inverted.menu .item,
.ui.inverted.menu .item > a:not(.ui) {
color: #ffffff;
}
.ui.inverted.menu .item:not(.dropdown).menu {
background: transparent;
}
.ui.inverted.menu .item .item,
.ui.inverted.menu .item .item > a:not(.ui) {
color: rgba(255, 255, 255, 0.5);
}
.ui.inverted.menu .dropdown .menu .item {
color: rgba(0, 0, 0, 0.8) !important;
}
.ui.inverted.menu .item.disabled,
.ui.inverted.menu .item.disabled:hover {
color: rgba(225, 225, 225, 0.3);
}
/*--- Border ---*/
.ui.inverted.menu .item:before {
background: -webkit-linear-gradient(rgba(255, 255, 255, 0.03) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.03) 100%);
background: linear-gradient(rgba(255, 255, 255, 0.03) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.03) 100%);
}
.ui.vertical.inverted.menu .item:before {
background: -webkit-linear-gradient(left, rgba(255, 255, 255, 0.03) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.03) 100%);
background: linear-gradient(to right, rgba(255, 255, 255, 0.03) 0%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.03) 100%);
}
/*--- Hover ---*/
.ui.link.inverted.menu .item:hover,
.ui.inverted.menu .link.item:hover,
.ui.inverted.menu a.item:hover,
.ui.inverted.menu .dropdown.item:hover {
background: rgba(255, 255, 255, 0.1);
color: #ffffff;
}
.ui.inverted.menu .item .menu a.item:hover,
.ui.inverted.menu .item .menu .link.item:hover {
background: transparent;
color: #ffffff;
}
/*--- Pressed ---*/
.ui.inverted.menu a.item:active,
.ui.inverted.menu .dropdown.item:active,
.ui.inverted.menu .link.item:active,
.ui.inverted.menu a.item:active {
background: rgba(255, 255, 255, 0.15);
color: #ffffff;
}
/*--- Active ---*/
.ui.inverted.menu .active.item {
box-shadow: none !important;
background: rgba(255, 255, 255, 0.2);
color: #ffffff !important;
}
.ui.inverted.vertical.menu .item .menu .active.item {
background: transparent;
color: #ffffff;
}
/*--- Pointers ---*/
.ui.inverted.pointing.menu .active.item:after {
background: #5B5B5B;
box-shadow: none;
}
.ui.inverted.pointing.menu .active.item:hover:after {
background: #4A4A4A;
}
/*--------------
Selection
---------------*/
.ui.selection.menu > .item {
color: rgba(0, 0, 0, 0.4);
}
.ui.selection.menu > .item:hover {
color: rgba(0, 0, 0, 0.6);
}
.ui.selection.menu > .item.active {
color: rgba(0, 0, 0, 0.85);
}
.ui.inverted.selection.menu > .item {
color: rgba(255, 255, 255, 0.4);
}
.ui.inverted.selection.menu > .item:hover {
color: rgba(255, 255, 255, 0.9);
}
.ui.inverted.selection.menu > .item.active {
color: #FFFFFF;
}
/*--------------
Floated
---------------*/
.ui.floated.menu {
float: left;
margin: 0rem 0.5rem 0rem 0rem;
}
.ui.right.floated.menu {
float: right;
margin: 0rem 0rem 0rem 0.5rem;
}
/*--------------
Inverted Colors
---------------*/
/*--- Light Colors ---*/
.ui.grey.menu {
background-color: #fafafa;
}
/*--- Inverted Colors ---*/
/* Blue */
.ui.inverted.blue.menu {
background-color: #3b83c0;
}
.ui.inverted.blue.pointing.menu .active.item:after {
background-color: #3b83c0;
}
/* Green */
.ui.inverted.green.menu {
background-color: #5bbd72;
}
.ui.inverted.green.pointing.menu .active.item:after {
background-color: #5bbd72;
}
/* Orange */
.ui.inverted.orange.menu {
background-color: #e07b53;
}
.ui.inverted.orange.pointing.menu .active.item:after {
background-color: #e07b53;
}
/* Pink */
.ui.inverted.pink.menu {
background-color: #d9499a;
}
.ui.inverted.pink.pointing.menu .active.item:after {
background-color: #d9499a;
}
/* Purple */
.ui.inverted.purple.menu {
background-color: #564f8a;
}
.ui.inverted.purple.pointing.menu .active.item:after {
background-color: #564f8a;
}
/* Red */
.ui.inverted.red.menu {
background-color: #d95c5c;
}
.ui.inverted.red.pointing.menu .active.item:after {
background-color: #d95c5c;
}
/* Teal */
.ui.inverted.teal.menu {
background-color: #00b5ad;
}
.ui.inverted.teal.pointing.menu .active.item:after {
background-color: #00b5ad;
}
/* Yellow */
.ui.inverted.yellow.menu {
background-color: #f2c61f;
}
.ui.inverted.yellow.pointing.menu .active.item:after {
background-color: #f2c61f;
}
/*--------------
Fitted
---------------*/
.ui.fitted.menu .item,
.ui.fitted.menu .item .menu .item,
.ui.menu .fitted.item {
padding: 0em;
}
.ui.horizontally.fitted.menu .item,
.ui.horizontally.fitted.menu .item .menu .item,
.ui.menu .horizontally.fitted.item {
padding-top: 0.78571em;
padding-bottom: 0.78571em;
}
.ui.vertically.fitted.menu .item,
.ui.vertically.fitted.menu .item .menu .item,
.ui.menu .vertically.fitted.item {
padding-left: 0.95em;
padding-right: 0.95em;
}
/*--------------
Borderless
---------------*/
.ui.borderless.menu .item:before,
.ui.borderless.menu .item .menu .item:before,
.ui.menu .borderless.item:before {
background: none !important;
}
/*-------------------
Compact
--------------------*/
.ui.compact.menu {
display: inline-block;
margin: 0em;
vertical-align: middle;
}
.ui.compact.vertical.menu {
width: auto !important;
}
.ui.compact.vertical.menu .item:last-child::before {
display: block;
}
/*-------------------
Fluid
--------------------*/
.ui.menu.fluid,
.ui.vertical.menu.fluid {
display: block;
width: 100% !important;
}
/*-------------------
Evenly Sized
--------------------*/
.ui.item.menu,
.ui.item.menu .item {
width: 100%;
padding-left: 0px !important;
padding-right: 0px !important;
text-align: center;
}
.ui.item.menu > .item:last-child {
border-radius: 0px 0.2857rem 0.2857rem 0px;
}
.ui.menu.two.item .item {
width: 50%;
}
.ui.menu.three.item .item {
width: 33.333%;
}
.ui.menu.four.item .item {
width: 25%;
}
.ui.menu.five.item .item {
width: 20%;
}
.ui.menu.six.item .item {
width: 16.666%;
}
.ui.menu.seven.item .item {
width: 14.285%;
}
.ui.menu.eight.item .item {
width: 12.500%;
}
.ui.menu.nine.item .item {
width: 11.11%;
}
.ui.menu.ten.item .item {
width: 10.0%;
}
.ui.menu.eleven.item .item {
width: 9.09%;
}
.ui.menu.twelve.item .item {
width: 8.333%;
}
/*--------------
Fixed
---------------*/
.ui.menu.fixed {
position: fixed;
z-index: 101;
margin: 0em;
border: none;
width: 100%;
}
.ui.menu.fixed,
.ui.menu.fixed .item:first-child,
.ui.menu.fixed .item:last-child {
border-radius: 0px !important;
}
.ui.fixed.menu,
.ui.top.fixed.menu {
top: 0px;
left: 0px;
right: auto;
bottom: auto;
}
.ui.right.fixed.menu {
top: 0px;
right: 0px;
left: auto;
bottom: auto;
width: auto;
height: 100%;
}
.ui.bottom.fixed.menu {
bottom: 0px;
left: 0px;
top: auto;
right: auto;
}
.ui.left.fixed.menu {
top: 0px;
left: 0px;
right: auto;
bottom: auto;
width: auto;
height: 100%;
}
/* Coupling with Grid */
.ui.fixed.menu + .ui.grid {
padding-top: 2.75rem;
}
/*-------------------
Pointing
--------------------*/
.ui.pointing.menu .active.item:after {
position: absolute;
bottom: -0.3em;
left: 50%;
content: '';
margin-left: -0.3em;
width: 0.6em;
height: 0.6em;
border: none;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
border-right: 1px solid rgba(0, 0, 0, 0.1);
background: none;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
z-index: 2;
-webkit-transition: background 0.2s ease
;
transition: background 0.2s ease
;
}
/* Don't double up pointers */
.ui.pointing.menu .active.item .menu .active.item:after {
display: none;
}
.ui.vertical.pointing.menu .active.item:after {
position: absolute;
top: 50%;
margin-top: -0.3em;
right: -0.3em;
bottom: auto;
left: auto;
border: none;
border-top: 1px solid rgba(0, 0, 0, 0.1);
border-right: 1px solid rgba(0, 0, 0, 0.1);
}
/* Colors */
.ui.pointing.menu .active.item:hover:after {
background-color: #fafafa;
}
.ui.pointing.menu .active.item:after {
background-color: #f6f6f6;
}
.ui.vertical.pointing.menu .item:hover:after {
background-color: #fafafa;
}
.ui.vertical.pointing.menu .active.item:after {
background-color: #fcfcfc;
}
/*--------------
Attached
---------------*/
.ui.menu.attached {
margin: 0rem;
border-radius: 0px;
/* avoid rgba multiplying */
box-shadow: 0px 0px 0px 1px #dddddd;
}
.ui.top.attached.menu {
border-radius: 0.2857rem 0.2857rem 0em 0em;
}
.ui.menu.bottom.attached {
border-radius: 0em 0em 0.2857rem 0.2857rem;
}
/*--------------
Sizes
---------------*/
/* Small */
.ui.small.menu .item {
font-size: 0.875rem;
}
.ui.small.vertical.menu {
width: 13rem;
}
/* Medium */
.ui.menu .item {
font-size: 1rem;
}
.ui.vertical.menu {
width: 15rem;
}
/* Large */
.ui.large.menu .item {
font-size: 1.125rem;
}
.ui.large.menu .item .item {
font-size: 0.875rem;
}
.ui.large.menu .dropdown .item {
font-size: 1rem;
}
.ui.large.vertical.menu {
width: 18rem;
}
/*******************************
Theme Overrides
*******************************/
/*******************************
Site Overrides
*******************************/
|
aranoah/seats-reservation-system
|
public/Semantic-UI-1.5.2/dist/components/menu.css
|
CSS
|
apache-2.0
| 31,971
|
/*
* Copyright 2011-2012, Meador Inge, Mentor Graphics Corporation.
*
* Some ideas based on un-pushed work done by Vivek Mahajan, Jason Jin, and
* Mingkai Hu from Freescale Semiconductor, Inc.
*
* 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.
*
*/
#include <linux/list.h>
#include <linux/of_platform.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <asm/prom.h>
#include <asm/hw_irq.h>
#include <asm/ppc-pci.h>
#include <asm/mpic_msgr.h>
#define MPIC_MSGR_REGISTERS_PER_BLOCK 4
#define MPIC_MSGR_STRIDE 0x10
#define MPIC_MSGR_MER_OFFSET 0x100
#define MSGR_INUSE 0
#define MSGR_FREE 1
static struct mpic_msgr **mpic_msgrs;
static unsigned int mpic_msgr_count;
static DEFINE_RAW_SPINLOCK(msgrs_lock);
static inline void _mpic_msgr_mer_write(struct mpic_msgr *msgr, u32 value)
{
out_be32(msgr->mer, value);
}
static inline u32 _mpic_msgr_mer_read(struct mpic_msgr *msgr)
{
return in_be32(msgr->mer);
}
static inline void _mpic_msgr_disable(struct mpic_msgr *msgr)
{
u32 mer = _mpic_msgr_mer_read(msgr);
_mpic_msgr_mer_write(msgr, mer & ~(1 << msgr->num));
}
struct mpic_msgr *mpic_msgr_get(unsigned int reg_num)
{
unsigned long flags;
struct mpic_msgr *msgr;
/* Assume busy until proven otherwise. */
msgr = ERR_PTR(-EBUSY);
if (reg_num >= mpic_msgr_count)
return ERR_PTR(-ENODEV);
raw_spin_lock_irqsave(&msgrs_lock, flags);
msgr = mpic_msgrs[reg_num];
if (msgr->in_use == MSGR_FREE)
msgr->in_use = MSGR_INUSE;
raw_spin_unlock_irqrestore(&msgrs_lock, flags);
return msgr;
}
EXPORT_SYMBOL_GPL(mpic_msgr_get);
void mpic_msgr_put(struct mpic_msgr *msgr)
{
unsigned long flags;
raw_spin_lock_irqsave(&msgr->lock, flags);
msgr->in_use = MSGR_FREE;
_mpic_msgr_disable(msgr);
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_put);
void mpic_msgr_enable(struct mpic_msgr *msgr)
{
unsigned long flags;
u32 mer;
raw_spin_lock_irqsave(&msgr->lock, flags);
mer = _mpic_msgr_mer_read(msgr);
_mpic_msgr_mer_write(msgr, mer | (1 << msgr->num));
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_enable);
void mpic_msgr_disable(struct mpic_msgr *msgr)
{
unsigned long flags;
raw_spin_lock_irqsave(&msgr->lock, flags);
_mpic_msgr_disable(msgr);
raw_spin_unlock_irqrestore(&msgr->lock, flags);
}
EXPORT_SYMBOL_GPL(mpic_msgr_disable);
/* The following three functions are used to compute the order and number of
* the message register blocks. They are clearly very inefficent. However,
* they are called *only* a few times during device initialization.
*/
static unsigned int mpic_msgr_number_of_blocks(void)
{
unsigned int count;
struct device_node *aliases;
count = 0;
aliases = of_find_node_by_name(NULL, "aliases");
if (aliases) {
char buf[32];
for (;;) {
snprintf(buf, sizeof(buf), "mpic-msgr-block%d", count);
if (!of_find_property(aliases, buf, NULL))
break;
count += 1;
}
}
return count;
}
static unsigned int mpic_msgr_number_of_registers(void)
{
return mpic_msgr_number_of_blocks() * MPIC_MSGR_REGISTERS_PER_BLOCK;
}
static int mpic_msgr_block_number(struct device_node *node)
{
struct device_node *aliases;
unsigned int index, number_of_blocks;
char buf[64];
number_of_blocks = mpic_msgr_number_of_blocks();
aliases = of_find_node_by_name(NULL, "aliases");
if (!aliases)
return -1;
for (index = 0; index < number_of_blocks; ++index) {
struct property *prop;
snprintf(buf, sizeof(buf), "mpic-msgr-block%d", index);
prop = of_find_property(aliases, buf, NULL);
if (node == of_find_node_by_path(prop->value))
break;
}
return index == number_of_blocks ? -1 : index;
}
/* The probe function for a single message register block.
*/
static int mpic_msgr_probe(struct platform_device *dev)
{
void __iomem *msgr_block_addr;
int block_number;
struct resource rsrc;
unsigned int i;
unsigned int irq_index;
struct device_node *np = dev->dev.of_node;
unsigned int receive_mask;
const unsigned int *prop;
if (!np) {
dev_err(&dev->dev, "Device OF-Node is NULL");
return -EFAULT;
}
/* Allocate the message register array upon the first device
* registered.
*/
if (!mpic_msgrs) {
mpic_msgr_count = mpic_msgr_number_of_registers();
dev_info(&dev->dev, "Found %d message registers\n",
mpic_msgr_count);
mpic_msgrs = kzalloc(sizeof(struct mpic_msgr) * mpic_msgr_count,
GFP_KERNEL);
if (!mpic_msgrs) {
dev_err(&dev->dev,
"No memory for message register blocks\n");
return -ENOMEM;
}
}
dev_info(&dev->dev, "Of-device full name %s\n", np->full_name);
/* IO map the message register block. */
of_address_to_resource(np, 0, &rsrc);
msgr_block_addr = ioremap(rsrc.start, rsrc.end - rsrc.start);
if (!msgr_block_addr) {
dev_err(&dev->dev, "Failed to iomap MPIC message registers");
return -EFAULT;
}
/* Ensure the block has a defined order. */
block_number = mpic_msgr_block_number(np);
if (block_number < 0) {
dev_err(&dev->dev,
"Failed to find message register block alias\n");
return -ENODEV;
}
dev_info(&dev->dev, "Setting up message register block %d\n",
block_number);
/* Grab the receive mask which specifies what registers can receive
* interrupts.
*/
prop = of_get_property(np, "mpic-msgr-receive-mask", NULL);
receive_mask = (prop) ? *prop : 0xF;
/* Build up the appropriate message register data structures. */
for (i = 0, irq_index = 0; i < MPIC_MSGR_REGISTERS_PER_BLOCK; ++i) {
struct mpic_msgr *msgr;
unsigned int reg_number;
msgr = kzalloc(sizeof(struct mpic_msgr), GFP_KERNEL);
if (!msgr) {
dev_err(&dev->dev, "No memory for message register\n");
return -ENOMEM;
}
reg_number = block_number * MPIC_MSGR_REGISTERS_PER_BLOCK + i;
msgr->base = msgr_block_addr + i * MPIC_MSGR_STRIDE;
msgr->mer = (u32 *)((u8 *)msgr->base + MPIC_MSGR_MER_OFFSET);
msgr->in_use = MSGR_FREE;
msgr->num = i;
raw_spin_lock_init(&msgr->lock);
if (receive_mask & (1 << i)) {
struct resource irq;
if (of_irq_to_resource(np, irq_index, &irq) == NO_IRQ) {
dev_err(&dev->dev,
"Missing interrupt specifier");
kfree(msgr);
return -EFAULT;
}
msgr->irq = irq.start;
irq_index += 1;
} else {
msgr->irq = NO_IRQ;
}
mpic_msgrs[reg_number] = msgr;
mpic_msgr_disable(msgr);
dev_info(&dev->dev, "Register %d initialized: irq %d\n",
reg_number, msgr->irq);
}
return 0;
}
static const struct of_device_id mpic_msgr_ids[] = {
{
.compatible = "fsl,mpic-v3.1-msgr",
.data = NULL,
},
{}
};
static struct platform_driver mpic_msgr_driver = {
.driver = {
.name = "mpic-msgr",
.owner = THIS_MODULE,
.of_match_table = mpic_msgr_ids,
},
.probe = mpic_msgr_probe,
};
static __init int mpic_msgr_init(void)
{
return platform_driver_register(&mpic_msgr_driver);
}
subsys_initcall(mpic_msgr_init);
|
prasidh09/cse506
|
unionfs-3.10.y/arch/powerpc/sysdev/mpic_msgr.c
|
C
|
gpl-2.0
| 7,032
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page Events - jQuery Mobile Demos</title>
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<link rel="stylesheet" href="../css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="../_assets/css/jqm-demos.css">
<script src="../js/jquery.js"></script>
<script src="../_assets/js/index.js"></script>
<script src="../js/jquery.mobile-1.4.5.min.js"></script>
<script src="http://cdn.rawgit.com/arschmitz/jquery-mobile-event-debugger/v0.0.4/jquery.mobile.event.debugger.js"></script>
<script>
$.mobile.eventLogger({
deprecated: true,
showAlert: true,
events: {
page: true
},
widgets: {
page: true,
pagecontainer: true
}
});
</script>
</head>
<body>
<div data-role="page" class="jqm-demos" data-quicklinks="true">
<div data-role="header" class="jqm-header">
<h2><a href="../" title="jQuery Mobile Demos home"><img src="../_assets/img/jquery-logo.png" alt="jQuery Mobile"></a></h2>
<p><span class="jqm-version"></span> Demos</p>
<a href="#" class="jqm-navmenu-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-bars ui-nodisc-icon ui-alt-icon ui-btn-left">Menu</a>
<a href="#" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-search ui-nodisc-icon ui-alt-icon ui-btn-right">Search</a>
</div><!-- /header -->
<div role="main" class="ui-content jqm-content">
<h1>navigate between pages and open and close panel and popup widgets to see which events fire and their data</h1>
<a class="ui-btn ui-corner-all ui" href="alertevents.html">Go To Page 1</a>
<a class="ui-btn ui-corner-all ui" href="alertevents-2.html">Go To Page 2</a>
</div><!-- /content -->
<div data-role="panel" class="jqm-navmenu-panel" data-position="left" data-display="overlay" data-theme="a">
<ul class="jqm-list ui-alt-icon ui-nodisc-icon">
<li data-filtertext="demos homepage" data-icon="home"><a href=".././">Home</a></li>
<li data-filtertext="introduction overview getting started"><a href="../intro/" data-ajax="false">Introduction</a></li>
<li data-filtertext="buttons button markup buttonmarkup method anchor link button element"><a href="../button-markup/" data-ajax="false">Buttons</a></li>
<li data-filtertext="form button widget input button submit reset"><a href="../button/" data-ajax="false">Button widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Checkboxradio widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups"><a href="../checkboxradio-checkbox/" data-ajax="false">Checkboxes</a></li>
<li data-filtertext="form checkboxradio widget radio input radio buttons controlgroups"><a href="../checkboxradio-radio/" data-ajax="false">Radio buttons</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Collapsible (set) widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="collapsibles content formatting"><a href="../collapsible/" data-ajax="false">Collapsible</a></li>
<li data-filtertext="dynamic collapsible set accordion append expand"><a href="../collapsible-dynamic/" data-ajax="false">Dynamic collapsibles</a></li>
<li data-filtertext="accordions collapsible set widget content formatting grouped collapsibles"><a href="../collapsibleset/" data-ajax="false">Collapsible set</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Controlgroup widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="controlgroups selectmenu checkboxradio input grouped buttons horizontal vertical"><a href="../controlgroup/" data-ajax="false">Controlgroup</a></li>
<li data-filtertext="dynamic controlgroup dynamically add buttons"><a href="../controlgroup-dynamic/" data-ajax="false">Dynamic controlgroups</a></li>
</ul>
</div>
</li>
<li data-filtertext="form datepicker widget date input"><a href="../datepicker/" data-ajax="false">Datepicker</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Events<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="swipe to delete list items listviews swipe events"><a href="../swipe-list/" data-ajax="false">Swipe list items</a></li>
<li data-filtertext="swipe to navigate swipe page navigation swipe events"><a href="../swipe-page/" data-ajax="false">Swipe page navigation</a></li>
</ul>
</div>
</li>
<li data-filtertext="filterable filter elements sorting searching listview table"><a href="../filterable/" data-ajax="false">Filterable widget</a></li>
<li data-filtertext="form flipswitch widget flip toggle switch binary select checkbox input"><a href="../flipswitch/" data-ajax="false">Flipswitch widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Forms<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms/" data-ajax="false">Forms</a></li>
<li data-filtertext="form hide labels hidden accessible ui-hidden-accessible forms"><a href="../forms-label-hidden-accessible/" data-ajax="false">Hide labels</a></li>
<li data-filtertext="form field containers fieldcontain ui-field-contain forms"><a href="../forms-field-contain/" data-ajax="false">Field containers</a></li>
<li data-filtertext="forms disabled form elements"><a href="../forms-disabled/" data-ajax="false">Forms disabled</a></li>
<li data-filtertext="forms gallery examples overview forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms-gallery/" data-ajax="false">Forms gallery</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Grids<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="grids columns blocks content formatting rwd responsive css framework"><a href="../grids/" data-ajax="false">Grids</a></li>
<li data-filtertext="buttons in grids css framework"><a href="../grids-buttons/" data-ajax="false">Buttons in grids</a></li>
<li data-filtertext="custom responsive grids rwd css framework"><a href="../grids-custom-responsive/" data-ajax="false">Custom responsive grids</a></li>
</ul>
</div>
</li>
<li data-filtertext="blocks content formatting sections heading"><a href="../body-bar-classes/" data-ajax="false">Grouping and dividing content</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Icons<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="button icons svg disc alt custom icon position"><a href="../icons/" data-ajax="false">Icons</a></li>
<li data-filtertext=""><a href="../icons-grunticon/" data-ajax="false">Grunticon loader</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Listview widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="listview widget thumbnails icons nested split button collapsible ul ol"><a href="../listview/" data-ajax="false">Listview</a></li>
<li data-filtertext="autocomplete filterable reveal listview filtertextbeforefilter placeholder"><a href="../listview-autocomplete/" data-ajax="false">Listview autocomplete</a></li>
<li data-filtertext="autocomplete filterable reveal listview remote data filtertextbeforefilter placeholder"><a href="../listview-autocomplete-remote/" data-ajax="false">Listview autocomplete remote data</a></li>
<li data-filtertext="autodividers anchor jump scroll linkbars listview lists ul ol"><a href="../listview-autodividers-linkbar/" data-ajax="false">Listview autodividers linkbar</a></li>
<li data-filtertext="listview autodividers selector autodividersselector lists ul ol"><a href="../listview-autodividers-selector/" data-ajax="false">Listview autodividers selector</a></li>
<li data-filtertext="listview nested list items"><a href="../listview-nested-lists/" data-ajax="false">Nested Listviews</a></li>
<li data-filtertext="listview collapsible list items flat"><a href="../listview-collapsible-item-flat/" data-ajax="false">Listview collapsible list items (flat)</a></li>
<li data-filtertext="listview collapsible list indented"><a href="../listview-collapsible-item-indented/" data-ajax="false">Listview collapsible list items (indented)</a></li>
<li data-filtertext="grid listview responsive grids responsive listviews lists ul"><a href="../listview-grid/" data-ajax="false">Listview responsive grid</a></li>
</ul>
</div>
</li>
<li data-filtertext="loader widget page loading navigation overlay spinner"><a href="../loader/" data-ajax="false">Loader widget</a></li>
<li data-filtertext="navbar widget navmenu toolbars header footer"><a href="../navbar/" data-ajax="false">Navbar widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Navigation<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="ajax navigation navigate widget history event method"><a href="../navigation/" data-ajax="false">Navigation</a></li>
<li data-filtertext="linking pages page links navigation ajax prefetch cache"><a href="../navigation-linking-pages/" data-ajax="false">Linking pages</a></li>
<!-- <li data-filtertext="php redirect server redirection server-side navigation"><a href="../navigation-php-redirect/" data-ajax="false">PHP redirect demo</a></li>-->
<li data-filtertext="navigation redirection hash query"><a href="../navigation-hash-processing/" data-ajax="false">Hash processing demo</a></li>
<li data-filtertext="navigation redirection hash query"><a href="../page-events/" data-ajax="false">Page Navigation Events</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Pages<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="pages page widget ajax navigation"><a href="../pages/" data-ajax="false">Pages</a></li>
<li data-filtertext="single page"><a href="../pages-single-page/" data-ajax="false">Single page</a></li>
<li data-filtertext="multipage multi-page page"><a href="../pages-multi-page/" data-ajax="false">Multi-page template</a></li>
<li data-filtertext="dialog page widget modal popup"><a href="../pages-dialog/" data-ajax="false">Dialog page</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Panel widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="panel widget sliding panels reveal push overlay responsive"><a href="../panel/" data-ajax="false">Panel</a></li>
<li data-filtertext=""><a href="../panel-external/" data-ajax="false">External panels</a></li>
<li data-filtertext="panel "><a href="../panel-fixed/" data-ajax="false">Fixed panels</a></li>
<li data-filtertext="panel slide panels sliding panels shadow rwd responsive breakpoint"><a href="../panel-responsive/" data-ajax="false">Panels responsive</a></li>
<li data-filtertext="panel custom style custom panel width reveal shadow listview panel styling page background wrapper"><a href="../panel-styling/" data-ajax="false">Custom panel style</a></li>
<li data-filtertext="panel open on swipe"><a href="../panel-swipe-open/" data-ajax="false">Panel open on swipe</a></li>
<li data-filtertext="panels outside page internal external toolbars"><a href="../panel-external-internal/" data-ajax="false">Panel external and internal</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Popup widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="popup widget popups dialog modal transition tooltip lightbox form overlay screen flip pop fade transition"><a href="../popup/" data-ajax="false">Popup</a></li>
<li data-filtertext="popup alignment position"><a href="../popup-alignment/" data-ajax="false">Popup alignment</a></li>
<li data-filtertext="popup arrow size popups popover"><a href="../popup-arrow-size/" data-ajax="false">Popup arrow size</a></li>
<li data-filtertext="dynamic popups popup images lightbox"><a href="../popup-dynamic/" data-ajax="false">Dynamic popups</a></li>
<li data-filtertext="popups with iframes scaling"><a href="../popup-iframe/" data-ajax="false">Popups with iframes</a></li>
<li data-filtertext="popup image scaling"><a href="../popup-image-scaling/" data-ajax="false">Popup image scaling</a></li>
<li data-filtertext="external popup outside multi-page"><a href="../popup-outside-multipage/" data-ajax="false">Popup outside multi-page</a></li>
</ul>
</div>
</li>
<li data-filtertext="form rangeslider widget dual sliders dual handle sliders range input"><a href="../rangeslider/" data-ajax="false">Rangeslider widget</a></li>
<li data-filtertext="responsive web design rwd adaptive progressive enhancement PE accessible mobile breakpoints media query media queries"><a href="../rwd/" data-ajax="false">Responsive Web Design</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Selectmenu widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form selectmenu widget select input custom select menu selects"><a href="../selectmenu/" data-ajax="false">Selectmenu</a></li>
<li data-filtertext="form custom select menu selectmenu widget custom menu option optgroup multiple selects"><a href="../selectmenu-custom/" data-ajax="false">Custom select menu</a></li>
<li data-filtertext="filterable select filter popup dialog"><a href="../selectmenu-custom-filter/" data-ajax="false">Custom select menu with filter</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Slider widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form slider widget range input single sliders"><a href="../slider/" data-ajax="false">Slider</a></li>
<li data-filtertext="form slider widget flipswitch slider binary select flip toggle switch"><a href="../slider-flipswitch/" data-ajax="false">Slider flip toggle switch</a></li>
<li data-filtertext="form slider tooltip handle value input range sliders"><a href="../slider-tooltip/" data-ajax="false">Slider tooltip</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Table widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="table widget reflow column toggle th td responsive tables rwd hide show tabular"><a href="../table-column-toggle/" data-ajax="false">Table Column Toggle</a></li>
<li data-filtertext="table column toggle phone comparison demo"><a href="../table-column-toggle-example/" data-ajax="false">Table Column Toggle demo</a></li>
<li data-filtertext="responsive tables table column toggle heading groups rwd breakpoint"><a href="../table-column-toggle-heading-groups/" data-ajax="false">Table Column Toggle heading groups</a></li>
<li data-filtertext="responsive tables table column toggle hide rwd breakpoint customization options"><a href="../table-column-toggle-options/" data-ajax="false">Table Column Toggle options</a></li>
<li data-filtertext="table reflow th td responsive rwd columns tabular"><a href="../table-reflow/" data-ajax="false">Table Reflow</a></li>
<li data-filtertext="responsive tables table reflow heading groups rwd breakpoint"><a href="../table-reflow-heading-groups/" data-ajax="false">Table Reflow heading groups</a></li>
<li data-filtertext="responsive tables table reflow stripes strokes table style"><a href="../table-reflow-stripes-strokes/" data-ajax="false">Table Reflow stripes and strokes</a></li>
<li data-filtertext="responsive tables table reflow stack custom styles"><a href="../table-reflow-styling/" data-ajax="false">Table Reflow custom styles</a></li>
</ul>
</div>
</li>
<li data-filtertext="ui tabs widget"><a href="../tabs/" data-ajax="false">Tabs widget</a></li>
<li data-filtertext="form textinput widget text input textarea number date time tel email file color password"><a href="../textinput/" data-ajax="false">Textinput widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Theming<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="default theme swatches theming style css"><a href="../theme-default/" data-ajax="false">Default theme</a></li>
<li data-filtertext="classic theme old theme swatches theming style css"><a href="../theme-classic/" data-ajax="false">Classic theme</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Toolbar widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="toolbar widget header footer toolbars fixed fullscreen external sections"><a href="../toolbar/" data-ajax="false">Toolbar</a></li>
<li data-filtertext="dynamic toolbars dynamically add toolbar header footer"><a href="../toolbar-dynamic/" data-ajax="false">Dynamic toolbars</a></li>
<li data-filtertext="external toolbars header footer"><a href="../toolbar-external/" data-ajax="false">External toolbars</a></li>
<li data-filtertext="fixed toolbars header footer"><a href="../toolbar-fixed/" data-ajax="false">Fixed toolbars</a></li>
<li data-filtertext="fixed fullscreen toolbars header footer"><a href="../toolbar-fixed-fullscreen/" data-ajax="false">Fullscreen toolbars</a></li>
<li data-filtertext="external fixed toolbars header footer"><a href="../toolbar-fixed-external/" data-ajax="false">Fixed external toolbars</a></li>
<li data-filtertext="external persistent toolbars header footer navbar navmenu"><a href="../toolbar-fixed-persistent/" data-ajax="false">Persistent toolbars</a></li>
<li data-filtertext="external ajax optimized toolbars persistent toolbars header footer navbar"><a href="../toolbar-fixed-persistent-optimized/" data-ajax="false">Ajax optimized toolbars</a></li>
<li data-filtertext="form in toolbars header footer"><a href="../toolbar-fixed-forms/" data-ajax="false">Form in toolbar</a></li>
</ul>
</div>
</li>
<li data-filtertext="page transitions animated pages popup navigation flip slide fade pop"><a href="../transitions/" data-ajax="false">Transitions</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
3rd party API demos<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="backbone requirejs navigation router"><a href="../backbone-requirejs/" data-ajax="false">Backbone RequireJS</a></li>
<li data-filtertext="google maps geolocation demo"><a href="../map-geolocation/" data-ajax="false">Google Maps geolocation</a></li>
<li data-filtertext="google maps hybrid"><a href="../map-list-toggle/" data-ajax="false">Google Maps list toggle</a></li>
</ul>
</div>
</li>
</ul>
</div><!-- /panel -->
<div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer">
<p>jQuery Mobile Demos version <span class="jqm-version"></span></p>
<p>Copyright 2014 The jQuery Foundation</p>
</div><!-- /footer -->
<!-- TODO: This should become an external panel so we can add input to markup (unique ID) -->
<div data-role="panel" class="jqm-search-panel" data-position="right" data-display="overlay" data-theme="a">
<div class="jqm-search">
<ul class="jqm-list" data-filter-placeholder="Search demos..." data-filter-reveal="true">
<li data-filtertext="demos homepage" data-icon="home"><a href=".././">Home</a></li>
<li data-filtertext="introduction overview getting started"><a href="../intro/" data-ajax="false">Introduction</a></li>
<li data-filtertext="buttons button markup buttonmarkup method anchor link button element"><a href="../button-markup/" data-ajax="false">Buttons</a></li>
<li data-filtertext="form button widget input button submit reset"><a href="../button/" data-ajax="false">Button widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Checkboxradio widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups"><a href="../checkboxradio-checkbox/" data-ajax="false">Checkboxes</a></li>
<li data-filtertext="form checkboxradio widget radio input radio buttons controlgroups"><a href="../checkboxradio-radio/" data-ajax="false">Radio buttons</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Collapsible (set) widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="collapsibles content formatting"><a href="../collapsible/" data-ajax="false">Collapsible</a></li>
<li data-filtertext="dynamic collapsible set accordion append expand"><a href="../collapsible-dynamic/" data-ajax="false">Dynamic collapsibles</a></li>
<li data-filtertext="accordions collapsible set widget content formatting grouped collapsibles"><a href="../collapsibleset/" data-ajax="false">Collapsible set</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Controlgroup widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="controlgroups selectmenu checkboxradio input grouped buttons horizontal vertical"><a href="../controlgroup/" data-ajax="false">Controlgroup</a></li>
<li data-filtertext="dynamic controlgroup dynamically add buttons"><a href="../controlgroup-dynamic/" data-ajax="false">Dynamic controlgroups</a></li>
</ul>
</div>
</li>
<li data-filtertext="form datepicker widget date input"><a href="../datepicker/" data-ajax="false">Datepicker</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Events<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="swipe to delete list items listviews swipe events"><a href="../swipe-list/" data-ajax="false">Swipe list items</a></li>
<li data-filtertext="swipe to navigate swipe page navigation swipe events"><a href="../swipe-page/" data-ajax="false">Swipe page navigation</a></li>
</ul>
</div>
</li>
<li data-filtertext="filterable filter elements sorting searching listview table"><a href="../filterable/" data-ajax="false">Filterable widget</a></li>
<li data-filtertext="form flipswitch widget flip toggle switch binary select checkbox input"><a href="../flipswitch/" data-ajax="false">Flipswitch widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Forms<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms/" data-ajax="false">Forms</a></li>
<li data-filtertext="form hide labels hidden accessible ui-hidden-accessible forms"><a href="../forms-label-hidden-accessible/" data-ajax="false">Hide labels</a></li>
<li data-filtertext="form field containers fieldcontain ui-field-contain forms"><a href="../forms-field-contain/" data-ajax="false">Field containers</a></li>
<li data-filtertext="forms disabled form elements"><a href="../forms-disabled/" data-ajax="false">Forms disabled</a></li>
<li data-filtertext="forms gallery examples overview forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms-gallery/" data-ajax="false">Forms gallery</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Grids<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="grids columns blocks content formatting rwd responsive css framework"><a href="../grids/" data-ajax="false">Grids</a></li>
<li data-filtertext="buttons in grids css framework"><a href="../grids-buttons/" data-ajax="false">Buttons in grids</a></li>
<li data-filtertext="custom responsive grids rwd css framework"><a href="../grids-custom-responsive/" data-ajax="false">Custom responsive grids</a></li>
</ul>
</div>
</li>
<li data-filtertext="blocks content formatting sections heading"><a href="../body-bar-classes/" data-ajax="false">Grouping and dividing content</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Icons<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="button icons svg disc alt custom icon position"><a href="../icons/" data-ajax="false">Icons</a></li>
<li data-filtertext=""><a href="../icons-grunticon/" data-ajax="false">Grunticon loader</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Listview widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="listview widget thumbnails icons nested split button collapsible ul ol"><a href="../listview/" data-ajax="false">Listview</a></li>
<li data-filtertext="autocomplete filterable reveal listview filtertextbeforefilter placeholder"><a href="../listview-autocomplete/" data-ajax="false">Listview autocomplete</a></li>
<li data-filtertext="autocomplete filterable reveal listview remote data filtertextbeforefilter placeholder"><a href="../listview-autocomplete-remote/" data-ajax="false">Listview autocomplete remote data</a></li>
<li data-filtertext="autodividers anchor jump scroll linkbars listview lists ul ol"><a href="../listview-autodividers-linkbar/" data-ajax="false">Listview autodividers linkbar</a></li>
<li data-filtertext="listview autodividers selector autodividersselector lists ul ol"><a href="../listview-autodividers-selector/" data-ajax="false">Listview autodividers selector</a></li>
<li data-filtertext="listview nested list items"><a href="../listview-nested-lists/" data-ajax="false">Nested Listviews</a></li>
<li data-filtertext="listview collapsible list items flat"><a href="../listview-collapsible-item-flat/" data-ajax="false">Listview collapsible list items (flat)</a></li>
<li data-filtertext="listview collapsible list indented"><a href="../listview-collapsible-item-indented/" data-ajax="false">Listview collapsible list items (indented)</a></li>
<li data-filtertext="grid listview responsive grids responsive listviews lists ul"><a href="../listview-grid/" data-ajax="false">Listview responsive grid</a></li>
</ul>
</div>
</li>
<li data-filtertext="loader widget page loading navigation overlay spinner"><a href="../loader/" data-ajax="false">Loader widget</a></li>
<li data-filtertext="navbar widget navmenu toolbars header footer"><a href="../navbar/" data-ajax="false">Navbar widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Navigation<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="ajax navigation navigate widget history event method"><a href="../navigation/" data-ajax="false">Navigation</a></li>
<li data-filtertext="linking pages page links navigation ajax prefetch cache"><a href="../navigation-linking-pages/" data-ajax="false">Linking pages</a></li>
<!-- <li data-filtertext="php redirect server redirection server-side navigation"><a href="../navigation-php-redirect/" data-ajax="false">PHP redirect demo</a></li>-->
<li data-filtertext="navigation redirection hash query"><a href="../navigation-hash-processing/" data-ajax="false">Hash processing demo</a></li>
<li data-filtertext="navigation redirection hash query"><a href="../page-events/" data-ajax="false">Page Navigation Events</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Pages<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="pages page widget ajax navigation"><a href="../pages/" data-ajax="false">Pages</a></li>
<li data-filtertext="single page"><a href="../pages-single-page/" data-ajax="false">Single page</a></li>
<li data-filtertext="multipage multi-page page"><a href="../pages-multi-page/" data-ajax="false">Multi-page template</a></li>
<li data-filtertext="dialog page widget modal popup"><a href="../pages-dialog/" data-ajax="false">Dialog page</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Panel widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="panel widget sliding panels reveal push overlay responsive"><a href="../panel/" data-ajax="false">Panel</a></li>
<li data-filtertext=""><a href="../panel-external/" data-ajax="false">External panels</a></li>
<li data-filtertext="panel "><a href="../panel-fixed/" data-ajax="false">Fixed panels</a></li>
<li data-filtertext="panel slide panels sliding panels shadow rwd responsive breakpoint"><a href="../panel-responsive/" data-ajax="false">Panels responsive</a></li>
<li data-filtertext="panel custom style custom panel width reveal shadow listview panel styling page background wrapper"><a href="../panel-styling/" data-ajax="false">Custom panel style</a></li>
<li data-filtertext="panel open on swipe"><a href="../panel-swipe-open/" data-ajax="false">Panel open on swipe</a></li>
<li data-filtertext="panels outside page internal external toolbars"><a href="../panel-external-internal/" data-ajax="false">Panel external and internal</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Popup widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="popup widget popups dialog modal transition tooltip lightbox form overlay screen flip pop fade transition"><a href="../popup/" data-ajax="false">Popup</a></li>
<li data-filtertext="popup alignment position"><a href="../popup-alignment/" data-ajax="false">Popup alignment</a></li>
<li data-filtertext="popup arrow size popups popover"><a href="../popup-arrow-size/" data-ajax="false">Popup arrow size</a></li>
<li data-filtertext="dynamic popups popup images lightbox"><a href="../popup-dynamic/" data-ajax="false">Dynamic popups</a></li>
<li data-filtertext="popups with iframes scaling"><a href="../popup-iframe/" data-ajax="false">Popups with iframes</a></li>
<li data-filtertext="popup image scaling"><a href="../popup-image-scaling/" data-ajax="false">Popup image scaling</a></li>
<li data-filtertext="external popup outside multi-page"><a href="../popup-outside-multipage/" data-ajax="false">Popup outside multi-page</a></li>
</ul>
</div>
</li>
<li data-filtertext="form rangeslider widget dual sliders dual handle sliders range input"><a href="../rangeslider/" data-ajax="false">Rangeslider widget</a></li>
<li data-filtertext="responsive web design rwd adaptive progressive enhancement PE accessible mobile breakpoints media query media queries"><a href="../rwd/" data-ajax="false">Responsive Web Design</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Selectmenu widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form selectmenu widget select input custom select menu selects"><a href="../selectmenu/" data-ajax="false">Selectmenu</a></li>
<li data-filtertext="form custom select menu selectmenu widget custom menu option optgroup multiple selects"><a href="../selectmenu-custom/" data-ajax="false">Custom select menu</a></li>
<li data-filtertext="filterable select filter popup dialog"><a href="../selectmenu-custom-filter/" data-ajax="false">Custom select menu with filter</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Slider widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="form slider widget range input single sliders"><a href="../slider/" data-ajax="false">Slider</a></li>
<li data-filtertext="form slider widget flipswitch slider binary select flip toggle switch"><a href="../slider-flipswitch/" data-ajax="false">Slider flip toggle switch</a></li>
<li data-filtertext="form slider tooltip handle value input range sliders"><a href="../slider-tooltip/" data-ajax="false">Slider tooltip</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Table widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="table widget reflow column toggle th td responsive tables rwd hide show tabular"><a href="../table-column-toggle/" data-ajax="false">Table Column Toggle</a></li>
<li data-filtertext="table column toggle phone comparison demo"><a href="../table-column-toggle-example/" data-ajax="false">Table Column Toggle demo</a></li>
<li data-filtertext="responsive tables table column toggle heading groups rwd breakpoint"><a href="../table-column-toggle-heading-groups/" data-ajax="false">Table Column Toggle heading groups</a></li>
<li data-filtertext="responsive tables table column toggle hide rwd breakpoint customization options"><a href="../table-column-toggle-options/" data-ajax="false">Table Column Toggle options</a></li>
<li data-filtertext="table reflow th td responsive rwd columns tabular"><a href="../table-reflow/" data-ajax="false">Table Reflow</a></li>
<li data-filtertext="responsive tables table reflow heading groups rwd breakpoint"><a href="../table-reflow-heading-groups/" data-ajax="false">Table Reflow heading groups</a></li>
<li data-filtertext="responsive tables table reflow stripes strokes table style"><a href="../table-reflow-stripes-strokes/" data-ajax="false">Table Reflow stripes and strokes</a></li>
<li data-filtertext="responsive tables table reflow stack custom styles"><a href="../table-reflow-styling/" data-ajax="false">Table Reflow custom styles</a></li>
</ul>
</div>
</li>
<li data-filtertext="ui tabs widget"><a href="../tabs/" data-ajax="false">Tabs widget</a></li>
<li data-filtertext="form textinput widget text input textarea number date time tel email file color password"><a href="../textinput/" data-ajax="false">Textinput widget</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Theming<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="default theme swatches theming style css"><a href="../theme-default/" data-ajax="false">Default theme</a></li>
<li data-filtertext="classic theme old theme swatches theming style css"><a href="../theme-classic/" data-ajax="false">Classic theme</a></li>
</ul>
</div>
</li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
Toolbar widget<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="toolbar widget header footer toolbars fixed fullscreen external sections"><a href="../toolbar/" data-ajax="false">Toolbar</a></li>
<li data-filtertext="dynamic toolbars dynamically add toolbar header footer"><a href="../toolbar-dynamic/" data-ajax="false">Dynamic toolbars</a></li>
<li data-filtertext="external toolbars header footer"><a href="../toolbar-external/" data-ajax="false">External toolbars</a></li>
<li data-filtertext="fixed toolbars header footer"><a href="../toolbar-fixed/" data-ajax="false">Fixed toolbars</a></li>
<li data-filtertext="fixed fullscreen toolbars header footer"><a href="../toolbar-fixed-fullscreen/" data-ajax="false">Fullscreen toolbars</a></li>
<li data-filtertext="external fixed toolbars header footer"><a href="../toolbar-fixed-external/" data-ajax="false">Fixed external toolbars</a></li>
<li data-filtertext="external persistent toolbars header footer navbar navmenu"><a href="../toolbar-fixed-persistent/" data-ajax="false">Persistent toolbars</a></li>
<li data-filtertext="external ajax optimized toolbars persistent toolbars header footer navbar"><a href="../toolbar-fixed-persistent-optimized/" data-ajax="false">Ajax optimized toolbars</a></li>
<li data-filtertext="form in toolbars header footer"><a href="../toolbar-fixed-forms/" data-ajax="false">Form in toolbar</a></li>
</ul>
</div>
</li>
<li data-filtertext="page transitions animated pages popup navigation flip slide fade pop"><a href="../transitions/" data-ajax="false">Transitions</a></li>
<li data-role="collapsible" data-enhanced="true" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false" class="ui-collapsible ui-collapsible-themed-content ui-collapsible-collapsed">
<h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed">
<a href="#" class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-right ui-btn-inherit ui-icon-carat-d">
3rd party API demos<span class="ui-collapsible-heading-status"> click to expand contents</span>
</a>
</h3>
<div class="ui-collapsible-content ui-body-inherit ui-collapsible-content-collapsed" aria-hidden="true">
<ul>
<li data-filtertext="backbone requirejs navigation router"><a href="../backbone-requirejs/" data-ajax="false">Backbone RequireJS</a></li>
<li data-filtertext="google maps geolocation demo"><a href="../map-geolocation/" data-ajax="false">Google Maps geolocation</a></li>
<li data-filtertext="google maps hybrid"><a href="../map-list-toggle/" data-ajax="false">Google Maps list toggle</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div><!-- /panel -->
</div><!-- /page -->
</body>
</html>
|
bhabanism/Threatmeter
|
www/js/vendor/jquery.mobile-1.4.5/demos/page-events/alertevents-3.php
|
PHP
|
bsd-3-clause
| 54,637
|
/*
* Copyright 2012-2014 the original author or 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 org.springframework.boot.configurationsample.method;
import org.springframework.boot.configurationsample.ConfigurationProperties;
/**
* Sample for testing invalid method configuration.
*
* @author Stephane Nicoll
*/
@ConfigurationProperties(prefix = "something")
public class InvalidMethodConfig {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@ConfigurationProperties(prefix = "invalid")
InvalidMethodConfig foo() {
return new InvalidMethodConfig();
}
}
|
rokn/Count_Words_2015
|
testing/spring-boot-master/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/method/InvalidMethodConfig.java
|
Java
|
mit
| 1,186
|
/* Alpha VMS external format of Extended Global Symbol Directory.
Copyright 2010 Free Software Foundation, Inc.
Written by Tristan Gingold <gingold@adacore.com>, AdaCore.
This file is part of BFD, the Binary File Descriptor library.
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 3 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., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#ifndef _VMS_EGSD_H
#define _VMS_EGSD_H
#define EGSD__K_ENTRIES 2 /* Offset to first entry in record. */
#define EGSD__C_ENTRIES 2 /* Offset to first entry in record. */
#define EGSD__C_PSC 0 /* Psect definition. */
#define EGSD__C_SYM 1 /* Symbol specification. */
#define EGSD__C_IDC 2 /* Random entity check. */
#define EGSD__C_SPSC 5 /* Shareable image psect definition. */
#define EGSD__C_SYMV 6 /* Vectored (dual-valued) versions of SYM. */
#define EGSD__C_SYMM 7 /* Masked versions of SYM. */
#define EGSD__C_SYMG 8 /* EGST - gst version of SYM. */
#define EGSD__C_MAXRECTYP 8 /* Maximum entry type defined. */
struct vms_egsd
{
/* Record type. */
unsigned char rectyp[2];
/* Record size. */
unsigned char recsiz[2];
/* Padding for alignment. */
unsigned char alignlw[4];
/* Followed by egsd entries. */
};
struct vms_egsd_entry
{
/* Entry type. */
unsigned char gsdtyp[2];
/* Length of the entry. */
unsigned char gsdsiz[2];
};
#endif /* _VMS_EGSD_H */
|
GarethNelson/Zoidberg
|
userland/newlib/include/vms/egsd.h
|
C
|
gpl-2.0
| 1,981
|
.highlight .hll { background-color: #ffc; }
.highlight .c { color: #999; } /* Comment */
.highlight .err { color: #a00; background-color: #faa } /* Error */
.highlight .k { color: #069; } /* Keyword */
.highlight .o { color: #555 } /* Operator */
.highlight .cm { color: #09f; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #099 } /* Comment.Preproc */
.highlight .c1 { color: #999; } /* Comment.Single */
.highlight .cs { color: #999; } /* Comment.Special */
.highlight .gd { background-color: #fcc; border: 1px solid #c00 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #f00 } /* Generic.Error */
.highlight .gh { color: #030; } /* Generic.Heading */
.highlight .gi { background-color: #cfc; border: 1px solid #0c0 } /* Generic.Inserted */
.highlight .go { color: #aaa } /* Generic.Output */
.highlight .gp { color: #009; } /* Generic.Prompt */
.highlight .gs { } /* Generic.Strong */
.highlight .gu { color: #030; } /* Generic.Subheading */
.highlight .gt { color: #9c6 } /* Generic.Traceback */
.highlight .kc { color: #069; } /* Keyword.Constant */
.highlight .kd { color: #069; } /* Keyword.Declaration */
.highlight .kn { color: #069; } /* Keyword.Namespace */
.highlight .kp { color: #069 } /* Keyword.Pseudo */
.highlight .kr { color: #069; } /* Keyword.Reserved */
.highlight .kt { color: #078; } /* Keyword.Type */
.highlight .m { color: #f60 } /* Literal.Number */
.highlight .s { color: #d44950 } /* Literal.String */
.highlight .na { color: #4f9fcf } /* Name.Attribute */
.highlight .nb { color: #366 } /* Name.Builtin */
.highlight .nc { color: #0a8; } /* Name.Class */
.highlight .no { color: #360 } /* Name.Constant */
.highlight .nd { color: #99f } /* Name.Decorator */
.highlight .ni { color: #999; } /* Name.Entity */
.highlight .ne { color: #c00; } /* Name.Exception */
.highlight .nf { color: #c0f } /* Name.Function */
.highlight .nl { color: #99f } /* Name.Label */
.highlight .nn { color: #0cf; } /* Name.Namespace */
.highlight .nt { color: #2f6f9f; } /* Name.Tag */
.highlight .nv { color: #033 } /* Name.Variable */
.highlight .ow { color: #000; } /* Operator.Word */
.highlight .w { color: #bbb } /* Text.Whitespace */
.highlight .mf { color: #f60 } /* Literal.Number.Float */
.highlight .mh { color: #f60 } /* Literal.Number.Hex */
.highlight .mi { color: #f60 } /* Literal.Number.Integer */
.highlight .mo { color: #f60 } /* Literal.Number.Oct */
.highlight .sb { color: #c30 } /* Literal.String.Backtick */
.highlight .sc { color: #c30 } /* Literal.String.Char */
.highlight .sd { color: #c30; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #c30 } /* Literal.String.Double */
.highlight .se { color: #c30; } /* Literal.String.Escape */
.highlight .sh { color: #c30 } /* Literal.String.Heredoc */
.highlight .si { color: #a00 } /* Literal.String.Interpol */
.highlight .sx { color: #c30 } /* Literal.String.Other */
.highlight .sr { color: #3aa } /* Literal.String.Regex */
.highlight .s1 { color: #c30 } /* Literal.String.Single */
.highlight .ss { color: #fc3 } /* Literal.String.Symbol */
.highlight .bp { color: #366 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #033 } /* Name.Variable.Class */
.highlight .vg { color: #033 } /* Name.Variable.Global */
.highlight .vi { color: #033 } /* Name.Variable.Instance */
.highlight .il { color: #f60 } /* Literal.Number.Integer.Long */
.css .o,
.css .o + .nt,
.css .nt + .nt { color: #999; }
|
danmiley/danmiley.github.io
|
www/public/css/syntax.css
|
CSS
|
mit
| 3,479
|
#include <linux/i2c.h>
#include <linux/sii8240.h>
#include "../../video/edid.h"
struct sii8240_platform_data *platform_init_data(struct i2c_client *client);
/*
int platform_ap_hdmi_hdcp_auth(struct sii8240_data *sii8240);
void platform_mhl_hpd_handler(bool value);
bool platform_hdmi_hpd_status(void);
*/
|
SM-G920P/G920P-MM
|
drivers/video/mhl/sii8240/sii8240_platform.h
|
C
|
gpl-2.0
| 307
|
<?php
/*
* $Id: Interface.php 3882 2008-02-22 18:11:35Z jwage $
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Driver;
/**
* The PDO implementation of the Statement interface.
* Used by all PDO-based drivers.
*
* @since 2.0
*/
class PDOStatement extends \PDOStatement implements Statement
{
private function __construct() {}
public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
{
// This thin wrapper is necessary to shield against the weird signature
// of PDOStatement::setFetchMode(): even if the second and third
// parameters are optional, PHP will not let us remove it from this
// declaration.
if ($arg2 === null && $arg3 === null) {
return parent::setFetchMode($fetchMode);
}
if ($arg3 === null) {
return parent::setFetchMode($fetchMode, $arg2);
}
return parent::setFetchMode($fetchMode, $arg2, $arg3);
}
}
|
Althenar/library
|
www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php
|
PHP
|
gpl-3.0
| 1,914
|
/* Copyright (c) 2012, The Linux Foundation. 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.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/bug.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/device.h>
#include <linux/notifier.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <mach/socinfo.h>
#include <mach/msm_smd.h>
#include <mach/rpm-smd.h>
#define CREATE_TRACE_POINTS
#include <mach/trace_rpm_smd.h>
#include "rpm-notifier.h"
/* Debug Definitions */
enum {
MSM_RPM_LOG_REQUEST_PRETTY = BIT(0),
MSM_RPM_LOG_REQUEST_RAW = BIT(1),
MSM_RPM_LOG_REQUEST_SHOW_MSG_ID = BIT(2),
};
static int msm_rpm_debug_mask;
module_param_named(
debug_mask, msm_rpm_debug_mask, int, S_IRUGO | S_IWUSR
);
struct msm_rpm_driver_data {
const char *ch_name;
uint32_t ch_type;
smd_channel_t *ch_info;
struct work_struct work;
spinlock_t smd_lock_write;
spinlock_t smd_lock_read;
struct completion smd_open;
};
#define DEFAULT_BUFFER_SIZE 256
#define GFP_FLAG(noirq) (noirq ? GFP_ATOMIC : GFP_KERNEL)
#define INV_RSC "resource does not exist"
#define ERR "err\0"
#define MAX_ERR_BUFFER_SIZE 128
#define INIT_ERROR 1
static ATOMIC_NOTIFIER_HEAD(msm_rpm_sleep_notifier);
static bool standalone;
int msm_rpm_register_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&msm_rpm_sleep_notifier, nb);
}
int msm_rpm_unregister_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&msm_rpm_sleep_notifier, nb);
}
static struct workqueue_struct *msm_rpm_smd_wq;
enum {
MSM_RPM_MSG_REQUEST_TYPE = 0,
MSM_RPM_MSG_TYPE_NR,
};
static const uint32_t msm_rpm_request_service[MSM_RPM_MSG_TYPE_NR] = {
0x716572, /* 'req\0' */
};
/*the order of fields matter and reflect the order expected by the RPM*/
struct rpm_request_header {
uint32_t service_type;
uint32_t request_len;
};
struct rpm_message_header {
uint32_t msg_id;
enum msm_rpm_set set;
uint32_t resource_type;
uint32_t resource_id;
uint32_t data_len;
};
struct msm_rpm_kvp_data {
uint32_t key;
uint32_t nbytes; /* number of bytes */
uint8_t *value;
bool valid;
};
static atomic_t msm_rpm_msg_id = ATOMIC_INIT(0);
static struct msm_rpm_driver_data msm_rpm_data;
struct msm_rpm_request {
struct rpm_request_header req_hdr;
struct rpm_message_header msg_hdr;
struct msm_rpm_kvp_data *kvp;
uint32_t num_elements;
uint32_t write_idx;
uint8_t *buf;
uint32_t numbytes;
};
/*
* Data related to message acknowledgement
*/
LIST_HEAD(msm_rpm_wait_list);
struct msm_rpm_wait_data {
struct list_head list;
uint32_t msg_id;
bool ack_recd;
int errno;
struct completion ack;
};
DEFINE_SPINLOCK(msm_rpm_list_lock);
struct msm_rpm_ack_msg {
uint32_t req;
uint32_t req_len;
uint32_t rsc_id;
uint32_t msg_len;
uint32_t id_ack;
};
static int irq_process;
LIST_HEAD(msm_rpm_ack_list);
static void msm_rpm_notify_sleep_chain(struct rpm_message_header *hdr,
struct msm_rpm_kvp_data *kvp)
{
struct msm_rpm_notifier_data notif;
notif.rsc_type = hdr->resource_type;
notif.rsc_id = hdr->resource_id;
notif.key = kvp->key;
notif.size = kvp->nbytes;
notif.value = kvp->value;
atomic_notifier_call_chain(&msm_rpm_sleep_notifier, 0, ¬if);
}
static int msm_rpm_add_kvp_data_common(struct msm_rpm_request *handle,
uint32_t key, const uint8_t *data, int size, bool noirq)
{
int i;
int data_size, msg_size;
if (!handle) {
pr_err("%s(): Invalid handle\n", __func__);
return -EINVAL;
}
data_size = ALIGN(size, SZ_4);
msg_size = data_size + sizeof(struct rpm_request_header);
for (i = 0; i < handle->write_idx; i++) {
if (handle->kvp[i].key != key)
continue;
if (handle->kvp[i].nbytes != data_size) {
kfree(handle->kvp[i].value);
handle->kvp[i].value = NULL;
} else {
if (!memcmp(handle->kvp[i].value, data, data_size))
return 0;
}
break;
}
if (i >= handle->num_elements) {
pr_err("%s(): Number of resources exceeds max allocated\n",
__func__);
return -ENOMEM;
}
if (i == handle->write_idx)
handle->write_idx++;
if (!handle->kvp[i].value) {
handle->kvp[i].value = kzalloc(data_size, GFP_FLAG(noirq));
if (!handle->kvp[i].value) {
pr_err("%s(): Failed malloc\n", __func__);
return -ENOMEM;
}
} else {
/* We enter the else case, if a key already exists but the
* data doesn't match. In which case, we should zero the data
* out.
*/
memset(handle->kvp[i].value, 0, data_size);
}
if (!handle->kvp[i].valid)
handle->msg_hdr.data_len += msg_size;
else
handle->msg_hdr.data_len += (data_size - handle->kvp[i].nbytes);
handle->kvp[i].nbytes = data_size;
handle->kvp[i].key = key;
memcpy(handle->kvp[i].value, data, size);
handle->kvp[i].valid = true;
if (handle->msg_hdr.set == MSM_RPM_CTX_SLEEP_SET)
msm_rpm_notify_sleep_chain(&handle->msg_hdr, &handle->kvp[i]);
return 0;
}
static struct msm_rpm_request *msm_rpm_create_request_common(
enum msm_rpm_set set, uint32_t rsc_type, uint32_t rsc_id,
int num_elements, bool noirq)
{
struct msm_rpm_request *cdata;
cdata = kzalloc(sizeof(struct msm_rpm_request),
GFP_FLAG(noirq));
if (!cdata) {
printk(KERN_INFO"%s():Cannot allocate memory for client data\n",
__func__);
goto cdata_alloc_fail;
}
cdata->msg_hdr.set = set;
cdata->msg_hdr.resource_type = rsc_type;
cdata->msg_hdr.resource_id = rsc_id;
cdata->msg_hdr.data_len = 0;
cdata->num_elements = num_elements;
cdata->write_idx = 0;
cdata->kvp = kzalloc(sizeof(struct msm_rpm_kvp_data) * num_elements,
GFP_FLAG(noirq));
if (!cdata->kvp) {
pr_warn("%s(): Cannot allocate memory for key value data\n",
__func__);
goto kvp_alloc_fail;
}
cdata->buf = kzalloc(DEFAULT_BUFFER_SIZE, GFP_FLAG(noirq));
if (!cdata->buf)
goto buf_alloc_fail;
cdata->numbytes = DEFAULT_BUFFER_SIZE;
return cdata;
buf_alloc_fail:
kfree(cdata->kvp);
kvp_alloc_fail:
kfree(cdata);
cdata_alloc_fail:
return NULL;
}
void msm_rpm_free_request(struct msm_rpm_request *handle)
{
int i;
if (!handle)
return;
for (i = 0; i < handle->write_idx; i++)
kfree(handle->kvp[i].value);
kfree(handle->kvp);
kfree(handle);
}
EXPORT_SYMBOL(msm_rpm_free_request);
struct msm_rpm_request *msm_rpm_create_request(
enum msm_rpm_set set, uint32_t rsc_type,
uint32_t rsc_id, int num_elements)
{
return msm_rpm_create_request_common(set, rsc_type, rsc_id,
num_elements, false);
}
EXPORT_SYMBOL(msm_rpm_create_request);
struct msm_rpm_request *msm_rpm_create_request_noirq(
enum msm_rpm_set set, uint32_t rsc_type,
uint32_t rsc_id, int num_elements)
{
return msm_rpm_create_request_common(set, rsc_type, rsc_id,
num_elements, true);
}
EXPORT_SYMBOL(msm_rpm_create_request_noirq);
int msm_rpm_add_kvp_data(struct msm_rpm_request *handle,
uint32_t key, const uint8_t *data, int size)
{
return msm_rpm_add_kvp_data_common(handle, key, data, size, false);
}
EXPORT_SYMBOL(msm_rpm_add_kvp_data);
int msm_rpm_add_kvp_data_noirq(struct msm_rpm_request *handle,
uint32_t key, const uint8_t *data, int size)
{
return msm_rpm_add_kvp_data_common(handle, key, data, size, true);
}
EXPORT_SYMBOL(msm_rpm_add_kvp_data_noirq);
/* Runs in interrupt context */
static void msm_rpm_notify(void *data, unsigned event)
{
struct msm_rpm_driver_data *pdata = (struct msm_rpm_driver_data *)data;
BUG_ON(!pdata);
if (!(pdata->ch_info))
return;
switch (event) {
case SMD_EVENT_DATA:
queue_work(msm_rpm_smd_wq, &pdata->work);
break;
case SMD_EVENT_OPEN:
complete(&pdata->smd_open);
break;
case SMD_EVENT_CLOSE:
case SMD_EVENT_STATUS:
case SMD_EVENT_REOPEN_READY:
break;
default:
pr_info("Unknown SMD event\n");
}
}
static struct msm_rpm_wait_data *msm_rpm_get_entry_from_msg_id(uint32_t msg_id)
{
struct list_head *ptr;
struct msm_rpm_wait_data *elem;
unsigned long flags;
spin_lock_irqsave(&msm_rpm_list_lock, flags);
list_for_each(ptr, &msm_rpm_wait_list) {
elem = list_entry(ptr, struct msm_rpm_wait_data, list);
if (elem && (elem->msg_id == msg_id))
break;
elem = NULL;
}
spin_unlock_irqrestore(&msm_rpm_list_lock, flags);
return elem;
}
static uint32_t msm_rpm_get_next_msg_id(void)
{
uint32_t id;
/*
* A message id of 0 is used by the driver to indicate a error
* condition. The RPM driver uses a id of 1 to indicate unsent data
* when the data sent over hasn't been modified. This isn't a error
* scenario and wait for ack returns a success when the message id is 1.
*/
do {
id = atomic_inc_return(&msm_rpm_msg_id);
} while ((id == 0) || (id == 1) || msm_rpm_get_entry_from_msg_id(id));
return id;
}
static int msm_rpm_add_wait_list(uint32_t msg_id)
{
unsigned long flags;
struct msm_rpm_wait_data *data =
kzalloc(sizeof(struct msm_rpm_wait_data), GFP_ATOMIC);
if (!data)
return -ENOMEM;
init_completion(&data->ack);
data->ack_recd = false;
data->msg_id = msg_id;
data->errno = INIT_ERROR;
spin_lock_irqsave(&msm_rpm_list_lock, flags);
list_add(&data->list, &msm_rpm_wait_list);
spin_unlock_irqrestore(&msm_rpm_list_lock, flags);
return 0;
}
static void msm_rpm_free_list_entry(struct msm_rpm_wait_data *elem)
{
unsigned long flags;
spin_lock_irqsave(&msm_rpm_list_lock, flags);
list_del(&elem->list);
spin_unlock_irqrestore(&msm_rpm_list_lock, flags);
kfree(elem);
}
static void msm_rpm_process_ack(uint32_t msg_id, int errno)
{
struct list_head *ptr;
struct msm_rpm_wait_data *elem;
unsigned long flags;
spin_lock_irqsave(&msm_rpm_list_lock, flags);
list_for_each(ptr, &msm_rpm_wait_list) {
elem = list_entry(ptr, struct msm_rpm_wait_data, list);
if (elem && (elem->msg_id == msg_id)) {
elem->errno = errno;
elem->ack_recd = true;
complete(&elem->ack);
break;
}
elem = NULL;
}
WARN_ON(!elem);
spin_unlock_irqrestore(&msm_rpm_list_lock, flags);
}
struct msm_rpm_kvp_packet {
uint32_t id;
uint32_t len;
uint32_t val;
};
static inline uint32_t msm_rpm_get_msg_id_from_ack(uint8_t *buf)
{
return ((struct msm_rpm_ack_msg *)buf)->id_ack;
}
static inline int msm_rpm_get_error_from_ack(uint8_t *buf)
{
uint8_t *tmp;
uint32_t req_len = ((struct msm_rpm_ack_msg *)buf)->req_len;
int rc = -ENODEV;
req_len -= sizeof(struct msm_rpm_ack_msg);
req_len += 2 * sizeof(uint32_t);
if (!req_len)
return 0;
tmp = buf + sizeof(struct msm_rpm_ack_msg);
BUG_ON(memcmp(tmp, ERR, sizeof(uint32_t)));
tmp += 2 * sizeof(uint32_t);
if (!(memcmp(tmp, INV_RSC, min(req_len, sizeof(INV_RSC))-1))) {
pr_err("%s(): RPM NACK Unsupported resource\n", __func__);
rc = -EINVAL;
} else {
pr_err("%s(): RPM NACK Invalid header\n", __func__);
}
return rc;
}
static int msm_rpm_read_smd_data(char *buf)
{
int pkt_sz;
int bytes_read = 0;
pkt_sz = smd_cur_packet_size(msm_rpm_data.ch_info);
if (!pkt_sz)
return -EAGAIN;
BUG_ON(pkt_sz > MAX_ERR_BUFFER_SIZE);
if (pkt_sz != smd_read_avail(msm_rpm_data.ch_info))
return -EAGAIN;
do {
int len;
len = smd_read(msm_rpm_data.ch_info, buf + bytes_read, pkt_sz);
pkt_sz -= len;
bytes_read += len;
} while (pkt_sz > 0);
BUG_ON(pkt_sz < 0);
return 0;
}
static void msm_rpm_smd_work(struct work_struct *work)
{
uint32_t msg_id;
int errno;
char buf[MAX_ERR_BUFFER_SIZE] = {0};
unsigned long flags;
while (smd_is_pkt_avail(msm_rpm_data.ch_info) && !irq_process) {
spin_lock_irqsave(&msm_rpm_data.smd_lock_read, flags);
if (msm_rpm_read_smd_data(buf)) {
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_read,
flags);
break;
}
msg_id = msm_rpm_get_msg_id_from_ack(buf);
errno = msm_rpm_get_error_from_ack(buf);
msm_rpm_process_ack(msg_id, errno);
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_read, flags);
}
}
#define DEBUG_PRINT_BUFFER_SIZE 512
static void msm_rpm_log_request(struct msm_rpm_request *cdata)
{
char buf[DEBUG_PRINT_BUFFER_SIZE];
size_t buflen = DEBUG_PRINT_BUFFER_SIZE;
char name[5];
u32 value;
int i, j, prev_valid;
int valid_count = 0;
int pos = 0;
name[4] = 0;
for (i = 0; i < cdata->write_idx; i++)
if (cdata->kvp[i].valid)
valid_count++;
pos += scnprintf(buf + pos, buflen - pos, "%sRPM req: ", KERN_INFO);
if (msm_rpm_debug_mask & MSM_RPM_LOG_REQUEST_SHOW_MSG_ID)
pos += scnprintf(buf + pos, buflen - pos, "msg_id=%u, ",
cdata->msg_hdr.msg_id);
pos += scnprintf(buf + pos, buflen - pos, "s=%s",
(cdata->msg_hdr.set == MSM_RPM_CTX_ACTIVE_SET ? "act" : "slp"));
if ((msm_rpm_debug_mask & MSM_RPM_LOG_REQUEST_PRETTY)
&& (msm_rpm_debug_mask & MSM_RPM_LOG_REQUEST_RAW)) {
/* Both pretty and raw formatting */
memcpy(name, &cdata->msg_hdr.resource_type, sizeof(uint32_t));
pos += scnprintf(buf + pos, buflen - pos,
", rsc_type=0x%08X (%s), rsc_id=%u; ",
cdata->msg_hdr.resource_type, name,
cdata->msg_hdr.resource_id);
for (i = 0, prev_valid = 0; i < cdata->write_idx; i++) {
if (!cdata->kvp[i].valid)
continue;
memcpy(name, &cdata->kvp[i].key, sizeof(uint32_t));
pos += scnprintf(buf + pos, buflen - pos,
"[key=0x%08X (%s), value=%s",
cdata->kvp[i].key, name,
(cdata->kvp[i].nbytes ? "0x" : "null"));
for (j = 0; j < cdata->kvp[i].nbytes; j++)
pos += scnprintf(buf + pos, buflen - pos,
"%02X ",
cdata->kvp[i].value[j]);
if (cdata->kvp[i].nbytes)
pos += scnprintf(buf + pos, buflen - pos, "(");
for (j = 0; j < cdata->kvp[i].nbytes; j += 4) {
value = 0;
memcpy(&value, &cdata->kvp[i].value[j],
min(sizeof(uint32_t),
cdata->kvp[i].nbytes - j));
pos += scnprintf(buf + pos, buflen - pos, "%u",
value);
if (j + 4 < cdata->kvp[i].nbytes)
pos += scnprintf(buf + pos,
buflen - pos, " ");
}
if (cdata->kvp[i].nbytes)
pos += scnprintf(buf + pos, buflen - pos, ")");
pos += scnprintf(buf + pos, buflen - pos, "]");
if (prev_valid + 1 < valid_count)
pos += scnprintf(buf + pos, buflen - pos, ", ");
prev_valid++;
}
} else if (msm_rpm_debug_mask & MSM_RPM_LOG_REQUEST_PRETTY) {
/* Pretty formatting only */
memcpy(name, &cdata->msg_hdr.resource_type, sizeof(uint32_t));
pos += scnprintf(buf + pos, buflen - pos, " %s %u; ", name,
cdata->msg_hdr.resource_id);
for (i = 0, prev_valid = 0; i < cdata->write_idx; i++) {
if (!cdata->kvp[i].valid)
continue;
memcpy(name, &cdata->kvp[i].key, sizeof(uint32_t));
pos += scnprintf(buf + pos, buflen - pos, "%s=%s",
name, (cdata->kvp[i].nbytes ? "" : "null"));
for (j = 0; j < cdata->kvp[i].nbytes; j += 4) {
value = 0;
memcpy(&value, &cdata->kvp[i].value[j],
min(sizeof(uint32_t),
cdata->kvp[i].nbytes - j));
pos += scnprintf(buf + pos, buflen - pos, "%u",
value);
if (j + 4 < cdata->kvp[i].nbytes)
pos += scnprintf(buf + pos,
buflen - pos, " ");
}
if (prev_valid + 1 < valid_count)
pos += scnprintf(buf + pos, buflen - pos, ", ");
prev_valid++;
}
} else {
/* Raw formatting only */
pos += scnprintf(buf + pos, buflen - pos,
", rsc_type=0x%08X, rsc_id=%u; ",
cdata->msg_hdr.resource_type,
cdata->msg_hdr.resource_id);
for (i = 0, prev_valid = 0; i < cdata->write_idx; i++) {
if (!cdata->kvp[i].valid)
continue;
pos += scnprintf(buf + pos, buflen - pos,
"[key=0x%08X, value=%s",
cdata->kvp[i].key,
(cdata->kvp[i].nbytes ? "0x" : "null"));
for (j = 0; j < cdata->kvp[i].nbytes; j++) {
pos += scnprintf(buf + pos, buflen - pos,
"%02X",
cdata->kvp[i].value[j]);
if (j + 1 < cdata->kvp[i].nbytes)
pos += scnprintf(buf + pos,
buflen - pos, " ");
}
pos += scnprintf(buf + pos, buflen - pos, "]");
if (prev_valid + 1 < valid_count)
pos += scnprintf(buf + pos, buflen - pos, ", ");
prev_valid++;
}
}
pos += scnprintf(buf + pos, buflen - pos, "\n");
printk(buf);
}
static int msm_rpm_send_data(struct msm_rpm_request *cdata,
int msg_type, bool noirq)
{
uint8_t *tmpbuff;
int i, ret, msg_size;
unsigned long flags;
int req_hdr_sz, msg_hdr_sz;
if (!cdata->msg_hdr.data_len)
return 1;
req_hdr_sz = sizeof(cdata->req_hdr);
msg_hdr_sz = sizeof(cdata->msg_hdr);
cdata->req_hdr.service_type = msm_rpm_request_service[msg_type];
cdata->msg_hdr.msg_id = msm_rpm_get_next_msg_id();
cdata->req_hdr.request_len = cdata->msg_hdr.data_len + msg_hdr_sz;
msg_size = cdata->req_hdr.request_len + req_hdr_sz;
/* populate data_len */
if (msg_size > cdata->numbytes) {
kfree(cdata->buf);
cdata->numbytes = msg_size;
cdata->buf = kzalloc(msg_size, GFP_FLAG(noirq));
}
if (!cdata->buf) {
pr_err("%s(): Failed malloc\n", __func__);
return 0;
}
tmpbuff = cdata->buf;
memcpy(tmpbuff, &cdata->req_hdr, req_hdr_sz + msg_hdr_sz);
tmpbuff += req_hdr_sz + msg_hdr_sz;
for (i = 0; (i < cdata->write_idx); i++) {
/* Sanity check */
BUG_ON((tmpbuff - cdata->buf) > cdata->numbytes);
if (!cdata->kvp[i].valid)
continue;
memcpy(tmpbuff, &cdata->kvp[i].key, sizeof(uint32_t));
tmpbuff += sizeof(uint32_t);
memcpy(tmpbuff, &cdata->kvp[i].nbytes, sizeof(uint32_t));
tmpbuff += sizeof(uint32_t);
memcpy(tmpbuff, cdata->kvp[i].value, cdata->kvp[i].nbytes);
tmpbuff += cdata->kvp[i].nbytes;
}
if (msm_rpm_debug_mask
& (MSM_RPM_LOG_REQUEST_PRETTY | MSM_RPM_LOG_REQUEST_RAW))
msm_rpm_log_request(cdata);
if (standalone) {
for (i = 0; (i < cdata->write_idx); i++)
cdata->kvp[i].valid = false;
cdata->msg_hdr.data_len = 0;
ret = cdata->msg_hdr.msg_id;
return ret;
}
msm_rpm_add_wait_list(cdata->msg_hdr.msg_id);
spin_lock_irqsave(&msm_rpm_data.smd_lock_write, flags);
ret = smd_write_avail(msm_rpm_data.ch_info);
if (ret < 0) {
pr_err("%s(): SMD not initialized\n", __func__);
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_write, flags);
return 0;
}
while ((ret < msg_size)) {
if (!noirq) {
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_write,
flags);
cpu_relax();
spin_lock_irqsave(&msm_rpm_data.smd_lock_write, flags);
} else
udelay(5);
ret = smd_write_avail(msm_rpm_data.ch_info);
}
ret = smd_write(msm_rpm_data.ch_info, &cdata->buf[0], msg_size);
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_write, flags);
if (ret == msg_size) {
for (i = 0; (i < cdata->write_idx); i++)
cdata->kvp[i].valid = false;
cdata->msg_hdr.data_len = 0;
ret = cdata->msg_hdr.msg_id;
} else if (ret < msg_size) {
struct msm_rpm_wait_data *rc;
ret = 0;
pr_err("Failed to write data msg_size:%d ret:%d\n",
msg_size, ret);
rc = msm_rpm_get_entry_from_msg_id(cdata->msg_hdr.msg_id);
if (rc)
msm_rpm_free_list_entry(rc);
}
return ret;
}
int msm_rpm_send_request(struct msm_rpm_request *handle)
{
return msm_rpm_send_data(handle, MSM_RPM_MSG_REQUEST_TYPE, false);
}
EXPORT_SYMBOL(msm_rpm_send_request);
int msm_rpm_send_request_noirq(struct msm_rpm_request *handle)
{
return msm_rpm_send_data(handle, MSM_RPM_MSG_REQUEST_TYPE, true);
}
EXPORT_SYMBOL(msm_rpm_send_request_noirq);
int msm_rpm_wait_for_ack(uint32_t msg_id)
{
struct msm_rpm_wait_data *elem;
if (!msg_id) {
pr_err("%s(): Invalid msg id\n", __func__);
return -ENOMEM;
}
if (msg_id == 1)
return 0;
if (standalone)
return 0;
elem = msm_rpm_get_entry_from_msg_id(msg_id);
if (!elem)
return 0;
wait_for_completion(&elem->ack);
msm_rpm_free_list_entry(elem);
return elem->errno;
}
EXPORT_SYMBOL(msm_rpm_wait_for_ack);
int msm_rpm_wait_for_ack_noirq(uint32_t msg_id)
{
struct msm_rpm_wait_data *elem;
unsigned long flags;
int rc = 0;
uint32_t id = 0;
if (!msg_id) {
pr_err("%s(): Invalid msg id\n", __func__);
return -ENOMEM;
}
if (msg_id == 1)
return 0;
if (standalone)
return 0;
spin_lock_irqsave(&msm_rpm_data.smd_lock_read, flags);
irq_process = true;
elem = msm_rpm_get_entry_from_msg_id(msg_id);
if (!elem)
/* Should this be a bug
* Is it ok for another thread to read the msg?
*/
goto wait_ack_cleanup;
if (elem->errno != INIT_ERROR) {
rc = elem->errno;
msm_rpm_free_list_entry(elem);
goto wait_ack_cleanup;
}
while (id != msg_id) {
if (smd_is_pkt_avail(msm_rpm_data.ch_info)) {
int errno;
char buf[MAX_ERR_BUFFER_SIZE] = {};
msm_rpm_read_smd_data(buf);
id = msm_rpm_get_msg_id_from_ack(buf);
errno = msm_rpm_get_error_from_ack(buf);
msm_rpm_process_ack(id, errno);
}
}
rc = elem->errno;
msm_rpm_free_list_entry(elem);
wait_ack_cleanup:
irq_process = false;
spin_unlock_irqrestore(&msm_rpm_data.smd_lock_read, flags);
return rc;
}
EXPORT_SYMBOL(msm_rpm_wait_for_ack_noirq);
int msm_rpm_send_message(enum msm_rpm_set set, uint32_t rsc_type,
uint32_t rsc_id, struct msm_rpm_kvp *kvp, int nelems)
{
int i, rc;
struct msm_rpm_request *req =
msm_rpm_create_request(set, rsc_type, rsc_id, nelems);
if (!req)
return -ENOMEM;
for (i = 0; i < nelems; i++) {
rc = msm_rpm_add_kvp_data(req, kvp[i].key,
kvp[i].data, kvp[i].length);
if (rc)
goto bail;
}
rc = msm_rpm_wait_for_ack(msm_rpm_send_request(req));
bail:
msm_rpm_free_request(req);
return rc;
}
EXPORT_SYMBOL(msm_rpm_send_message);
int msm_rpm_send_message_noirq(enum msm_rpm_set set, uint32_t rsc_type,
uint32_t rsc_id, struct msm_rpm_kvp *kvp, int nelems)
{
int i, rc;
struct msm_rpm_request *req =
msm_rpm_create_request_noirq(set, rsc_type, rsc_id, nelems);
if (!req)
return -ENOMEM;
for (i = 0; i < nelems; i++) {
rc = msm_rpm_add_kvp_data_noirq(req, kvp[i].key,
kvp[i].data, kvp[i].length);
if (rc)
goto bail;
}
rc = msm_rpm_wait_for_ack_noirq(msm_rpm_send_request_noirq(req));
bail:
msm_rpm_free_request(req);
return rc;
}
EXPORT_SYMBOL(msm_rpm_send_message_noirq);
/**
* During power collapse, the rpm driver disables the SMD interrupts to make
* sure that the interrupt doesn't wakes us from sleep.
*/
int msm_rpm_enter_sleep(void)
{
return smd_mask_receive_interrupt(msm_rpm_data.ch_info, true);
}
EXPORT_SYMBOL(msm_rpm_enter_sleep);
/**
* When the system resumes from power collapse, the SMD interrupt disabled by
* enter function has to reenabled to continue processing SMD message.
*/
void msm_rpm_exit_sleep(void)
{
smd_mask_receive_interrupt(msm_rpm_data.ch_info, false);
}
EXPORT_SYMBOL(msm_rpm_exit_sleep);
static bool msm_rpm_set_standalone(void)
{
if (machine_is_msm8974()) {
pr_warn("%s(): Running in standalone mode, requests "
"will not be sent to RPM\n", __func__);
standalone = true;
}
return standalone;
}
static int __devinit msm_rpm_dev_probe(struct platform_device *pdev)
{
char *key = NULL;
int ret;
key = "rpm-channel-name";
ret = of_property_read_string(pdev->dev.of_node, key,
&msm_rpm_data.ch_name);
if (ret)
goto fail;
key = "rpm-channel-type";
ret = of_property_read_u32(pdev->dev.of_node, key,
&msm_rpm_data.ch_type);
if (ret)
goto fail;
init_completion(&msm_rpm_data.smd_open);
spin_lock_init(&msm_rpm_data.smd_lock_write);
spin_lock_init(&msm_rpm_data.smd_lock_read);
INIT_WORK(&msm_rpm_data.work, msm_rpm_smd_work);
if (smd_named_open_on_edge(msm_rpm_data.ch_name, msm_rpm_data.ch_type,
&msm_rpm_data.ch_info, &msm_rpm_data,
msm_rpm_notify)) {
pr_info("Cannot open RPM channel %s %d\n", msm_rpm_data.ch_name,
msm_rpm_data.ch_type);
msm_rpm_set_standalone();
BUG_ON(!standalone);
complete(&msm_rpm_data.smd_open);
}
wait_for_completion(&msm_rpm_data.smd_open);
smd_disable_read_intr(msm_rpm_data.ch_info);
if (!standalone) {
msm_rpm_smd_wq = create_singlethread_workqueue("rpm-smd");
if (!msm_rpm_smd_wq)
return -EINVAL;
}
of_platform_populate(pdev->dev.of_node, NULL, NULL, &pdev->dev);
return 0;
fail:
pr_err("%s(): Failed to read node: %s, key=%s\n", __func__,
pdev->dev.of_node->full_name, key);
return -EINVAL;
}
static struct of_device_id msm_rpm_match_table[] = {
{.compatible = "qcom,rpm-smd"},
{},
};
static struct platform_driver msm_rpm_device_driver = {
.probe = msm_rpm_dev_probe,
.driver = {
.name = "rpm-smd",
.owner = THIS_MODULE,
.of_match_table = msm_rpm_match_table,
},
};
int __init msm_rpm_driver_init(void)
{
static bool registered;
if (registered)
return 0;
registered = true;
return platform_driver_register(&msm_rpm_device_driver);
}
EXPORT_SYMBOL(msm_rpm_driver_init);
late_initcall(msm_rpm_driver_init);
|
AOSP-JF/platform_kernel_samsung_jf
|
arch/arm/mach-msm/rpm-smd.c
|
C
|
gpl-2.0
| 24,854
|
/*
* Freescale MMA9553L Intelligent Pedometer driver
* Copyright (c) 2014, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/gpio/consumer.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/events.h>
#include <linux/pm_runtime.h>
#include "mma9551_core.h"
#define MMA9553_DRV_NAME "mma9553"
#define MMA9553_IRQ_NAME "mma9553_event"
#define MMA9553_GPIO_NAME "mma9553_int"
/* Pedometer configuration registers (R/W) */
#define MMA9553_REG_CONF_SLEEPMIN 0x00
#define MMA9553_REG_CONF_SLEEPMAX 0x02
#define MMA9553_REG_CONF_SLEEPTHD 0x04
#define MMA9553_MASK_CONF_WORD GENMASK(15, 0)
#define MMA9553_REG_CONF_CONF_STEPLEN 0x06
#define MMA9553_MASK_CONF_CONFIG BIT(15)
#define MMA9553_MASK_CONF_ACT_DBCNTM BIT(14)
#define MMA9553_MASK_CONF_SLP_DBCNTM BIT(13)
#define MMA9553_MASK_CONF_STEPLEN GENMASK(7, 0)
#define MMA9553_REG_CONF_HEIGHT_WEIGHT 0x08
#define MMA9553_MASK_CONF_HEIGHT GENMASK(15, 8)
#define MMA9553_MASK_CONF_WEIGHT GENMASK(7, 0)
#define MMA9553_REG_CONF_FILTER 0x0A
#define MMA9553_MASK_CONF_FILTSTEP GENMASK(15, 8)
#define MMA9553_MASK_CONF_MALE BIT(7)
#define MMA9553_MASK_CONF_FILTTIME GENMASK(6, 0)
#define MMA9553_REG_CONF_SPEED_STEP 0x0C
#define MMA9553_MASK_CONF_SPDPRD GENMASK(15, 8)
#define MMA9553_MASK_CONF_STEPCOALESCE GENMASK(7, 0)
#define MMA9553_REG_CONF_ACTTHD 0x0E
#define MMA9553_MAX_ACTTHD GENMASK(15, 0)
/* Pedometer status registers (R-only) */
#define MMA9553_REG_STATUS 0x00
#define MMA9553_MASK_STATUS_MRGFL BIT(15)
#define MMA9553_MASK_STATUS_SUSPCHG BIT(14)
#define MMA9553_MASK_STATUS_STEPCHG BIT(13)
#define MMA9553_MASK_STATUS_ACTCHG BIT(12)
#define MMA9553_MASK_STATUS_SUSP BIT(11)
#define MMA9553_MASK_STATUS_ACTIVITY GENMASK(10, 8)
#define MMA9553_MASK_STATUS_VERSION GENMASK(7, 0)
#define MMA9553_REG_STEPCNT 0x02
#define MMA9553_REG_DISTANCE 0x04
#define MMA9553_REG_SPEED 0x06
#define MMA9553_REG_CALORIES 0x08
#define MMA9553_REG_SLEEPCNT 0x0A
/* Pedometer events are always mapped to this pin. */
#define MMA9553_DEFAULT_GPIO_PIN mma9551_gpio6
#define MMA9553_DEFAULT_GPIO_POLARITY 0
/* Bitnum used for GPIO configuration = bit number in high status byte */
#define MMA9553_STATUS_TO_BITNUM(bit) (ffs(bit) - 9)
#define MMA9553_MAX_BITNUM MMA9553_STATUS_TO_BITNUM(BIT(16))
#define MMA9553_DEFAULT_SAMPLE_RATE 30 /* Hz */
/*
* The internal activity level must be stable for ACTTHD samples before
* ACTIVITY is updated. The ACTIVITY variable contains the current activity
* level and is updated every time a step is detected or once a second
* if there are no steps.
*/
#define MMA9553_ACTIVITY_THD_TO_SEC(thd) ((thd) / MMA9553_DEFAULT_SAMPLE_RATE)
#define MMA9553_ACTIVITY_SEC_TO_THD(sec) ((sec) * MMA9553_DEFAULT_SAMPLE_RATE)
/*
* Autonomously suspend pedometer if acceleration vector magnitude
* is near 1g (4096 at 0.244 mg/LSB resolution) for 30 seconds.
*/
#define MMA9553_DEFAULT_SLEEPMIN 3688 /* 0,9 g */
#define MMA9553_DEFAULT_SLEEPMAX 4508 /* 1,1 g */
#define MMA9553_DEFAULT_SLEEPTHD (MMA9553_DEFAULT_SAMPLE_RATE * 30)
#define MMA9553_CONFIG_RETRIES 2
/* Status register - activity field */
enum activity_level {
ACTIVITY_UNKNOWN,
ACTIVITY_REST,
ACTIVITY_WALKING,
ACTIVITY_JOGGING,
ACTIVITY_RUNNING,
};
static struct mma9553_event_info {
enum iio_chan_type type;
enum iio_modifier mod;
enum iio_event_direction dir;
} mma9553_events_info[] = {
{
.type = IIO_STEPS,
.mod = IIO_NO_MOD,
.dir = IIO_EV_DIR_NONE,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_STILL,
.dir = IIO_EV_DIR_RISING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_STILL,
.dir = IIO_EV_DIR_FALLING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_WALKING,
.dir = IIO_EV_DIR_RISING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_WALKING,
.dir = IIO_EV_DIR_FALLING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_JOGGING,
.dir = IIO_EV_DIR_RISING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_JOGGING,
.dir = IIO_EV_DIR_FALLING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_RUNNING,
.dir = IIO_EV_DIR_RISING,
},
{
.type = IIO_ACTIVITY,
.mod = IIO_MOD_RUNNING,
.dir = IIO_EV_DIR_FALLING,
},
};
#define MMA9553_EVENTS_INFO_SIZE ARRAY_SIZE(mma9553_events_info)
struct mma9553_event {
struct mma9553_event_info *info;
bool enabled;
};
struct mma9553_conf_regs {
u16 sleepmin;
u16 sleepmax;
u16 sleepthd;
u16 config;
u16 height_weight;
u16 filter;
u16 speed_step;
u16 actthd;
} __packed;
struct mma9553_data {
struct i2c_client *client;
/*
* 1. Serialize access to HW (requested by mma9551_core API).
* 2. Serialize sequences that power on/off the device and access HW.
*/
struct mutex mutex;
struct mma9553_conf_regs conf;
struct mma9553_event events[MMA9553_EVENTS_INFO_SIZE];
int num_events;
u8 gpio_bitnum;
/*
* This is used for all features that depend on step count:
* step count, distance, speed, calories.
*/
bool stepcnt_enabled;
u16 stepcnt;
u8 activity;
s64 timestamp;
};
static u8 mma9553_get_bits(u16 val, u16 mask)
{
return (val & mask) >> (ffs(mask) - 1);
}
static u16 mma9553_set_bits(u16 current_val, u16 val, u16 mask)
{
return (current_val & ~mask) | (val << (ffs(mask) - 1));
}
static enum iio_modifier mma9553_activity_to_mod(enum activity_level activity)
{
switch (activity) {
case ACTIVITY_RUNNING:
return IIO_MOD_RUNNING;
case ACTIVITY_JOGGING:
return IIO_MOD_JOGGING;
case ACTIVITY_WALKING:
return IIO_MOD_WALKING;
case ACTIVITY_REST:
return IIO_MOD_STILL;
case ACTIVITY_UNKNOWN:
default:
return IIO_NO_MOD;
}
}
static void mma9553_init_events(struct mma9553_data *data)
{
int i;
data->num_events = MMA9553_EVENTS_INFO_SIZE;
for (i = 0; i < data->num_events; i++) {
data->events[i].info = &mma9553_events_info[i];
data->events[i].enabled = false;
}
}
static struct mma9553_event *mma9553_get_event(struct mma9553_data *data,
enum iio_chan_type type,
enum iio_modifier mod,
enum iio_event_direction dir)
{
int i;
for (i = 0; i < data->num_events; i++)
if (data->events[i].info->type == type &&
data->events[i].info->mod == mod &&
data->events[i].info->dir == dir)
return &data->events[i];
return NULL;
}
static bool mma9553_is_any_event_enabled(struct mma9553_data *data,
bool check_type,
enum iio_chan_type type)
{
int i;
for (i = 0; i < data->num_events; i++)
if ((check_type && data->events[i].info->type == type &&
data->events[i].enabled) ||
(!check_type && data->events[i].enabled))
return true;
return false;
}
static int mma9553_set_config(struct mma9553_data *data, u16 reg,
u16 *p_reg_val, u16 val, u16 mask)
{
int ret, retries;
u16 reg_val, config;
reg_val = *p_reg_val;
if (val == mma9553_get_bits(reg_val, mask))
return 0;
reg_val = mma9553_set_bits(reg_val, val, mask);
ret = mma9551_write_config_word(data->client, MMA9551_APPID_PEDOMETER,
reg, reg_val);
if (ret < 0) {
dev_err(&data->client->dev,
"error writing config register 0x%x\n", reg);
return ret;
}
*p_reg_val = reg_val;
/* Reinitializes the pedometer with current configuration values */
config = mma9553_set_bits(data->conf.config, 1,
MMA9553_MASK_CONF_CONFIG);
ret = mma9551_write_config_word(data->client, MMA9551_APPID_PEDOMETER,
MMA9553_REG_CONF_CONF_STEPLEN, config);
if (ret < 0) {
dev_err(&data->client->dev,
"error writing config register 0x%x\n",
MMA9553_REG_CONF_CONF_STEPLEN);
return ret;
}
retries = MMA9553_CONFIG_RETRIES;
do {
mma9551_sleep(MMA9553_DEFAULT_SAMPLE_RATE);
ret = mma9551_read_config_word(data->client,
MMA9551_APPID_PEDOMETER,
MMA9553_REG_CONF_CONF_STEPLEN,
&config);
if (ret < 0)
return ret;
} while (mma9553_get_bits(config, MMA9553_MASK_CONF_CONFIG) &&
--retries > 0);
return 0;
}
static int mma9553_read_activity_stepcnt(struct mma9553_data *data,
u8 *activity, u16 *stepcnt)
{
u16 buf[2];
int ret;
ret = mma9551_read_status_words(data->client, MMA9551_APPID_PEDOMETER,
MMA9553_REG_STATUS, ARRAY_SIZE(buf),
buf);
if (ret < 0) {
dev_err(&data->client->dev,
"error reading status and stepcnt\n");
return ret;
}
*activity = mma9553_get_bits(buf[0], MMA9553_MASK_STATUS_ACTIVITY);
*stepcnt = buf[1];
return 0;
}
static int mma9553_conf_gpio(struct mma9553_data *data)
{
u8 bitnum = 0, appid = MMA9551_APPID_PEDOMETER;
int ret;
struct mma9553_event *ev_step_detect;
bool activity_enabled;
activity_enabled = mma9553_is_any_event_enabled(data, true,
IIO_ACTIVITY);
ev_step_detect = mma9553_get_event(data, IIO_STEPS, IIO_NO_MOD,
IIO_EV_DIR_NONE);
/*
* If both step detector and activity are enabled, use the MRGFL bit.
* This bit is the logical OR of the SUSPCHG, STEPCHG, and ACTCHG flags.
*/
if (activity_enabled && ev_step_detect->enabled)
bitnum = MMA9553_STATUS_TO_BITNUM(MMA9553_MASK_STATUS_MRGFL);
else if (ev_step_detect->enabled)
bitnum = MMA9553_STATUS_TO_BITNUM(MMA9553_MASK_STATUS_STEPCHG);
else if (activity_enabled)
bitnum = MMA9553_STATUS_TO_BITNUM(MMA9553_MASK_STATUS_ACTCHG);
else /* Reset */
appid = MMA9551_APPID_NONE;
if (data->gpio_bitnum == bitnum)
return 0;
/* Save initial values for activity and stepcnt */
if (activity_enabled || ev_step_detect->enabled) {
ret = mma9553_read_activity_stepcnt(data, &data->activity,
&data->stepcnt);
if (ret < 0)
return ret;
}
ret = mma9551_gpio_config(data->client, MMA9553_DEFAULT_GPIO_PIN, appid,
bitnum, MMA9553_DEFAULT_GPIO_POLARITY);
if (ret < 0)
return ret;
data->gpio_bitnum = bitnum;
return 0;
}
static int mma9553_init(struct mma9553_data *data)
{
int ret;
ret = mma9551_read_version(data->client);
if (ret)
return ret;
/*
* Read all the pedometer configuration registers. This is used as
* a device identification command to differentiate the MMA9553L
* from the MMA9550L.
*/
ret = mma9551_read_config_words(data->client, MMA9551_APPID_PEDOMETER,
MMA9553_REG_CONF_SLEEPMIN,
sizeof(data->conf) / sizeof(u16),
(u16 *)&data->conf);
if (ret < 0) {
dev_err(&data->client->dev,
"failed to read configuration registers\n");
return ret;
}
/* Reset GPIO */
data->gpio_bitnum = MMA9553_MAX_BITNUM;
ret = mma9553_conf_gpio(data);
if (ret < 0)
return ret;
ret = mma9551_app_reset(data->client, MMA9551_RSC_PED);
if (ret < 0)
return ret;
/* Init config registers */
data->conf.sleepmin = MMA9553_DEFAULT_SLEEPMIN;
data->conf.sleepmax = MMA9553_DEFAULT_SLEEPMAX;
data->conf.sleepthd = MMA9553_DEFAULT_SLEEPTHD;
data->conf.config = mma9553_set_bits(data->conf.config, 1,
MMA9553_MASK_CONF_CONFIG);
/*
* Clear the activity debounce counter when the activity level changes,
* so that the confidence level applies for any activity level.
*/
data->conf.config = mma9553_set_bits(data->conf.config, 1,
MMA9553_MASK_CONF_ACT_DBCNTM);
ret = mma9551_write_config_words(data->client, MMA9551_APPID_PEDOMETER,
MMA9553_REG_CONF_SLEEPMIN,
sizeof(data->conf) / sizeof(u16),
(u16 *)&data->conf);
if (ret < 0) {
dev_err(&data->client->dev,
"failed to write configuration registers\n");
return ret;
}
return mma9551_set_device_state(data->client, true);
}
static int mma9553_read_status_word(struct mma9553_data *data, u16 reg,
u16 *tmp)
{
bool powered_on;
int ret;
/*
* The HW only counts steps and other dependent
* parameters (speed, distance, calories, activity)
* if power is on (from enabling an event or the
* step counter).
*/
powered_on = mma9553_is_any_event_enabled(data, false, 0) ||
data->stepcnt_enabled;
if (!powered_on) {
dev_err(&data->client->dev, "No channels enabled\n");
return -EINVAL;
}
mutex_lock(&data->mutex);
ret = mma9551_read_status_word(data->client, MMA9551_APPID_PEDOMETER,
reg, tmp);
mutex_unlock(&data->mutex);
return ret;
}
static int mma9553_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
u16 tmp;
u8 activity;
switch (mask) {
case IIO_CHAN_INFO_PROCESSED:
switch (chan->type) {
case IIO_STEPS:
ret = mma9553_read_status_word(data,
MMA9553_REG_STEPCNT,
&tmp);
if (ret < 0)
return ret;
*val = tmp;
return IIO_VAL_INT;
case IIO_DISTANCE:
ret = mma9553_read_status_word(data,
MMA9553_REG_DISTANCE,
&tmp);
if (ret < 0)
return ret;
*val = tmp;
return IIO_VAL_INT;
case IIO_ACTIVITY:
ret = mma9553_read_status_word(data,
MMA9553_REG_STATUS,
&tmp);
if (ret < 0)
return ret;
activity =
mma9553_get_bits(tmp, MMA9553_MASK_STATUS_ACTIVITY);
/*
* The device does not support confidence value levels,
* so we will always have 100% for current activity and
* 0% for the others.
*/
if (chan->channel2 == mma9553_activity_to_mod(activity))
*val = 100;
else
*val = 0;
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_RAW:
switch (chan->type) {
case IIO_VELOCITY: /* m/h */
if (chan->channel2 != IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z)
return -EINVAL;
ret = mma9553_read_status_word(data,
MMA9553_REG_SPEED,
&tmp);
if (ret < 0)
return ret;
*val = tmp;
return IIO_VAL_INT;
case IIO_ENERGY: /* Cal or kcal */
ret = mma9553_read_status_word(data,
MMA9553_REG_CALORIES,
&tmp);
if (ret < 0)
return ret;
*val = tmp;
return IIO_VAL_INT;
case IIO_ACCEL:
mutex_lock(&data->mutex);
ret = mma9551_read_accel_chan(data->client,
chan, val, val2);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_VELOCITY: /* m/h to m/s */
if (chan->channel2 != IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z)
return -EINVAL;
*val = 0;
*val2 = 277; /* 0.000277 */
return IIO_VAL_INT_PLUS_MICRO;
case IIO_ENERGY: /* Cal or kcal to J */
*val = 4184;
return IIO_VAL_INT;
case IIO_ACCEL:
return mma9551_read_accel_scale(val, val2);
default:
return -EINVAL;
}
case IIO_CHAN_INFO_ENABLE:
*val = data->stepcnt_enabled;
return IIO_VAL_INT;
case IIO_CHAN_INFO_CALIBHEIGHT:
tmp = mma9553_get_bits(data->conf.height_weight,
MMA9553_MASK_CONF_HEIGHT);
*val = tmp / 100; /* cm to m */
*val2 = (tmp % 100) * 10000;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_CHAN_INFO_CALIBWEIGHT:
*val = mma9553_get_bits(data->conf.height_weight,
MMA9553_MASK_CONF_WEIGHT);
return IIO_VAL_INT;
case IIO_CHAN_INFO_DEBOUNCE_COUNT:
switch (chan->type) {
case IIO_STEPS:
*val = mma9553_get_bits(data->conf.filter,
MMA9553_MASK_CONF_FILTSTEP);
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_DEBOUNCE_TIME:
switch (chan->type) {
case IIO_STEPS:
*val = mma9553_get_bits(data->conf.filter,
MMA9553_MASK_CONF_FILTTIME);
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_INT_TIME:
switch (chan->type) {
case IIO_VELOCITY:
if (chan->channel2 != IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z)
return -EINVAL;
*val = mma9553_get_bits(data->conf.speed_step,
MMA9553_MASK_CONF_SPDPRD);
return IIO_VAL_INT;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
}
static int mma9553_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
struct mma9553_data *data = iio_priv(indio_dev);
int ret, tmp;
switch (mask) {
case IIO_CHAN_INFO_ENABLE:
if (data->stepcnt_enabled == !!val)
return 0;
mutex_lock(&data->mutex);
ret = mma9551_set_power_state(data->client, val);
if (ret < 0) {
mutex_unlock(&data->mutex);
return ret;
}
data->stepcnt_enabled = val;
mutex_unlock(&data->mutex);
return 0;
case IIO_CHAN_INFO_CALIBHEIGHT:
/* m to cm */
tmp = val * 100 + val2 / 10000;
if (tmp < 0 || tmp > 255)
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data,
MMA9553_REG_CONF_HEIGHT_WEIGHT,
&data->conf.height_weight,
tmp, MMA9553_MASK_CONF_HEIGHT);
mutex_unlock(&data->mutex);
return ret;
case IIO_CHAN_INFO_CALIBWEIGHT:
if (val < 0 || val > 255)
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data,
MMA9553_REG_CONF_HEIGHT_WEIGHT,
&data->conf.height_weight,
val, MMA9553_MASK_CONF_WEIGHT);
mutex_unlock(&data->mutex);
return ret;
case IIO_CHAN_INFO_DEBOUNCE_COUNT:
switch (chan->type) {
case IIO_STEPS:
/*
* Set to 0 to disable step filtering. If the value
* specified is greater than 6, then 6 will be used.
*/
if (val < 0)
return -EINVAL;
if (val > 6)
val = 6;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data, MMA9553_REG_CONF_FILTER,
&data->conf.filter, val,
MMA9553_MASK_CONF_FILTSTEP);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_DEBOUNCE_TIME:
switch (chan->type) {
case IIO_STEPS:
if (val < 0 || val > 127)
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data, MMA9553_REG_CONF_FILTER,
&data->conf.filter, val,
MMA9553_MASK_CONF_FILTTIME);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_INT_TIME:
switch (chan->type) {
case IIO_VELOCITY:
if (chan->channel2 != IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z)
return -EINVAL;
/*
* If set to a value greater than 5, then 5 will be
* used. Warning: Do not set SPDPRD to 0 or 1 as
* this may cause undesirable behavior.
*/
if (val < 2)
return -EINVAL;
if (val > 5)
val = 5;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data,
MMA9553_REG_CONF_SPEED_STEP,
&data->conf.speed_step, val,
MMA9553_MASK_CONF_SPDPRD);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
}
static int mma9553_read_event_config(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan,
enum iio_event_type type,
enum iio_event_direction dir)
{
struct mma9553_data *data = iio_priv(indio_dev);
struct mma9553_event *event;
event = mma9553_get_event(data, chan->type, chan->channel2, dir);
if (!event)
return -EINVAL;
return event->enabled;
}
static int mma9553_write_event_config(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan,
enum iio_event_type type,
enum iio_event_direction dir, int state)
{
struct mma9553_data *data = iio_priv(indio_dev);
struct mma9553_event *event;
int ret;
event = mma9553_get_event(data, chan->type, chan->channel2, dir);
if (!event)
return -EINVAL;
if (event->enabled == state)
return 0;
mutex_lock(&data->mutex);
ret = mma9551_set_power_state(data->client, state);
if (ret < 0)
goto err_out;
event->enabled = state;
ret = mma9553_conf_gpio(data);
if (ret < 0)
goto err_conf_gpio;
mutex_unlock(&data->mutex);
return 0;
err_conf_gpio:
if (state) {
event->enabled = false;
mma9551_set_power_state(data->client, false);
}
err_out:
mutex_unlock(&data->mutex);
return ret;
}
static int mma9553_read_event_value(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan,
enum iio_event_type type,
enum iio_event_direction dir,
enum iio_event_info info,
int *val, int *val2)
{
struct mma9553_data *data = iio_priv(indio_dev);
*val2 = 0;
switch (info) {
case IIO_EV_INFO_VALUE:
switch (chan->type) {
case IIO_STEPS:
*val = mma9553_get_bits(data->conf.speed_step,
MMA9553_MASK_CONF_STEPCOALESCE);
return IIO_VAL_INT;
case IIO_ACTIVITY:
/*
* The device does not support confidence value levels.
* We set an average of 50%.
*/
*val = 50;
return IIO_VAL_INT;
default:
return -EINVAL;
}
case IIO_EV_INFO_PERIOD:
switch (chan->type) {
case IIO_ACTIVITY:
*val = MMA9553_ACTIVITY_THD_TO_SEC(data->conf.actthd);
return IIO_VAL_INT;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
}
static int mma9553_write_event_value(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan,
enum iio_event_type type,
enum iio_event_direction dir,
enum iio_event_info info,
int val, int val2)
{
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
switch (info) {
case IIO_EV_INFO_VALUE:
switch (chan->type) {
case IIO_STEPS:
if (val < 0 || val > 255)
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data,
MMA9553_REG_CONF_SPEED_STEP,
&data->conf.speed_step, val,
MMA9553_MASK_CONF_STEPCOALESCE);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
case IIO_EV_INFO_PERIOD:
switch (chan->type) {
case IIO_ACTIVITY:
if (val < 0 || val > MMA9553_ACTIVITY_THD_TO_SEC(
MMA9553_MAX_ACTTHD))
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data, MMA9553_REG_CONF_ACTTHD,
&data->conf.actthd,
MMA9553_ACTIVITY_SEC_TO_THD
(val), MMA9553_MASK_CONF_WORD);
mutex_unlock(&data->mutex);
return ret;
default:
return -EINVAL;
}
default:
return -EINVAL;
}
}
static int mma9553_get_calibgender_mode(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan)
{
struct mma9553_data *data = iio_priv(indio_dev);
u8 gender;
gender = mma9553_get_bits(data->conf.filter, MMA9553_MASK_CONF_MALE);
/*
* HW expects 0 for female and 1 for male,
* while iio index is 0 for male and 1 for female.
*/
return !gender;
}
static int mma9553_set_calibgender_mode(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan,
unsigned int mode)
{
struct mma9553_data *data = iio_priv(indio_dev);
u8 gender = !mode;
int ret;
if ((mode != 0) && (mode != 1))
return -EINVAL;
mutex_lock(&data->mutex);
ret = mma9553_set_config(data, MMA9553_REG_CONF_FILTER,
&data->conf.filter, gender,
MMA9553_MASK_CONF_MALE);
mutex_unlock(&data->mutex);
return ret;
}
static const struct iio_event_spec mma9553_step_event = {
.type = IIO_EV_TYPE_CHANGE,
.dir = IIO_EV_DIR_NONE,
.mask_separate = BIT(IIO_EV_INFO_ENABLE) | BIT(IIO_EV_INFO_VALUE),
};
static const struct iio_event_spec mma9553_activity_events[] = {
{
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_RISING,
.mask_separate = BIT(IIO_EV_INFO_ENABLE) |
BIT(IIO_EV_INFO_VALUE) |
BIT(IIO_EV_INFO_PERIOD),
},
{
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_FALLING,
.mask_separate = BIT(IIO_EV_INFO_ENABLE) |
BIT(IIO_EV_INFO_VALUE) |
BIT(IIO_EV_INFO_PERIOD),
},
};
static const char * const mma9553_calibgender_modes[] = { "male", "female" };
static const struct iio_enum mma9553_calibgender_enum = {
.items = mma9553_calibgender_modes,
.num_items = ARRAY_SIZE(mma9553_calibgender_modes),
.get = mma9553_get_calibgender_mode,
.set = mma9553_set_calibgender_mode,
};
static const struct iio_chan_spec_ext_info mma9553_ext_info[] = {
IIO_ENUM("calibgender", IIO_SHARED_BY_TYPE, &mma9553_calibgender_enum),
IIO_ENUM_AVAILABLE("calibgender", &mma9553_calibgender_enum),
{},
};
#define MMA9553_PEDOMETER_CHANNEL(_type, _mask) { \
.type = _type, \
.info_mask_separate = BIT(IIO_CHAN_INFO_ENABLE) | \
BIT(IIO_CHAN_INFO_CALIBHEIGHT) | \
_mask, \
.ext_info = mma9553_ext_info, \
}
#define MMA9553_ACTIVITY_CHANNEL(_chan2) { \
.type = IIO_ACTIVITY, \
.modified = 1, \
.channel2 = _chan2, \
.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_CALIBHEIGHT) | \
BIT(IIO_CHAN_INFO_ENABLE), \
.event_spec = mma9553_activity_events, \
.num_event_specs = ARRAY_SIZE(mma9553_activity_events), \
.ext_info = mma9553_ext_info, \
}
static const struct iio_chan_spec mma9553_channels[] = {
MMA9551_ACCEL_CHANNEL(IIO_MOD_X),
MMA9551_ACCEL_CHANNEL(IIO_MOD_Y),
MMA9551_ACCEL_CHANNEL(IIO_MOD_Z),
{
.type = IIO_STEPS,
.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
BIT(IIO_CHAN_INFO_ENABLE) |
BIT(IIO_CHAN_INFO_DEBOUNCE_COUNT) |
BIT(IIO_CHAN_INFO_DEBOUNCE_TIME),
.event_spec = &mma9553_step_event,
.num_event_specs = 1,
},
MMA9553_PEDOMETER_CHANNEL(IIO_DISTANCE, BIT(IIO_CHAN_INFO_PROCESSED)),
{
.type = IIO_VELOCITY,
.modified = 1,
.channel2 = IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_INT_TIME) |
BIT(IIO_CHAN_INFO_ENABLE),
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_CALIBHEIGHT),
.ext_info = mma9553_ext_info,
},
MMA9553_PEDOMETER_CHANNEL(IIO_ENERGY, BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_CALIBWEIGHT)),
MMA9553_ACTIVITY_CHANNEL(IIO_MOD_RUNNING),
MMA9553_ACTIVITY_CHANNEL(IIO_MOD_JOGGING),
MMA9553_ACTIVITY_CHANNEL(IIO_MOD_WALKING),
MMA9553_ACTIVITY_CHANNEL(IIO_MOD_STILL),
};
static const struct iio_info mma9553_info = {
.driver_module = THIS_MODULE,
.read_raw = mma9553_read_raw,
.write_raw = mma9553_write_raw,
.read_event_config = mma9553_read_event_config,
.write_event_config = mma9553_write_event_config,
.read_event_value = mma9553_read_event_value,
.write_event_value = mma9553_write_event_value,
};
static irqreturn_t mma9553_irq_handler(int irq, void *private)
{
struct iio_dev *indio_dev = private;
struct mma9553_data *data = iio_priv(indio_dev);
data->timestamp = iio_get_time_ns();
/*
* Since we only configure the interrupt pin when an
* event is enabled, we are sure we have at least
* one event enabled at this point.
*/
return IRQ_WAKE_THREAD;
}
static irqreturn_t mma9553_event_handler(int irq, void *private)
{
struct iio_dev *indio_dev = private;
struct mma9553_data *data = iio_priv(indio_dev);
u16 stepcnt;
u8 activity;
struct mma9553_event *ev_activity, *ev_prev_activity, *ev_step_detect;
int ret;
mutex_lock(&data->mutex);
ret = mma9553_read_activity_stepcnt(data, &activity, &stepcnt);
if (ret < 0) {
mutex_unlock(&data->mutex);
return IRQ_HANDLED;
}
ev_prev_activity = mma9553_get_event(data, IIO_ACTIVITY,
mma9553_activity_to_mod(
data->activity),
IIO_EV_DIR_FALLING);
ev_activity = mma9553_get_event(data, IIO_ACTIVITY,
mma9553_activity_to_mod(activity),
IIO_EV_DIR_RISING);
ev_step_detect = mma9553_get_event(data, IIO_STEPS, IIO_NO_MOD,
IIO_EV_DIR_NONE);
if (ev_step_detect->enabled && (stepcnt != data->stepcnt)) {
data->stepcnt = stepcnt;
iio_push_event(indio_dev,
IIO_EVENT_CODE(IIO_STEPS, 0, IIO_NO_MOD,
IIO_EV_DIR_NONE,
IIO_EV_TYPE_CHANGE, 0, 0, 0),
data->timestamp);
}
if (activity != data->activity) {
data->activity = activity;
/* ev_activity can be NULL if activity == ACTIVITY_UNKNOWN */
if (ev_prev_activity && ev_prev_activity->enabled)
iio_push_event(indio_dev,
IIO_EVENT_CODE(IIO_ACTIVITY, 0,
ev_prev_activity->info->mod,
IIO_EV_DIR_FALLING,
IIO_EV_TYPE_THRESH, 0, 0,
0),
data->timestamp);
if (ev_activity && ev_activity->enabled)
iio_push_event(indio_dev,
IIO_EVENT_CODE(IIO_ACTIVITY, 0,
ev_activity->info->mod,
IIO_EV_DIR_RISING,
IIO_EV_TYPE_THRESH, 0, 0,
0),
data->timestamp);
}
mutex_unlock(&data->mutex);
return IRQ_HANDLED;
}
static int mma9553_gpio_probe(struct i2c_client *client)
{
struct device *dev;
struct gpio_desc *gpio;
int ret;
if (!client)
return -EINVAL;
dev = &client->dev;
/* data ready GPIO interrupt pin */
gpio = devm_gpiod_get_index(dev, MMA9553_GPIO_NAME, 0, GPIOD_IN);
if (IS_ERR(gpio)) {
dev_err(dev, "ACPI GPIO get index failed\n");
return PTR_ERR(gpio);
}
ret = gpiod_to_irq(gpio);
dev_dbg(dev, "GPIO resource, no:%d irq:%d\n", desc_to_gpio(gpio), ret);
return ret;
}
static const char *mma9553_match_acpi_device(struct device *dev)
{
const struct acpi_device_id *id;
id = acpi_match_device(dev->driver->acpi_match_table, dev);
if (!id)
return NULL;
return dev_name(dev);
}
static int mma9553_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct mma9553_data *data;
struct iio_dev *indio_dev;
const char *name = NULL;
int ret;
indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
if (!indio_dev)
return -ENOMEM;
data = iio_priv(indio_dev);
i2c_set_clientdata(client, indio_dev);
data->client = client;
if (id)
name = id->name;
else if (ACPI_HANDLE(&client->dev))
name = mma9553_match_acpi_device(&client->dev);
else
return -ENOSYS;
mutex_init(&data->mutex);
mma9553_init_events(data);
ret = mma9553_init(data);
if (ret < 0)
return ret;
indio_dev->dev.parent = &client->dev;
indio_dev->channels = mma9553_channels;
indio_dev->num_channels = ARRAY_SIZE(mma9553_channels);
indio_dev->name = name;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->info = &mma9553_info;
if (client->irq < 0)
client->irq = mma9553_gpio_probe(client);
if (client->irq > 0) {
ret = devm_request_threaded_irq(&client->dev, client->irq,
mma9553_irq_handler,
mma9553_event_handler,
IRQF_TRIGGER_RISING,
MMA9553_IRQ_NAME, indio_dev);
if (ret < 0) {
dev_err(&client->dev, "request irq %d failed\n",
client->irq);
goto out_poweroff;
}
}
ret = iio_device_register(indio_dev);
if (ret < 0) {
dev_err(&client->dev, "unable to register iio device\n");
goto out_poweroff;
}
ret = pm_runtime_set_active(&client->dev);
if (ret < 0)
goto out_iio_unregister;
pm_runtime_enable(&client->dev);
pm_runtime_set_autosuspend_delay(&client->dev,
MMA9551_AUTO_SUSPEND_DELAY_MS);
pm_runtime_use_autosuspend(&client->dev);
dev_dbg(&indio_dev->dev, "Registered device %s\n", name);
return 0;
out_iio_unregister:
iio_device_unregister(indio_dev);
out_poweroff:
mma9551_set_device_state(client, false);
return ret;
}
static int mma9553_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
struct mma9553_data *data = iio_priv(indio_dev);
pm_runtime_disable(&client->dev);
pm_runtime_set_suspended(&client->dev);
pm_runtime_put_noidle(&client->dev);
iio_device_unregister(indio_dev);
mutex_lock(&data->mutex);
mma9551_set_device_state(data->client, false);
mutex_unlock(&data->mutex);
return 0;
}
#ifdef CONFIG_PM
static int mma9553_runtime_suspend(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
mutex_lock(&data->mutex);
ret = mma9551_set_device_state(data->client, false);
mutex_unlock(&data->mutex);
if (ret < 0) {
dev_err(&data->client->dev, "powering off device failed\n");
return -EAGAIN;
}
return 0;
}
static int mma9553_runtime_resume(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
ret = mma9551_set_device_state(data->client, true);
if (ret < 0)
return ret;
mma9551_sleep(MMA9553_DEFAULT_SAMPLE_RATE);
return 0;
}
#endif
#ifdef CONFIG_PM_SLEEP
static int mma9553_suspend(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
mutex_lock(&data->mutex);
ret = mma9551_set_device_state(data->client, false);
mutex_unlock(&data->mutex);
return ret;
}
static int mma9553_resume(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct mma9553_data *data = iio_priv(indio_dev);
int ret;
mutex_lock(&data->mutex);
ret = mma9551_set_device_state(data->client, true);
mutex_unlock(&data->mutex);
return ret;
}
#endif
static const struct dev_pm_ops mma9553_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(mma9553_suspend, mma9553_resume)
SET_RUNTIME_PM_OPS(mma9553_runtime_suspend,
mma9553_runtime_resume, NULL)
};
static const struct acpi_device_id mma9553_acpi_match[] = {
{"MMA9553", 0},
{},
};
MODULE_DEVICE_TABLE(acpi, mma9553_acpi_match);
static const struct i2c_device_id mma9553_id[] = {
{"mma9553", 0},
{},
};
MODULE_DEVICE_TABLE(i2c, mma9553_id);
static struct i2c_driver mma9553_driver = {
.driver = {
.name = MMA9553_DRV_NAME,
.acpi_match_table = ACPI_PTR(mma9553_acpi_match),
.pm = &mma9553_pm_ops,
},
.probe = mma9553_probe,
.remove = mma9553_remove,
.id_table = mma9553_id,
};
module_i2c_driver(mma9553_driver);
MODULE_AUTHOR("Irina Tirdea <irina.tirdea@intel.com>");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MMA9553L pedometer platform driver");
|
publicloudapp/csrutil
|
linux-4.3/drivers/iio/accel/mma9553.c
|
C
|
mit
| 33,626
|
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (C) 2019 BayLibre, SAS
* Author: Maxime Jourdan <mjourdan@baylibre.com>
*/
#include <media/v4l2-mem2mem.h>
#include <media/videobuf2-dma-contig.h>
#include "vdec_helpers.h"
#include "dos_regs.h"
#include "codec_h264.h"
#define SIZE_EXT_FW (20 * SZ_1K)
#define SIZE_WORKSPACE 0x1ee000
#define SIZE_SEI (8 * SZ_1K)
/*
* Offset added by the firmware which must be substracted
* from the workspace phyaddr
*/
#define WORKSPACE_BUF_OFFSET 0x1000000
/* ISR status */
#define CMD_MASK GENMASK(7, 0)
#define CMD_SRC_CHANGE 1
#define CMD_FRAMES_READY 2
#define CMD_FATAL_ERROR 6
#define CMD_BAD_WIDTH 7
#define CMD_BAD_HEIGHT 8
#define SEI_DATA_READY BIT(15)
/* Picture type */
#define PIC_TOP_BOT 5
#define PIC_BOT_TOP 6
/* Size of Motion Vector per macroblock */
#define MB_MV_SIZE 96
/* Frame status data */
#define PIC_STRUCT_BIT 5
#define PIC_STRUCT_MASK GENMASK(2, 0)
#define BUF_IDX_MASK GENMASK(4, 0)
#define ERROR_FLAG BIT(9)
#define OFFSET_BIT 16
#define OFFSET_MASK GENMASK(15, 0)
/* Bitstream parsed data */
#define MB_TOTAL_BIT 8
#define MB_TOTAL_MASK GENMASK(15, 0)
#define MB_WIDTH_MASK GENMASK(7, 0)
#define MAX_REF_BIT 24
#define MAX_REF_MASK GENMASK(6, 0)
#define AR_IDC_BIT 16
#define AR_IDC_MASK GENMASK(7, 0)
#define AR_PRESENT_FLAG BIT(0)
#define AR_EXTEND 0xff
/*
* Buffer to send to the ESPARSER to signal End Of Stream for H.264.
* This is a 16x16 encoded picture that will trigger drain firmware-side.
* There is no known alternative.
*/
static const u8 eos_sequence[SZ_4K] = {
0x00, 0x00, 0x00, 0x01, 0x06, 0x05, 0xff, 0xe4, 0xdc, 0x45, 0xe9, 0xbd,
0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef,
0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72, 0x65, 0x20,
0x36, 0x37, 0x20, 0x72, 0x31, 0x31, 0x33, 0x30, 0x20, 0x38, 0x34, 0x37,
0x35, 0x39, 0x37, 0x37, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, 0x34,
0x2f, 0x4d, 0x50, 0x45, 0x47, 0x2d, 0x34, 0x20, 0x41, 0x56, 0x43, 0x20,
0x63, 0x6f, 0x64, 0x65, 0x63, 0x20, 0x2d, 0x20, 0x43, 0x6f, 0x70, 0x79,
0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x32, 0x30,
0x30, 0x39, 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f,
0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6c, 0x61, 0x6e,
0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, 0x68, 0x74,
0x6d, 0x6c, 0x20, 0x2d, 0x20, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73,
0x3a, 0x20, 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d, 0x31, 0x20, 0x72, 0x65,
0x66, 0x3d, 0x31, 0x20, 0x64, 0x65, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3d,
0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, 0x61, 0x6c, 0x79, 0x73,
0x65, 0x3d, 0x30, 0x78, 0x31, 0x3a, 0x30, 0x78, 0x31, 0x31, 0x31, 0x20,
0x6d, 0x65, 0x3d, 0x68, 0x65, 0x78, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x65,
0x3d, 0x36, 0x20, 0x70, 0x73, 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e,
0x30, 0x3a, 0x30, 0x2e, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f,
0x72, 0x65, 0x66, 0x3d, 0x30, 0x20, 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e,
0x67, 0x65, 0x3d, 0x31, 0x36, 0x20, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x61,
0x5f, 0x6d, 0x65, 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69,
0x73, 0x3d, 0x30, 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x30,
0x20, 0x63, 0x71, 0x6d, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a,
0x6f, 0x6e, 0x65, 0x3d, 0x32, 0x31, 0x2c, 0x31, 0x31, 0x20, 0x63, 0x68,
0x72, 0x6f, 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66, 0x73,
0x65, 0x74, 0x3d, 0x2d, 0x32, 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64,
0x73, 0x3d, 0x31, 0x20, 0x6e, 0x72, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x63,
0x69, 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, 0x6d, 0x62, 0x61, 0x66,
0x66, 0x3d, 0x30, 0x20, 0x62, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x3d,
0x30, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x3d, 0x32, 0x35, 0x30,
0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x3d,
0x32, 0x35, 0x20, 0x73, 0x63, 0x65, 0x6e, 0x65, 0x63, 0x75, 0x74, 0x3d,
0x34, 0x30, 0x20, 0x72, 0x63, 0x3d, 0x61, 0x62, 0x72, 0x20, 0x62, 0x69,
0x74, 0x72, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x30, 0x20, 0x72, 0x61, 0x74,
0x65, 0x74, 0x6f, 0x6c, 0x3d, 0x31, 0x2e, 0x30, 0x20, 0x71, 0x63, 0x6f,
0x6d, 0x70, 0x3d, 0x30, 0x2e, 0x36, 0x30, 0x20, 0x71, 0x70, 0x6d, 0x69,
0x6e, 0x3d, 0x31, 0x30, 0x20, 0x71, 0x70, 0x6d, 0x61, 0x78, 0x3d, 0x35,
0x31, 0x20, 0x71, 0x70, 0x73, 0x74, 0x65, 0x70, 0x3d, 0x34, 0x20, 0x69,
0x70, 0x5f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x3d, 0x31, 0x2e, 0x34, 0x30,
0x20, 0x61, 0x71, 0x3d, 0x31, 0x3a, 0x31, 0x2e, 0x30, 0x30, 0x00, 0x80,
0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, 0x0a, 0x9a, 0x74, 0xf4, 0x20,
0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, 0x06, 0x51, 0xe2, 0x44, 0xd4,
0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x32, 0xc8, 0x00, 0x00, 0x00, 0x01,
0x65, 0x88, 0x80, 0x20, 0x00, 0x08, 0x7f, 0xea, 0x6a, 0xe2, 0x99, 0xb6,
0x57, 0xae, 0x49, 0x30, 0xf5, 0xfe, 0x5e, 0x46, 0x0b, 0x72, 0x44, 0xc4,
0xe1, 0xfc, 0x62, 0xda, 0xf1, 0xfb, 0xa2, 0xdb, 0xd6, 0xbe, 0x5c, 0xd7,
0x24, 0xa3, 0xf5, 0xb9, 0x2f, 0x57, 0x16, 0x49, 0x75, 0x47, 0x77, 0x09,
0x5c, 0xa1, 0xb4, 0xc3, 0x4f, 0x60, 0x2b, 0xb0, 0x0c, 0xc8, 0xd6, 0x66,
0xba, 0x9b, 0x82, 0x29, 0x33, 0x92, 0x26, 0x99, 0x31, 0x1c, 0x7f, 0x9b,
0x00, 0x00, 0x01, 0x0ff,
};
static const u8 *codec_h264_eos_sequence(u32 *len)
{
*len = ARRAY_SIZE(eos_sequence);
return eos_sequence;
}
struct codec_h264 {
/* H.264 decoder requires an extended firmware */
void *ext_fw_vaddr;
dma_addr_t ext_fw_paddr;
/* Buffer for the H.264 Workspace */
void *workspace_vaddr;
dma_addr_t workspace_paddr;
/* Buffer for the H.264 references MV */
void *ref_vaddr;
dma_addr_t ref_paddr;
u32 ref_size;
/* Buffer for parsed SEI data */
void *sei_vaddr;
dma_addr_t sei_paddr;
u32 mb_width;
u32 mb_height;
u32 max_refs;
};
static int codec_h264_can_recycle(struct amvdec_core *core)
{
return !amvdec_read_dos(core, AV_SCRATCH_7) ||
!amvdec_read_dos(core, AV_SCRATCH_8);
}
static void codec_h264_recycle(struct amvdec_core *core, u32 buf_idx)
{
/*
* Tell the firmware it can recycle this buffer.
* AV_SCRATCH_8 serves the same purpose.
*/
if (!amvdec_read_dos(core, AV_SCRATCH_7))
amvdec_write_dos(core, AV_SCRATCH_7, buf_idx + 1);
else
amvdec_write_dos(core, AV_SCRATCH_8, buf_idx + 1);
}
static int codec_h264_start(struct amvdec_session *sess)
{
u32 workspace_offset;
struct amvdec_core *core = sess->core;
struct codec_h264 *h264 = sess->priv;
/* Allocate some memory for the H.264 decoder's state */
h264->workspace_vaddr =
dma_alloc_coherent(core->dev, SIZE_WORKSPACE,
&h264->workspace_paddr, GFP_KERNEL);
if (!h264->workspace_vaddr)
return -ENOMEM;
/* Allocate some memory for the H.264 SEI dump */
h264->sei_vaddr = dma_alloc_coherent(core->dev, SIZE_SEI,
&h264->sei_paddr, GFP_KERNEL);
if (!h264->sei_vaddr)
return -ENOMEM;
amvdec_write_dos_bits(core, POWER_CTL_VLD, BIT(9) | BIT(6));
workspace_offset = h264->workspace_paddr - WORKSPACE_BUF_OFFSET;
amvdec_write_dos(core, AV_SCRATCH_1, workspace_offset);
amvdec_write_dos(core, AV_SCRATCH_G, h264->ext_fw_paddr);
amvdec_write_dos(core, AV_SCRATCH_I, h264->sei_paddr -
workspace_offset);
/* Enable "error correction" */
amvdec_write_dos(core, AV_SCRATCH_F,
(amvdec_read_dos(core, AV_SCRATCH_F) & 0xffffffc3) |
BIT(4) | BIT(7));
amvdec_write_dos(core, MDEC_PIC_DC_THRESH, 0x404038aa);
return 0;
}
static int codec_h264_stop(struct amvdec_session *sess)
{
struct codec_h264 *h264 = sess->priv;
struct amvdec_core *core = sess->core;
if (h264->ext_fw_vaddr)
dma_free_coherent(core->dev, SIZE_EXT_FW,
h264->ext_fw_vaddr, h264->ext_fw_paddr);
if (h264->workspace_vaddr)
dma_free_coherent(core->dev, SIZE_WORKSPACE,
h264->workspace_vaddr, h264->workspace_paddr);
if (h264->ref_vaddr)
dma_free_coherent(core->dev, h264->ref_size,
h264->ref_vaddr, h264->ref_paddr);
if (h264->sei_vaddr)
dma_free_coherent(core->dev, SIZE_SEI,
h264->sei_vaddr, h264->sei_paddr);
return 0;
}
static int codec_h264_load_extended_firmware(struct amvdec_session *sess,
const u8 *data, u32 len)
{
struct codec_h264 *h264;
struct amvdec_core *core = sess->core;
if (len < SIZE_EXT_FW)
return -EINVAL;
h264 = kzalloc(sizeof(*h264), GFP_KERNEL);
if (!h264)
return -ENOMEM;
h264->ext_fw_vaddr = dma_alloc_coherent(core->dev, SIZE_EXT_FW,
&h264->ext_fw_paddr,
GFP_KERNEL);
if (!h264->ext_fw_vaddr) {
kfree(h264);
return -ENOMEM;
}
memcpy(h264->ext_fw_vaddr, data, SIZE_EXT_FW);
sess->priv = h264;
return 0;
}
static const struct v4l2_fract par_table[] = {
{ 1, 1 }, { 1, 1 }, { 12, 11 }, { 10, 11 },
{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
{ 64, 33 }, { 160, 99 }, { 4, 3 }, { 3, 2 },
{ 2, 1 }
};
static void codec_h264_set_par(struct amvdec_session *sess)
{
struct amvdec_core *core = sess->core;
u32 seq_info = amvdec_read_dos(core, AV_SCRATCH_2);
u32 ar_idc = (seq_info >> AR_IDC_BIT) & AR_IDC_MASK;
if (!(seq_info & AR_PRESENT_FLAG))
return;
if (ar_idc == AR_EXTEND) {
u32 ar_info = amvdec_read_dos(core, AV_SCRATCH_3);
sess->pixelaspect.numerator = ar_info & 0xffff;
sess->pixelaspect.denominator = (ar_info >> 16) & 0xffff;
return;
}
if (ar_idc >= ARRAY_SIZE(par_table))
return;
sess->pixelaspect = par_table[ar_idc];
}
static void codec_h264_resume(struct amvdec_session *sess)
{
struct amvdec_core *core = sess->core;
struct codec_h264 *h264 = sess->priv;
u32 mb_width, mb_height, mb_total;
amvdec_set_canvases(sess,
(u32[]){ ANC0_CANVAS_ADDR, 0 },
(u32[]){ 24, 0 });
dev_dbg(core->dev, "max_refs = %u; actual_dpb_size = %u\n",
h264->max_refs, sess->num_dst_bufs);
/* Align to a multiple of 4 macroblocks */
mb_width = ALIGN(h264->mb_width, 4);
mb_height = ALIGN(h264->mb_height, 4);
mb_total = mb_width * mb_height;
h264->ref_size = mb_total * MB_MV_SIZE * h264->max_refs;
h264->ref_vaddr = dma_alloc_coherent(core->dev, h264->ref_size,
&h264->ref_paddr, GFP_KERNEL);
if (!h264->ref_vaddr) {
amvdec_abort(sess);
return;
}
/* Address to store the references' MVs */
amvdec_write_dos(core, AV_SCRATCH_1, h264->ref_paddr);
/* End of ref MV */
amvdec_write_dos(core, AV_SCRATCH_4, h264->ref_paddr + h264->ref_size);
amvdec_write_dos(core, AV_SCRATCH_0, (h264->max_refs << 24) |
(sess->num_dst_bufs << 16) |
((h264->max_refs - 1) << 8));
}
/*
* Configure the H.264 decoder when the parser detected a parameter set change
*/
static void codec_h264_src_change(struct amvdec_session *sess)
{
struct amvdec_core *core = sess->core;
struct codec_h264 *h264 = sess->priv;
u32 parsed_info, mb_total;
u32 crop_infor, crop_bottom, crop_right;
u32 frame_width, frame_height;
sess->keyframe_found = 1;
parsed_info = amvdec_read_dos(core, AV_SCRATCH_1);
/* Total number of 16x16 macroblocks */
mb_total = (parsed_info >> MB_TOTAL_BIT) & MB_TOTAL_MASK;
/* Number of macroblocks per line */
h264->mb_width = parsed_info & MB_WIDTH_MASK;
/* Number of macroblock lines */
h264->mb_height = mb_total / h264->mb_width;
h264->max_refs = ((parsed_info >> MAX_REF_BIT) & MAX_REF_MASK) + 1;
crop_infor = amvdec_read_dos(core, AV_SCRATCH_6);
crop_bottom = (crop_infor & 0xff);
crop_right = (crop_infor >> 16) & 0xff;
frame_width = h264->mb_width * 16 - crop_right;
frame_height = h264->mb_height * 16 - crop_bottom;
dev_dbg(core->dev, "frame: %ux%u; crop: %u %u\n",
frame_width, frame_height, crop_right, crop_bottom);
codec_h264_set_par(sess);
amvdec_src_change(sess, frame_width, frame_height, h264->max_refs + 5);
}
/*
* The bitstream offset is split in half in 2 different registers.
* Fetch its MSB here, which location depends on the frame number.
*/
static u32 get_offset_msb(struct amvdec_core *core, int frame_num)
{
int take_msb = frame_num % 2;
int reg_offset = (frame_num / 2) * 4;
u32 offset_msb = amvdec_read_dos(core, AV_SCRATCH_A + reg_offset);
if (take_msb)
return offset_msb & 0xffff0000;
return (offset_msb & 0x0000ffff) << 16;
}
static void codec_h264_frames_ready(struct amvdec_session *sess, u32 status)
{
struct amvdec_core *core = sess->core;
int error_count;
int num_frames;
int i;
error_count = amvdec_read_dos(core, AV_SCRATCH_D);
num_frames = (status >> 8) & 0xff;
if (error_count) {
dev_warn(core->dev,
"decoder error(s) happened, count %d\n", error_count);
amvdec_write_dos(core, AV_SCRATCH_D, 0);
}
for (i = 0; i < num_frames; i++) {
u32 frame_status = amvdec_read_dos(core, AV_SCRATCH_1 + i * 4);
u32 buffer_index = frame_status & BUF_IDX_MASK;
u32 pic_struct = (frame_status >> PIC_STRUCT_BIT) &
PIC_STRUCT_MASK;
u32 offset = (frame_status >> OFFSET_BIT) & OFFSET_MASK;
u32 field = V4L2_FIELD_NONE;
/*
* A buffer decode error means it was decoded,
* but part of the picture will have artifacts.
* Typical reason is a temporarily corrupted bitstream
*/
if (frame_status & ERROR_FLAG)
dev_dbg(core->dev, "Buffer %d decode error\n",
buffer_index);
if (pic_struct == PIC_TOP_BOT)
field = V4L2_FIELD_INTERLACED_TB;
else if (pic_struct == PIC_BOT_TOP)
field = V4L2_FIELD_INTERLACED_BT;
offset |= get_offset_msb(core, i);
amvdec_dst_buf_done_idx(sess, buffer_index, offset, field);
}
}
static irqreturn_t codec_h264_threaded_isr(struct amvdec_session *sess)
{
struct amvdec_core *core = sess->core;
u32 status;
u32 size;
u8 cmd;
status = amvdec_read_dos(core, AV_SCRATCH_0);
cmd = status & CMD_MASK;
switch (cmd) {
case CMD_SRC_CHANGE:
codec_h264_src_change(sess);
break;
case CMD_FRAMES_READY:
codec_h264_frames_ready(sess, status);
break;
case CMD_FATAL_ERROR:
dev_err(core->dev, "H.264 decoder fatal error\n");
goto abort;
case CMD_BAD_WIDTH:
size = (amvdec_read_dos(core, AV_SCRATCH_1) + 1) * 16;
dev_err(core->dev, "Unsupported video width: %u\n", size);
goto abort;
case CMD_BAD_HEIGHT:
size = (amvdec_read_dos(core, AV_SCRATCH_1) + 1) * 16;
dev_err(core->dev, "Unsupported video height: %u\n", size);
goto abort;
case 0: /* Unused but not worth printing for */
case 9:
break;
default:
dev_info(core->dev, "Unexpected H264 ISR: %08X\n", cmd);
break;
}
if (cmd && cmd != CMD_SRC_CHANGE)
amvdec_write_dos(core, AV_SCRATCH_0, 0);
/* Decoder has some SEI data for us ; ignore */
if (amvdec_read_dos(core, AV_SCRATCH_J) & SEI_DATA_READY)
amvdec_write_dos(core, AV_SCRATCH_J, 0);
return IRQ_HANDLED;
abort:
amvdec_abort(sess);
return IRQ_HANDLED;
}
static irqreturn_t codec_h264_isr(struct amvdec_session *sess)
{
struct amvdec_core *core = sess->core;
amvdec_write_dos(core, ASSIST_MBOX1_CLR_REG, 1);
return IRQ_WAKE_THREAD;
}
struct amvdec_codec_ops codec_h264_ops = {
.start = codec_h264_start,
.stop = codec_h264_stop,
.load_extended_firmware = codec_h264_load_extended_firmware,
.isr = codec_h264_isr,
.threaded_isr = codec_h264_threaded_isr,
.can_recycle = codec_h264_can_recycle,
.recycle = codec_h264_recycle,
.eos_sequence = codec_h264_eos_sequence,
.resume = codec_h264_resume,
};
|
CSE3320/kernel-code
|
linux-5.8/drivers/staging/media/meson/vdec/codec_h264.c
|
C
|
gpl-2.0
| 15,177
|
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
|
painless-software/painless-continuous-delivery
|
{{cookiecutter.project_slug}}/_/frameworks/SpringBoot/mvnw.cmd
|
Batchfile
|
apache-2.0
| 6,608
|
YUI.add('oop', function(Y) {
/**
* Supplies object inheritance and manipulation utilities. This adds
* additional functionaity to what is provided in yui-base, and the
* methods are applied directly to the YUI instance. This module
* is required for most YUI components.
* @module oop
*/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = "_~yuim~_",
EACH = 'each',
SOME = 'some',
dispatch = function(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);
}
}
};
/**
* The following methods are added to the YUI instance
* @class YUI~oop
*/
/**
* Applies prototype properties from the supplier to the receiver.
* The receiver can be a constructor or an instance.
* @method augment
* @param {Function} r the object to receive the augmentation
* @param {Function} s the object that supplies the properties to augment
* @param ov {boolean} if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param wl {string[]} a whitelist. If supplied, only properties in
* this list will be applied to the receiver.
* @param args {Array | Any} arg or arguments to apply to the supplier
* constructor when initializing.
* @return {object} the augmented object
*
* @todo constructor optional?
* @todo understanding what an instance is augmented with
* @TODO best practices for overriding sequestered methods.
*/
Y.augment = function(r, s, ov, wl, args) {
var sProto = s.prototype,
newProto = null,
construct = s,
a = (args) ? Y.Array(args) : [],
rProto = r.prototype,
target = rProto || r,
applyConstructor = false,
sequestered, replacements, i;
// working on a class, so apply constructor infrastructure
if (rProto && construct) {
sequestered = {};
replacements = {};
newProto = {};
// sequester all of the functions in the supplier and replace with
// one that will restore all of them.
Y.Object.each(sProto, function(v, k) {
replacements[k] = function() {
// Y.log('sequestered function "' + k + '" executed. Initializing EventTarget');
// overwrite the prototype with all of the sequestered functions,
// but only if it hasn't been overridden
for (i in sequestered) {
if (sequestered.hasOwnProperty(i) && (this[i] === replacements[i])) {
// Y.log('... restoring ' + k);
this[i] = sequestered[i];
}
}
// apply the constructor
construct.apply(this, a);
// apply the original sequestered function
return sequestered[k].apply(this, arguments);
};
if ((!wl || (k in wl)) && (ov || !(k in this))) {
// Y.log('augment: ' + k);
if (L.isFunction(v)) {
// sequester the function
sequestered[k] = v;
// replace the sequestered function with a function that will
// restore all sequestered functions and exectue the constructor.
this[k] = replacements[k];
} else {
// Y.log('augment() applying non-function: ' + k);
this[k] = v;
}
}
}, newProto, true);
// augmenting an instance, so apply the constructor immediately
} else {
applyConstructor = true;
}
Y.mix(target, newProto || sProto, ov, wl);
if (applyConstructor) {
s.apply(target, a);
}
return r;
};
/**
* 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 ov {boolean} if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param wl {string[]} 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 {YUI} the YUI instance
*/
Y.extend = function(r, s, px, sx) {
if (!s||!r) {
// @TODO error symbols
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
* Y.NodeLists
* @method each
* @param o the object to iterate
* @param f the function to execute. This function
* receives the value, key, and object as parameters
* @param 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
* Y.NodeLists.
* @method some
* @param o the object to iterate
* @param f the function to execute. This function
* receives the value, key, and object as parameters
* @param 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 obj/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 o what to clone
* @param safe {boolean} 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 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 c optional execution context for f
* @param owner Owner object passed when clone is iterating an
* object. Used to set up context for cloned functions.
* @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 (o instanceof YUI) {
return o;
}
var o2, marked = cloned || {}, stamp,
each = Y.each || Y.Object.each;
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// return new RegExp(o.source); // if we do this we need to set the flags too
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) {
each(o, function(v, k) {
if (!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) {
delete v[CLONE_MARKER];
});
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 f {Function|String} the function to bind, or a function name
* to execute on the context object
* @param c the execution context
* @param 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 f {Function|String} the function to bind, or a function name
* to execute on the context object
* @param c the execution context
* @param 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);
};
};
}, '@VERSION@' );
|
dryajov/cdnjs
|
ajax/libs/yui/3.1.2/oop/oop-debug.js
|
JavaScript
|
mit
| 12,875
|
/*
* idprom.c: Routines to load the idprom into kernel addresses and
* interpret the data contained within.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Sun3/3x models added by David Monro (davidm@psrg.cs.usyd.edu.au)
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/string.h>
#include <asm/oplib.h>
#include <asm/idprom.h>
#include <asm/machines.h> /* Fun with Sun released architectures. */
struct idprom *idprom;
EXPORT_SYMBOL(idprom);
static struct idprom idprom_buffer;
/* Here is the master table of Sun machines which use some implementation
* of the Sparc CPU and have a meaningful IDPROM machtype value that we
* know about. See asm-sparc/machines.h for empirical constants.
*/
static struct Sun_Machine_Models Sun_Machines[NUM_SUN_MACHINES] = {
/* First, Sun3's */
{ .name = "Sun 3/160 Series", .id_machtype = (SM_SUN3 | SM_3_160) },
{ .name = "Sun 3/50", .id_machtype = (SM_SUN3 | SM_3_50) },
{ .name = "Sun 3/260 Series", .id_machtype = (SM_SUN3 | SM_3_260) },
{ .name = "Sun 3/110 Series", .id_machtype = (SM_SUN3 | SM_3_110) },
{ .name = "Sun 3/60", .id_machtype = (SM_SUN3 | SM_3_60) },
{ .name = "Sun 3/E", .id_machtype = (SM_SUN3 | SM_3_E) },
/* Now, Sun3x's */
{ .name = "Sun 3/460 Series", .id_machtype = (SM_SUN3X | SM_3_460) },
{ .name = "Sun 3/80", .id_machtype = (SM_SUN3X | SM_3_80) },
/* Then, Sun4's */
// { .name = "Sun 4/100 Series", .id_machtype = (SM_SUN4 | SM_4_110) },
// { .name = "Sun 4/200 Series", .id_machtype = (SM_SUN4 | SM_4_260) },
// { .name = "Sun 4/300 Series", .id_machtype = (SM_SUN4 | SM_4_330) },
// { .name = "Sun 4/400 Series", .id_machtype = (SM_SUN4 | SM_4_470) },
/* And now, Sun4c's */
// { .name = "Sun4c SparcStation 1", .id_machtype = (SM_SUN4C | SM_4C_SS1) },
// { .name = "Sun4c SparcStation IPC", .id_machtype = (SM_SUN4C | SM_4C_IPC) },
// { .name = "Sun4c SparcStation 1+", .id_machtype = (SM_SUN4C | SM_4C_SS1PLUS) },
// { .name = "Sun4c SparcStation SLC", .id_machtype = (SM_SUN4C | SM_4C_SLC) },
// { .name = "Sun4c SparcStation 2", .id_machtype = (SM_SUN4C | SM_4C_SS2) },
// { .name = "Sun4c SparcStation ELC", .id_machtype = (SM_SUN4C | SM_4C_ELC) },
// { .name = "Sun4c SparcStation IPX", .id_machtype = (SM_SUN4C | SM_4C_IPX) },
/* Finally, early Sun4m's */
// { .name = "Sun4m SparcSystem600", .id_machtype = (SM_SUN4M | SM_4M_SS60) },
// { .name = "Sun4m SparcStation10/20", .id_machtype = (SM_SUN4M | SM_4M_SS50) },
// { .name = "Sun4m SparcStation5", .id_machtype = (SM_SUN4M | SM_4M_SS40) },
/* One entry for the OBP arch's which are sun4d, sun4e, and newer sun4m's */
// { .name = "Sun4M OBP based system", .id_machtype = (SM_SUN4M_OBP | 0x0) }
};
static void __init display_system_type(unsigned char machtype)
{
register int i;
for (i = 0; i < NUM_SUN_MACHINES; i++) {
if(Sun_Machines[i].id_machtype == machtype) {
if (machtype != (SM_SUN4M_OBP | 0x00))
printk("TYPE: %s\n", Sun_Machines[i].name);
else {
#if 0
prom_getproperty(prom_root_node, "banner-name",
sysname, sizeof(sysname));
printk("TYPE: %s\n", sysname);
#endif
}
return;
}
}
prom_printf("IDPROM: Bogus id_machtype value, 0x%x\n", machtype);
prom_halt();
}
void sun3_get_model(unsigned char* model)
{
register int i;
for (i = 0; i < NUM_SUN_MACHINES; i++) {
if(Sun_Machines[i].id_machtype == idprom->id_machtype) {
strcpy(model, Sun_Machines[i].name);
return;
}
}
}
/* Calculate the IDPROM checksum (xor of the data bytes). */
static unsigned char __init calc_idprom_cksum(struct idprom *idprom)
{
unsigned char cksum, i, *ptr = (unsigned char *)idprom;
for (i = cksum = 0; i <= 0x0E; i++)
cksum ^= *ptr++;
return cksum;
}
/* Create a local IDPROM copy, verify integrity, and display information. */
void __init idprom_init(void)
{
prom_get_idprom((char *) &idprom_buffer, sizeof(idprom_buffer));
idprom = &idprom_buffer;
if (idprom->id_format != 0x01) {
prom_printf("IDPROM: Unknown format type!\n");
prom_halt();
}
if (idprom->id_cksum != calc_idprom_cksum(idprom)) {
prom_printf("IDPROM: Checksum failure (nvram=%x, calc=%x)!\n",
idprom->id_cksum, calc_idprom_cksum(idprom));
prom_halt();
}
display_system_type(idprom->id_machtype);
printk("Ethernet address: %x:%x:%x:%x:%x:%x\n",
idprom->id_ethaddr[0], idprom->id_ethaddr[1],
idprom->id_ethaddr[2], idprom->id_ethaddr[3],
idprom->id_ethaddr[4], idprom->id_ethaddr[5]);
}
|
talnoah/android_kernel_htc_dlx
|
virt/arch/m68k/sun3/idprom.c
|
C
|
gpl-2.0
| 4,541
|
/* $Id: t4.h,v 1.1.1.1 1999/07/27 21:50:27 mike Exp $ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#ifndef _T4_
#define _T4_
/*
* CCITT T.4 1D Huffman runlength codes and
* related definitions. Given the small sizes
* of these tables it does not seem
* worthwhile to make code & length 8 bits.
*/
typedef struct tableentry {
unsigned short length; /* bit length of g3 code */
unsigned short code; /* g3 code */
short runlen; /* run length in bits */
} tableentry;
#define EOL 0x001 /* EOL code value - 0000 0000 0000 1 */
/* status values returned instead of a run length */
#define G3CODE_EOL -1 /* NB: ACT_EOL - ACT_WRUNT */
#define G3CODE_INVALID -2 /* NB: ACT_INVALID - ACT_WRUNT */
#define G3CODE_EOF -3 /* end of input data */
#define G3CODE_INCOMP -4 /* incomplete run code */
/*
* Note that these tables are ordered such that the
* index into the table is known to be either the
* run length, or (run length / 64) + a fixed offset.
*
* NB: The G3CODE_INVALID entries are only used
* during state generation (see mkg3states.c).
*/
#ifdef G3CODES
const tableentry TIFFFaxWhiteCodes[] = {
{ 8, 0x35, 0 }, /* 0011 0101 */
{ 6, 0x7, 1 }, /* 0001 11 */
{ 4, 0x7, 2 }, /* 0111 */
{ 4, 0x8, 3 }, /* 1000 */
{ 4, 0xB, 4 }, /* 1011 */
{ 4, 0xC, 5 }, /* 1100 */
{ 4, 0xE, 6 }, /* 1110 */
{ 4, 0xF, 7 }, /* 1111 */
{ 5, 0x13, 8 }, /* 1001 1 */
{ 5, 0x14, 9 }, /* 1010 0 */
{ 5, 0x7, 10 }, /* 0011 1 */
{ 5, 0x8, 11 }, /* 0100 0 */
{ 6, 0x8, 12 }, /* 0010 00 */
{ 6, 0x3, 13 }, /* 0000 11 */
{ 6, 0x34, 14 }, /* 1101 00 */
{ 6, 0x35, 15 }, /* 1101 01 */
{ 6, 0x2A, 16 }, /* 1010 10 */
{ 6, 0x2B, 17 }, /* 1010 11 */
{ 7, 0x27, 18 }, /* 0100 111 */
{ 7, 0xC, 19 }, /* 0001 100 */
{ 7, 0x8, 20 }, /* 0001 000 */
{ 7, 0x17, 21 }, /* 0010 111 */
{ 7, 0x3, 22 }, /* 0000 011 */
{ 7, 0x4, 23 }, /* 0000 100 */
{ 7, 0x28, 24 }, /* 0101 000 */
{ 7, 0x2B, 25 }, /* 0101 011 */
{ 7, 0x13, 26 }, /* 0010 011 */
{ 7, 0x24, 27 }, /* 0100 100 */
{ 7, 0x18, 28 }, /* 0011 000 */
{ 8, 0x2, 29 }, /* 0000 0010 */
{ 8, 0x3, 30 }, /* 0000 0011 */
{ 8, 0x1A, 31 }, /* 0001 1010 */
{ 8, 0x1B, 32 }, /* 0001 1011 */
{ 8, 0x12, 33 }, /* 0001 0010 */
{ 8, 0x13, 34 }, /* 0001 0011 */
{ 8, 0x14, 35 }, /* 0001 0100 */
{ 8, 0x15, 36 }, /* 0001 0101 */
{ 8, 0x16, 37 }, /* 0001 0110 */
{ 8, 0x17, 38 }, /* 0001 0111 */
{ 8, 0x28, 39 }, /* 0010 1000 */
{ 8, 0x29, 40 }, /* 0010 1001 */
{ 8, 0x2A, 41 }, /* 0010 1010 */
{ 8, 0x2B, 42 }, /* 0010 1011 */
{ 8, 0x2C, 43 }, /* 0010 1100 */
{ 8, 0x2D, 44 }, /* 0010 1101 */
{ 8, 0x4, 45 }, /* 0000 0100 */
{ 8, 0x5, 46 }, /* 0000 0101 */
{ 8, 0xA, 47 }, /* 0000 1010 */
{ 8, 0xB, 48 }, /* 0000 1011 */
{ 8, 0x52, 49 }, /* 0101 0010 */
{ 8, 0x53, 50 }, /* 0101 0011 */
{ 8, 0x54, 51 }, /* 0101 0100 */
{ 8, 0x55, 52 }, /* 0101 0101 */
{ 8, 0x24, 53 }, /* 0010 0100 */
{ 8, 0x25, 54 }, /* 0010 0101 */
{ 8, 0x58, 55 }, /* 0101 1000 */
{ 8, 0x59, 56 }, /* 0101 1001 */
{ 8, 0x5A, 57 }, /* 0101 1010 */
{ 8, 0x5B, 58 }, /* 0101 1011 */
{ 8, 0x4A, 59 }, /* 0100 1010 */
{ 8, 0x4B, 60 }, /* 0100 1011 */
{ 8, 0x32, 61 }, /* 0011 0010 */
{ 8, 0x33, 62 }, /* 0011 0011 */
{ 8, 0x34, 63 }, /* 0011 0100 */
{ 5, 0x1B, 64 }, /* 1101 1 */
{ 5, 0x12, 128 }, /* 1001 0 */
{ 6, 0x17, 192 }, /* 0101 11 */
{ 7, 0x37, 256 }, /* 0110 111 */
{ 8, 0x36, 320 }, /* 0011 0110 */
{ 8, 0x37, 384 }, /* 0011 0111 */
{ 8, 0x64, 448 }, /* 0110 0100 */
{ 8, 0x65, 512 }, /* 0110 0101 */
{ 8, 0x68, 576 }, /* 0110 1000 */
{ 8, 0x67, 640 }, /* 0110 0111 */
{ 9, 0xCC, 704 }, /* 0110 0110 0 */
{ 9, 0xCD, 768 }, /* 0110 0110 1 */
{ 9, 0xD2, 832 }, /* 0110 1001 0 */
{ 9, 0xD3, 896 }, /* 0110 1001 1 */
{ 9, 0xD4, 960 }, /* 0110 1010 0 */
{ 9, 0xD5, 1024 }, /* 0110 1010 1 */
{ 9, 0xD6, 1088 }, /* 0110 1011 0 */
{ 9, 0xD7, 1152 }, /* 0110 1011 1 */
{ 9, 0xD8, 1216 }, /* 0110 1100 0 */
{ 9, 0xD9, 1280 }, /* 0110 1100 1 */
{ 9, 0xDA, 1344 }, /* 0110 1101 0 */
{ 9, 0xDB, 1408 }, /* 0110 1101 1 */
{ 9, 0x98, 1472 }, /* 0100 1100 0 */
{ 9, 0x99, 1536 }, /* 0100 1100 1 */
{ 9, 0x9A, 1600 }, /* 0100 1101 0 */
{ 6, 0x18, 1664 }, /* 0110 00 */
{ 9, 0x9B, 1728 }, /* 0100 1101 1 */
{ 11, 0x8, 1792 }, /* 0000 0001 000 */
{ 11, 0xC, 1856 }, /* 0000 0001 100 */
{ 11, 0xD, 1920 }, /* 0000 0001 101 */
{ 12, 0x12, 1984 }, /* 0000 0001 0010 */
{ 12, 0x13, 2048 }, /* 0000 0001 0011 */
{ 12, 0x14, 2112 }, /* 0000 0001 0100 */
{ 12, 0x15, 2176 }, /* 0000 0001 0101 */
{ 12, 0x16, 2240 }, /* 0000 0001 0110 */
{ 12, 0x17, 2304 }, /* 0000 0001 0111 */
{ 12, 0x1C, 2368 }, /* 0000 0001 1100 */
{ 12, 0x1D, 2432 }, /* 0000 0001 1101 */
{ 12, 0x1E, 2496 }, /* 0000 0001 1110 */
{ 12, 0x1F, 2560 }, /* 0000 0001 1111 */
{ 12, 0x1, G3CODE_EOL }, /* 0000 0000 0001 */
{ 9, 0x1, G3CODE_INVALID }, /* 0000 0000 1 */
{ 10, 0x1, G3CODE_INVALID }, /* 0000 0000 01 */
{ 11, 0x1, G3CODE_INVALID }, /* 0000 0000 001 */
{ 12, 0x0, G3CODE_INVALID }, /* 0000 0000 0000 */
};
const tableentry TIFFFaxBlackCodes[] = {
{ 10, 0x37, 0 }, /* 0000 1101 11 */
{ 3, 0x2, 1 }, /* 010 */
{ 2, 0x3, 2 }, /* 11 */
{ 2, 0x2, 3 }, /* 10 */
{ 3, 0x3, 4 }, /* 011 */
{ 4, 0x3, 5 }, /* 0011 */
{ 4, 0x2, 6 }, /* 0010 */
{ 5, 0x3, 7 }, /* 0001 1 */
{ 6, 0x5, 8 }, /* 0001 01 */
{ 6, 0x4, 9 }, /* 0001 00 */
{ 7, 0x4, 10 }, /* 0000 100 */
{ 7, 0x5, 11 }, /* 0000 101 */
{ 7, 0x7, 12 }, /* 0000 111 */
{ 8, 0x4, 13 }, /* 0000 0100 */
{ 8, 0x7, 14 }, /* 0000 0111 */
{ 9, 0x18, 15 }, /* 0000 1100 0 */
{ 10, 0x17, 16 }, /* 0000 0101 11 */
{ 10, 0x18, 17 }, /* 0000 0110 00 */
{ 10, 0x8, 18 }, /* 0000 0010 00 */
{ 11, 0x67, 19 }, /* 0000 1100 111 */
{ 11, 0x68, 20 }, /* 0000 1101 000 */
{ 11, 0x6C, 21 }, /* 0000 1101 100 */
{ 11, 0x37, 22 }, /* 0000 0110 111 */
{ 11, 0x28, 23 }, /* 0000 0101 000 */
{ 11, 0x17, 24 }, /* 0000 0010 111 */
{ 11, 0x18, 25 }, /* 0000 0011 000 */
{ 12, 0xCA, 26 }, /* 0000 1100 1010 */
{ 12, 0xCB, 27 }, /* 0000 1100 1011 */
{ 12, 0xCC, 28 }, /* 0000 1100 1100 */
{ 12, 0xCD, 29 }, /* 0000 1100 1101 */
{ 12, 0x68, 30 }, /* 0000 0110 1000 */
{ 12, 0x69, 31 }, /* 0000 0110 1001 */
{ 12, 0x6A, 32 }, /* 0000 0110 1010 */
{ 12, 0x6B, 33 }, /* 0000 0110 1011 */
{ 12, 0xD2, 34 }, /* 0000 1101 0010 */
{ 12, 0xD3, 35 }, /* 0000 1101 0011 */
{ 12, 0xD4, 36 }, /* 0000 1101 0100 */
{ 12, 0xD5, 37 }, /* 0000 1101 0101 */
{ 12, 0xD6, 38 }, /* 0000 1101 0110 */
{ 12, 0xD7, 39 }, /* 0000 1101 0111 */
{ 12, 0x6C, 40 }, /* 0000 0110 1100 */
{ 12, 0x6D, 41 }, /* 0000 0110 1101 */
{ 12, 0xDA, 42 }, /* 0000 1101 1010 */
{ 12, 0xDB, 43 }, /* 0000 1101 1011 */
{ 12, 0x54, 44 }, /* 0000 0101 0100 */
{ 12, 0x55, 45 }, /* 0000 0101 0101 */
{ 12, 0x56, 46 }, /* 0000 0101 0110 */
{ 12, 0x57, 47 }, /* 0000 0101 0111 */
{ 12, 0x64, 48 }, /* 0000 0110 0100 */
{ 12, 0x65, 49 }, /* 0000 0110 0101 */
{ 12, 0x52, 50 }, /* 0000 0101 0010 */
{ 12, 0x53, 51 }, /* 0000 0101 0011 */
{ 12, 0x24, 52 }, /* 0000 0010 0100 */
{ 12, 0x37, 53 }, /* 0000 0011 0111 */
{ 12, 0x38, 54 }, /* 0000 0011 1000 */
{ 12, 0x27, 55 }, /* 0000 0010 0111 */
{ 12, 0x28, 56 }, /* 0000 0010 1000 */
{ 12, 0x58, 57 }, /* 0000 0101 1000 */
{ 12, 0x59, 58 }, /* 0000 0101 1001 */
{ 12, 0x2B, 59 }, /* 0000 0010 1011 */
{ 12, 0x2C, 60 }, /* 0000 0010 1100 */
{ 12, 0x5A, 61 }, /* 0000 0101 1010 */
{ 12, 0x66, 62 }, /* 0000 0110 0110 */
{ 12, 0x67, 63 }, /* 0000 0110 0111 */
{ 10, 0xF, 64 }, /* 0000 0011 11 */
{ 12, 0xC8, 128 }, /* 0000 1100 1000 */
{ 12, 0xC9, 192 }, /* 0000 1100 1001 */
{ 12, 0x5B, 256 }, /* 0000 0101 1011 */
{ 12, 0x33, 320 }, /* 0000 0011 0011 */
{ 12, 0x34, 384 }, /* 0000 0011 0100 */
{ 12, 0x35, 448 }, /* 0000 0011 0101 */
{ 13, 0x6C, 512 }, /* 0000 0011 0110 0 */
{ 13, 0x6D, 576 }, /* 0000 0011 0110 1 */
{ 13, 0x4A, 640 }, /* 0000 0010 0101 0 */
{ 13, 0x4B, 704 }, /* 0000 0010 0101 1 */
{ 13, 0x4C, 768 }, /* 0000 0010 0110 0 */
{ 13, 0x4D, 832 }, /* 0000 0010 0110 1 */
{ 13, 0x72, 896 }, /* 0000 0011 1001 0 */
{ 13, 0x73, 960 }, /* 0000 0011 1001 1 */
{ 13, 0x74, 1024 }, /* 0000 0011 1010 0 */
{ 13, 0x75, 1088 }, /* 0000 0011 1010 1 */
{ 13, 0x76, 1152 }, /* 0000 0011 1011 0 */
{ 13, 0x77, 1216 }, /* 0000 0011 1011 1 */
{ 13, 0x52, 1280 }, /* 0000 0010 1001 0 */
{ 13, 0x53, 1344 }, /* 0000 0010 1001 1 */
{ 13, 0x54, 1408 }, /* 0000 0010 1010 0 */
{ 13, 0x55, 1472 }, /* 0000 0010 1010 1 */
{ 13, 0x5A, 1536 }, /* 0000 0010 1101 0 */
{ 13, 0x5B, 1600 }, /* 0000 0010 1101 1 */
{ 13, 0x64, 1664 }, /* 0000 0011 0010 0 */
{ 13, 0x65, 1728 }, /* 0000 0011 0010 1 */
{ 11, 0x8, 1792 }, /* 0000 0001 000 */
{ 11, 0xC, 1856 }, /* 0000 0001 100 */
{ 11, 0xD, 1920 }, /* 0000 0001 101 */
{ 12, 0x12, 1984 }, /* 0000 0001 0010 */
{ 12, 0x13, 2048 }, /* 0000 0001 0011 */
{ 12, 0x14, 2112 }, /* 0000 0001 0100 */
{ 12, 0x15, 2176 }, /* 0000 0001 0101 */
{ 12, 0x16, 2240 }, /* 0000 0001 0110 */
{ 12, 0x17, 2304 }, /* 0000 0001 0111 */
{ 12, 0x1C, 2368 }, /* 0000 0001 1100 */
{ 12, 0x1D, 2432 }, /* 0000 0001 1101 */
{ 12, 0x1E, 2496 }, /* 0000 0001 1110 */
{ 12, 0x1F, 2560 }, /* 0000 0001 1111 */
{ 12, 0x1, G3CODE_EOL }, /* 0000 0000 0001 */
{ 9, 0x1, G3CODE_INVALID }, /* 0000 0000 1 */
{ 10, 0x1, G3CODE_INVALID }, /* 0000 0000 01 */
{ 11, 0x1, G3CODE_INVALID }, /* 0000 0000 001 */
{ 12, 0x0, G3CODE_INVALID }, /* 0000 0000 0000 */
};
#else
extern const tableentry TIFFFaxWhiteCodes[];
extern const tableentry TIFFFaxBlackCodes[];
#endif
#endif /* _T4_ */
|
xbmc/atv2
|
xbmc/lib/cximage-6.0/tiff/t4.h
|
C
|
gpl-2.0
| 11,289
|
from contextlib import contextmanager
from .termui import get_terminal_size
from .parser import split_opt
from ._compat import term_len
# Can force a width. This is used by the test system
FORCED_WIDTH = None
def measure_table(rows):
widths = {}
for row in rows:
for idx, col in enumerate(row):
widths[idx] = max(widths.get(idx, 0), term_len(col))
return tuple(y for x, y in sorted(widths.items()))
def iter_rows(rows, col_count):
for row in rows:
row = tuple(row)
yield row + ('',) * (col_count - len(row))
def wrap_text(text, width=78, initial_indent='', subsequent_indent='',
preserve_paragraphs=False):
"""A helper function that intelligently wraps text. By default, it
assumes that it operates on a single paragraph of text but if the
`preserve_paragraphs` parameter is provided it will intelligently
handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty
line containing the ``\\b`` character (``\\x08``) to indicate that
no rewrapping should happen in that block.
:param text: the text that should be rewrapped.
:param width: the maximum width for the text.
:param initial_indent: the initial indent that should be placed on the
first line as a string.
:param subsequent_indent: the indent string that should be placed on
each consecutive line.
:param preserve_paragraphs: if this flag is set then the wrapping will
intelligently handle paragraphs.
"""
from ._textwrap import TextWrapper
text = text.expandtabs()
wrapper = TextWrapper(width, initial_indent=initial_indent,
subsequent_indent=subsequent_indent,
replace_whitespace=False)
if not preserve_paragraphs:
return wrapper.fill(text)
p = []
buf = []
indent = None
def _flush_par():
if not buf:
return
if buf[0].strip() == '\b':
p.append((indent or 0, True, '\n'.join(buf[1:])))
else:
p.append((indent or 0, False, ' '.join(buf)))
del buf[:]
for line in text.splitlines():
if not line:
_flush_par()
indent = None
else:
if indent is None:
orig_len = term_len(line)
line = line.lstrip()
indent = orig_len - term_len(line)
buf.append(line)
_flush_par()
rv = []
for indent, raw, text in p:
with wrapper.extra_indent(' ' * indent):
if raw:
rv.append(wrapper.indent_only(text))
else:
rv.append(wrapper.fill(text))
return '\n\n'.join(rv)
class HelpFormatter(object):
"""This class helps with formatting text-based help pages. It's
usually just needed for very special internal cases, but it's also
exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
:param indent_increment: the additional increment for each level.
:param width: the width for the text. This defaults to the terminal
width clamped to a maximum of 78.
"""
def __init__(self, indent_increment=2, width=None, max_width=None):
self.indent_increment = indent_increment
if max_width is None:
max_width = 80
if width is None:
width = FORCED_WIDTH
if width is None:
width = max(min(get_terminal_size()[0], max_width) - 2, 50)
self.width = width
self.current_indent = 0
self.buffer = []
def write(self, string):
"""Writes a unicode string into the internal buffer."""
self.buffer.append(string)
def indent(self):
"""Increases the indentation."""
self.current_indent += self.indent_increment
def dedent(self):
"""Decreases the indentation."""
self.current_indent -= self.indent_increment
def write_usage(self, prog, args='', prefix='Usage: '):
"""Writes a usage line into the buffer.
:param prog: the program name.
:param args: whitespace separated list of arguments.
:param prefix: the prefix for the first line.
"""
usage_prefix = '%*s%s ' % (self.current_indent, prefix, prog)
text_width = self.width - self.current_indent
if text_width >= (term_len(usage_prefix) + 20):
# The arguments will fit to the right of the prefix.
indent = ' ' * term_len(usage_prefix)
self.write(wrap_text(args, text_width,
initial_indent=usage_prefix,
subsequent_indent=indent))
else:
# The prefix is too long, put the arguments on the next line.
self.write(usage_prefix)
self.write('\n')
indent = ' ' * (max(self.current_indent, term_len(prefix)) + 4)
self.write(wrap_text(args, text_width,
initial_indent=indent,
subsequent_indent=indent))
self.write('\n')
def write_heading(self, heading):
"""Writes a heading into the buffer."""
self.write('%*s%s:\n' % (self.current_indent, '', heading))
def write_paragraph(self):
"""Writes a paragraph into the buffer."""
if self.buffer:
self.write('\n')
def write_text(self, text):
"""Writes re-indented text into the buffer. This rewraps and
preserves paragraphs.
"""
text_width = max(self.width - self.current_indent, 11)
indent = ' ' * self.current_indent
self.write(wrap_text(text, text_width,
initial_indent=indent,
subsequent_indent=indent,
preserve_paragraphs=True))
self.write('\n')
def write_dl(self, rows, col_max=30, col_spacing=2):
"""Writes a definition list into the buffer. This is how options
and commands are usually formatted.
:param rows: a list of two item tuples for the terms and values.
:param col_max: the maximum width of the first column.
:param col_spacing: the number of spaces between the first and
second column.
"""
rows = list(rows)
widths = measure_table(rows)
if len(widths) != 2:
raise TypeError('Expected two columns for definition list')
first_col = min(widths[0], col_max) + col_spacing
for first, second in iter_rows(rows, len(widths)):
self.write('%*s%s' % (self.current_indent, '', first))
if not second:
self.write('\n')
continue
if term_len(first) <= first_col - col_spacing:
self.write(' ' * (first_col - term_len(first)))
else:
self.write('\n')
self.write(' ' * (first_col + self.current_indent))
text_width = max(self.width - first_col - 2, 10)
lines = iter(wrap_text(second, text_width).splitlines())
if lines:
self.write(next(lines) + '\n')
for line in lines:
self.write('%*s%s\n' % (
first_col + self.current_indent, '', line))
else:
self.write('\n')
@contextmanager
def section(self, name):
"""Helpful context manager that writes a paragraph, a heading,
and the indents.
:param name: the section name that is written as heading.
"""
self.write_paragraph()
self.write_heading(name)
self.indent()
try:
yield
finally:
self.dedent()
@contextmanager
def indentation(self):
"""A context manager that increases the indentation."""
self.indent()
try:
yield
finally:
self.dedent()
def getvalue(self):
"""Returns the buffer contents."""
return ''.join(self.buffer)
def join_options(options):
"""Given a list of option strings this joins them in the most appropriate
way and returns them in the form ``(formatted_string,
any_prefix_is_slash)`` where the second item in the tuple is a flag that
indicates if any of the option prefixes was a slash.
"""
rv = []
any_prefix_is_slash = False
for opt in options:
prefix = split_opt(opt)[0]
if prefix == '/':
any_prefix_is_slash = True
rv.append((len(prefix), opt))
rv.sort(key=lambda x: x[0])
rv = ', '.join(x[1] for x in rv)
return rv, any_prefix_is_slash
|
wildchildyn/autism-website
|
yanni_env/lib/python3.6/site-packages/click/formatting.py
|
Python
|
gpl-3.0
| 8,889
|
/*
* Copyright (C) 2010 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <subdev/fb.h>
struct nv30_fb_priv {
struct nouveau_fb base;
};
void
nv30_fb_tile_init(struct nouveau_fb *pfb, int i, u32 addr, u32 size, u32 pitch,
u32 flags, struct nouveau_fb_tile *tile)
{
/* for performance, select alternate bank offset for zeta */
if (!(flags & 4)) {
tile->addr = (0 << 4);
} else {
if (pfb->tile.comp) /* z compression */
pfb->tile.comp(pfb, i, size, flags, tile);
tile->addr = (1 << 4);
}
tile->addr |= 0x00000001; /* enable */
tile->addr |= addr;
tile->limit = max(1u, addr + size) - 1;
tile->pitch = pitch;
}
static void
nv30_fb_tile_comp(struct nouveau_fb *pfb, int i, u32 size, u32 flags,
struct nouveau_fb_tile *tile)
{
u32 tiles = DIV_ROUND_UP(size, 0x40);
u32 tags = round_up(tiles / pfb->ram.parts, 0x40);
if (!nouveau_mm_head(&pfb->tags, 1, tags, tags, 1, &tile->tag)) {
if (flags & 2) tile->zcomp |= 0x01000000; /* Z16 */
else tile->zcomp |= 0x02000000; /* Z24S8 */
tile->zcomp |= ((tile->tag->offset ) >> 6);
tile->zcomp |= ((tile->tag->offset + tags - 1) >> 6) << 12;
#ifdef __BIG_ENDIAN
tile->zcomp |= 0x10000000;
#endif
}
}
static int
calc_bias(struct nv30_fb_priv *priv, int k, int i, int j)
{
struct nouveau_device *device = nv_device(priv);
int b = (device->chipset > 0x30 ?
nv_rd32(priv, 0x122c + 0x10 * k + 0x4 * j) >> (4 * (i ^ 1)) :
0) & 0xf;
return 2 * (b & 0x8 ? b - 0x10 : b);
}
static int
calc_ref(struct nv30_fb_priv *priv, int l, int k, int i)
{
int j, x = 0;
for (j = 0; j < 4; j++) {
int m = (l >> (8 * i) & 0xff) + calc_bias(priv, k, i, j);
x |= (0x80 | clamp(m, 0, 0x1f)) << (8 * j);
}
return x;
}
int
nv30_fb_init(struct nouveau_object *object)
{
struct nouveau_device *device = nv_device(object);
struct nv30_fb_priv *priv = (void *)object;
int ret, i, j;
ret = nouveau_fb_init(&priv->base);
if (ret)
return ret;
/* Init the memory timing regs at 0x10037c/0x1003ac */
if (device->chipset == 0x30 ||
device->chipset == 0x31 ||
device->chipset == 0x35) {
/* Related to ROP count */
int n = (device->chipset == 0x31 ? 2 : 4);
int l = nv_rd32(priv, 0x1003d0);
for (i = 0; i < n; i++) {
for (j = 0; j < 3; j++)
nv_wr32(priv, 0x10037c + 0xc * i + 0x4 * j,
calc_ref(priv, l, 0, j));
for (j = 0; j < 2; j++)
nv_wr32(priv, 0x1003ac + 0x8 * i + 0x4 * j,
calc_ref(priv, l, 1, j));
}
}
return 0;
}
static int
nv30_fb_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv30_fb_priv *priv;
int ret;
ret = nouveau_fb_create(parent, engine, oclass, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.memtype_valid = nv04_fb_memtype_valid;
priv->base.ram.init = nv20_fb_vram_init;
priv->base.tile.regions = 8;
priv->base.tile.init = nv30_fb_tile_init;
priv->base.tile.comp = nv30_fb_tile_comp;
priv->base.tile.fini = nv20_fb_tile_fini;
priv->base.tile.prog = nv20_fb_tile_prog;
return nouveau_fb_preinit(&priv->base);
}
struct nouveau_oclass
nv30_fb_oclass = {
.handle = NV_SUBDEV(FB, 0x30),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv30_fb_ctor,
.dtor = _nouveau_fb_dtor,
.init = nv30_fb_init,
.fini = _nouveau_fb_fini,
},
};
|
prasidh09/cse506
|
unionfs-3.10.y/drivers/gpu/drm/nouveau/core/subdev/fb/nv30.c
|
C
|
gpl-2.0
| 4,495
|
/*
* vivid-core.c - A Virtual Video Test Driver, core initialization
*
* Copyright 2014 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
*
* This program is free software; you may 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/font.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/v4l2-dv-timings.h>
#include <media/videobuf2-vmalloc.h>
#include <media/v4l2-dv-timings.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include "vivid-core.h"
#include "vivid-vid-common.h"
#include "vivid-vid-cap.h"
#include "vivid-vid-out.h"
#include "vivid-radio-common.h"
#include "vivid-radio-rx.h"
#include "vivid-radio-tx.h"
#include "vivid-sdr-cap.h"
#include "vivid-vbi-cap.h"
#include "vivid-vbi-out.h"
#include "vivid-osd.h"
#include "vivid-ctrls.h"
#define VIVID_MODULE_NAME "vivid"
/* The maximum number of vivid devices */
#define VIVID_MAX_DEVS 64
MODULE_DESCRIPTION("Virtual Video Test Driver");
MODULE_AUTHOR("Hans Verkuil");
MODULE_LICENSE("GPL");
static unsigned n_devs = 1;
module_param(n_devs, uint, 0444);
MODULE_PARM_DESC(n_devs, " number of driver instances to create");
static int vid_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(vid_cap_nr, int, NULL, 0444);
MODULE_PARM_DESC(vid_cap_nr, " videoX start number, -1 is autodetect");
static int vid_out_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(vid_out_nr, int, NULL, 0444);
MODULE_PARM_DESC(vid_out_nr, " videoX start number, -1 is autodetect");
static int vbi_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(vbi_cap_nr, int, NULL, 0444);
MODULE_PARM_DESC(vbi_cap_nr, " vbiX start number, -1 is autodetect");
static int vbi_out_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(vbi_out_nr, int, NULL, 0444);
MODULE_PARM_DESC(vbi_out_nr, " vbiX start number, -1 is autodetect");
static int sdr_cap_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(sdr_cap_nr, int, NULL, 0444);
MODULE_PARM_DESC(sdr_cap_nr, " swradioX start number, -1 is autodetect");
static int radio_rx_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(radio_rx_nr, int, NULL, 0444);
MODULE_PARM_DESC(radio_rx_nr, " radioX start number, -1 is autodetect");
static int radio_tx_nr[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(radio_tx_nr, int, NULL, 0444);
MODULE_PARM_DESC(radio_tx_nr, " radioX start number, -1 is autodetect");
static int ccs_cap_mode[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(ccs_cap_mode, int, NULL, 0444);
MODULE_PARM_DESC(ccs_cap_mode, " capture crop/compose/scale mode:\n"
"\t\t bit 0=crop, 1=compose, 2=scale,\n"
"\t\t -1=user-controlled (default)");
static int ccs_out_mode[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = -1 };
module_param_array(ccs_out_mode, int, NULL, 0444);
MODULE_PARM_DESC(ccs_out_mode, " output crop/compose/scale mode:\n"
"\t\t bit 0=crop, 1=compose, 2=scale,\n"
"\t\t -1=user-controlled (default)");
static unsigned multiplanar[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 1 };
module_param_array(multiplanar, uint, NULL, 0444);
MODULE_PARM_DESC(multiplanar, " 1 (default) creates a single planar device, 2 creates a multiplanar device.");
/* Default: video + vbi-cap (raw and sliced) + radio rx + radio tx + sdr + vbi-out + vid-out */
static unsigned node_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0x1d3d };
module_param_array(node_types, uint, NULL, 0444);
MODULE_PARM_DESC(node_types, " node types, default is 0x1d3d. Bitmask with the following meaning:\n"
"\t\t bit 0: Video Capture node\n"
"\t\t bit 2-3: VBI Capture node: 0 = none, 1 = raw vbi, 2 = sliced vbi, 3 = both\n"
"\t\t bit 4: Radio Receiver node\n"
"\t\t bit 5: Software Defined Radio Receiver node\n"
"\t\t bit 8: Video Output node\n"
"\t\t bit 10-11: VBI Output node: 0 = none, 1 = raw vbi, 2 = sliced vbi, 3 = both\n"
"\t\t bit 12: Radio Transmitter node\n"
"\t\t bit 16: Framebuffer for testing overlays");
/* Default: 4 inputs */
static unsigned num_inputs[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 4 };
module_param_array(num_inputs, uint, NULL, 0444);
MODULE_PARM_DESC(num_inputs, " number of inputs, default is 4");
/* Default: input 0 = WEBCAM, 1 = TV, 2 = SVID, 3 = HDMI */
static unsigned input_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 0xe4 };
module_param_array(input_types, uint, NULL, 0444);
MODULE_PARM_DESC(input_types, " input types, default is 0xe4. Two bits per input,\n"
"\t\t bits 0-1 == input 0, bits 31-30 == input 15.\n"
"\t\t Type 0 == webcam, 1 == TV, 2 == S-Video, 3 == HDMI");
/* Default: 2 outputs */
static unsigned num_outputs[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 2 };
module_param_array(num_outputs, uint, NULL, 0444);
MODULE_PARM_DESC(num_outputs, " number of outputs, default is 2");
/* Default: output 0 = SVID, 1 = HDMI */
static unsigned output_types[VIVID_MAX_DEVS] = { [0 ... (VIVID_MAX_DEVS - 1)] = 2 };
module_param_array(output_types, uint, NULL, 0444);
MODULE_PARM_DESC(output_types, " output types, default is 0x02. One bit per output,\n"
"\t\t bit 0 == output 0, bit 15 == output 15.\n"
"\t\t Type 0 == S-Video, 1 == HDMI");
unsigned vivid_debug;
module_param(vivid_debug, uint, 0644);
MODULE_PARM_DESC(vivid_debug, " activates debug info");
static bool no_error_inj;
module_param(no_error_inj, bool, 0444);
MODULE_PARM_DESC(no_error_inj, " if set disable the error injecting controls");
static struct vivid_dev *vivid_devs[VIVID_MAX_DEVS];
const struct v4l2_rect vivid_min_rect = {
0, 0, MIN_WIDTH, MIN_HEIGHT
};
const struct v4l2_rect vivid_max_rect = {
0, 0, MAX_WIDTH * MAX_ZOOM, MAX_HEIGHT * MAX_ZOOM
};
static const u8 vivid_hdmi_edid[256] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
0x63, 0x3a, 0xaa, 0x55, 0x00, 0x00, 0x00, 0x00,
0x0a, 0x18, 0x01, 0x03, 0x80, 0x10, 0x09, 0x78,
0x0e, 0x00, 0xb2, 0xa0, 0x57, 0x49, 0x9b, 0x26,
0x10, 0x48, 0x4f, 0x2f, 0xcf, 0x00, 0x31, 0x59,
0x45, 0x59, 0x81, 0x80, 0x81, 0x40, 0x90, 0x40,
0x95, 0x00, 0xa9, 0x40, 0xb3, 0x00, 0x02, 0x3a,
0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c,
0x46, 0x00, 0x10, 0x09, 0x00, 0x00, 0x00, 0x1e,
0x00, 0x00, 0x00, 0xfd, 0x00, 0x18, 0x55, 0x18,
0x5e, 0x11, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 'v',
'4', 'l', '2', '-', 'h', 'd', 'm', 'i',
0x0a, 0x0a, 0x0a, 0x0a, 0x00, 0x00, 0x00, 0x10,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf0,
0x02, 0x03, 0x1a, 0xc0, 0x48, 0xa2, 0x10, 0x04,
0x02, 0x01, 0x21, 0x14, 0x13, 0x23, 0x09, 0x07,
0x07, 0x65, 0x03, 0x0c, 0x00, 0x10, 0x00, 0xe2,
0x00, 0x2a, 0x01, 0x1d, 0x00, 0x80, 0x51, 0xd0,
0x1c, 0x20, 0x40, 0x80, 0x35, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a,
0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd7
};
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct vivid_dev *dev = video_drvdata(file);
struct video_device *vdev = video_devdata(file);
strcpy(cap->driver, "vivid");
strcpy(cap->card, "vivid");
snprintf(cap->bus_info, sizeof(cap->bus_info),
"platform:%s", dev->v4l2_dev.name);
if (vdev->vfl_type == VFL_TYPE_GRABBER && vdev->vfl_dir == VFL_DIR_RX)
cap->device_caps = dev->vid_cap_caps;
if (vdev->vfl_type == VFL_TYPE_GRABBER && vdev->vfl_dir == VFL_DIR_TX)
cap->device_caps = dev->vid_out_caps;
else if (vdev->vfl_type == VFL_TYPE_VBI && vdev->vfl_dir == VFL_DIR_RX)
cap->device_caps = dev->vbi_cap_caps;
else if (vdev->vfl_type == VFL_TYPE_VBI && vdev->vfl_dir == VFL_DIR_TX)
cap->device_caps = dev->vbi_out_caps;
else if (vdev->vfl_type == VFL_TYPE_SDR)
cap->device_caps = dev->sdr_cap_caps;
else if (vdev->vfl_type == VFL_TYPE_RADIO && vdev->vfl_dir == VFL_DIR_RX)
cap->device_caps = dev->radio_rx_caps;
else if (vdev->vfl_type == VFL_TYPE_RADIO && vdev->vfl_dir == VFL_DIR_TX)
cap->device_caps = dev->radio_tx_caps;
cap->capabilities = dev->vid_cap_caps | dev->vid_out_caps |
dev->vbi_cap_caps | dev->vbi_out_caps |
dev->radio_rx_caps | dev->radio_tx_caps |
dev->sdr_cap_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int vidioc_s_hw_freq_seek(struct file *file, void *fh, const struct v4l2_hw_freq_seek *a)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_rx_s_hw_freq_seek(file, fh, a);
return -ENOTTY;
}
static int vidioc_enum_freq_bands(struct file *file, void *fh, struct v4l2_frequency_band *band)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_rx_enum_freq_bands(file, fh, band);
if (vdev->vfl_type == VFL_TYPE_SDR)
return vivid_sdr_enum_freq_bands(file, fh, band);
return -ENOTTY;
}
static int vidioc_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_rx_g_tuner(file, fh, vt);
if (vdev->vfl_type == VFL_TYPE_SDR)
return vivid_sdr_g_tuner(file, fh, vt);
return vivid_video_g_tuner(file, fh, vt);
}
static int vidioc_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_rx_s_tuner(file, fh, vt);
if (vdev->vfl_type == VFL_TYPE_SDR)
return vivid_sdr_s_tuner(file, fh, vt);
return vivid_video_s_tuner(file, fh, vt);
}
static int vidioc_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf)
{
struct vivid_dev *dev = video_drvdata(file);
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_g_frequency(file,
vdev->vfl_dir == VFL_DIR_RX ?
&dev->radio_rx_freq : &dev->radio_tx_freq, vf);
if (vdev->vfl_type == VFL_TYPE_SDR)
return vivid_sdr_g_frequency(file, fh, vf);
return vivid_video_g_frequency(file, fh, vf);
}
static int vidioc_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf)
{
struct vivid_dev *dev = video_drvdata(file);
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_type == VFL_TYPE_RADIO)
return vivid_radio_s_frequency(file,
vdev->vfl_dir == VFL_DIR_RX ?
&dev->radio_rx_freq : &dev->radio_tx_freq, vf);
if (vdev->vfl_type == VFL_TYPE_SDR)
return vivid_sdr_s_frequency(file, fh, vf);
return vivid_video_s_frequency(file, fh, vf);
}
static int vidioc_overlay(struct file *file, void *fh, unsigned i)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_overlay(file, fh, i);
return vivid_vid_out_overlay(file, fh, i);
}
static int vidioc_g_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *a)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_g_fbuf(file, fh, a);
return vivid_vid_out_g_fbuf(file, fh, a);
}
static int vidioc_s_fbuf(struct file *file, void *fh, const struct v4l2_framebuffer *a)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_s_fbuf(file, fh, a);
return vivid_vid_out_s_fbuf(file, fh, a);
}
static int vidioc_s_std(struct file *file, void *fh, v4l2_std_id id)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_s_std(file, fh, id);
return vivid_vid_out_s_std(file, fh, id);
}
static int vidioc_s_dv_timings(struct file *file, void *fh, struct v4l2_dv_timings *timings)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_s_dv_timings(file, fh, timings);
return vivid_vid_out_s_dv_timings(file, fh, timings);
}
static int vidioc_cropcap(struct file *file, void *fh, struct v4l2_cropcap *cc)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_cropcap(file, fh, cc);
return vivid_vid_out_cropcap(file, fh, cc);
}
static int vidioc_g_selection(struct file *file, void *fh,
struct v4l2_selection *sel)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_g_selection(file, fh, sel);
return vivid_vid_out_g_selection(file, fh, sel);
}
static int vidioc_s_selection(struct file *file, void *fh,
struct v4l2_selection *sel)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_s_selection(file, fh, sel);
return vivid_vid_out_s_selection(file, fh, sel);
}
static int vidioc_g_parm(struct file *file, void *fh,
struct v4l2_streamparm *parm)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_g_parm(file, fh, parm);
return vivid_vid_out_g_parm(file, fh, parm);
}
static int vidioc_s_parm(struct file *file, void *fh,
struct v4l2_streamparm *parm)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_vid_cap_s_parm(file, fh, parm);
return vivid_vid_out_g_parm(file, fh, parm);
}
static ssize_t vivid_radio_read(struct file *file, char __user *buf,
size_t size, loff_t *offset)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_TX)
return -EINVAL;
return vivid_radio_rx_read(file, buf, size, offset);
}
static ssize_t vivid_radio_write(struct file *file, const char __user *buf,
size_t size, loff_t *offset)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return -EINVAL;
return vivid_radio_tx_write(file, buf, size, offset);
}
static unsigned int vivid_radio_poll(struct file *file, struct poll_table_struct *wait)
{
struct video_device *vdev = video_devdata(file);
if (vdev->vfl_dir == VFL_DIR_RX)
return vivid_radio_rx_poll(file, wait);
return vivid_radio_tx_poll(file, wait);
}
static bool vivid_is_in_use(struct video_device *vdev)
{
unsigned long flags;
bool res;
spin_lock_irqsave(&vdev->fh_lock, flags);
res = !list_empty(&vdev->fh_list);
spin_unlock_irqrestore(&vdev->fh_lock, flags);
return res;
}
static bool vivid_is_last_user(struct vivid_dev *dev)
{
unsigned uses = vivid_is_in_use(&dev->vid_cap_dev) +
vivid_is_in_use(&dev->vid_out_dev) +
vivid_is_in_use(&dev->vbi_cap_dev) +
vivid_is_in_use(&dev->vbi_out_dev) +
vivid_is_in_use(&dev->sdr_cap_dev) +
vivid_is_in_use(&dev->radio_rx_dev) +
vivid_is_in_use(&dev->radio_tx_dev);
return uses == 1;
}
static int vivid_fop_release(struct file *file)
{
struct vivid_dev *dev = video_drvdata(file);
struct video_device *vdev = video_devdata(file);
mutex_lock(&dev->mutex);
if (!no_error_inj && v4l2_fh_is_singular_file(file) &&
!video_is_registered(vdev) && vivid_is_last_user(dev)) {
/*
* I am the last user of this driver, and a disconnect
* was forced (since this video_device is unregistered),
* so re-register all video_device's again.
*/
v4l2_info(&dev->v4l2_dev, "reconnect\n");
set_bit(V4L2_FL_REGISTERED, &dev->vid_cap_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->vid_out_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->vbi_cap_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->vbi_out_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->sdr_cap_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->radio_rx_dev.flags);
set_bit(V4L2_FL_REGISTERED, &dev->radio_tx_dev.flags);
}
mutex_unlock(&dev->mutex);
if (file->private_data == dev->overlay_cap_owner)
dev->overlay_cap_owner = NULL;
if (file->private_data == dev->radio_rx_rds_owner) {
dev->radio_rx_rds_last_block = 0;
dev->radio_rx_rds_owner = NULL;
}
if (file->private_data == dev->radio_tx_rds_owner) {
dev->radio_tx_rds_last_block = 0;
dev->radio_tx_rds_owner = NULL;
}
if (vdev->queue)
return vb2_fop_release(file);
return v4l2_fh_release(file);
}
static const struct v4l2_file_operations vivid_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vivid_fop_release,
.read = vb2_fop_read,
.write = vb2_fop_write,
.poll = vb2_fop_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = vb2_fop_mmap,
};
static const struct v4l2_file_operations vivid_radio_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vivid_fop_release,
.read = vivid_radio_read,
.write = vivid_radio_write,
.poll = vivid_radio_poll,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops vivid_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_enum_fmt_vid_cap_mplane = vidioc_enum_fmt_vid_mplane,
.vidioc_g_fmt_vid_cap_mplane = vidioc_g_fmt_vid_cap_mplane,
.vidioc_try_fmt_vid_cap_mplane = vidioc_try_fmt_vid_cap_mplane,
.vidioc_s_fmt_vid_cap_mplane = vidioc_s_fmt_vid_cap_mplane,
.vidioc_enum_fmt_vid_out = vidioc_enum_fmt_vid,
.vidioc_g_fmt_vid_out = vidioc_g_fmt_vid_out,
.vidioc_try_fmt_vid_out = vidioc_try_fmt_vid_out,
.vidioc_s_fmt_vid_out = vidioc_s_fmt_vid_out,
.vidioc_enum_fmt_vid_out_mplane = vidioc_enum_fmt_vid_mplane,
.vidioc_g_fmt_vid_out_mplane = vidioc_g_fmt_vid_out_mplane,
.vidioc_try_fmt_vid_out_mplane = vidioc_try_fmt_vid_out_mplane,
.vidioc_s_fmt_vid_out_mplane = vidioc_s_fmt_vid_out_mplane,
.vidioc_g_selection = vidioc_g_selection,
.vidioc_s_selection = vidioc_s_selection,
.vidioc_cropcap = vidioc_cropcap,
.vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_try_fmt_vbi_cap = vidioc_g_fmt_vbi_cap,
.vidioc_s_fmt_vbi_cap = vidioc_s_fmt_vbi_cap,
.vidioc_g_fmt_sliced_vbi_cap = vidioc_g_fmt_sliced_vbi_cap,
.vidioc_try_fmt_sliced_vbi_cap = vidioc_try_fmt_sliced_vbi_cap,
.vidioc_s_fmt_sliced_vbi_cap = vidioc_s_fmt_sliced_vbi_cap,
.vidioc_g_sliced_vbi_cap = vidioc_g_sliced_vbi_cap,
.vidioc_g_fmt_vbi_out = vidioc_g_fmt_vbi_out,
.vidioc_try_fmt_vbi_out = vidioc_g_fmt_vbi_out,
.vidioc_s_fmt_vbi_out = vidioc_s_fmt_vbi_out,
.vidioc_g_fmt_sliced_vbi_out = vidioc_g_fmt_sliced_vbi_out,
.vidioc_try_fmt_sliced_vbi_out = vidioc_try_fmt_sliced_vbi_out,
.vidioc_s_fmt_sliced_vbi_out = vidioc_s_fmt_sliced_vbi_out,
.vidioc_enum_fmt_sdr_cap = vidioc_enum_fmt_sdr_cap,
.vidioc_g_fmt_sdr_cap = vidioc_g_fmt_sdr_cap,
.vidioc_try_fmt_sdr_cap = vidioc_g_fmt_sdr_cap,
.vidioc_s_fmt_sdr_cap = vidioc_g_fmt_sdr_cap,
.vidioc_overlay = vidioc_overlay,
.vidioc_enum_framesizes = vidioc_enum_framesizes,
.vidioc_enum_frameintervals = vidioc_enum_frameintervals,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_s_parm = vidioc_s_parm,
.vidioc_enum_fmt_vid_overlay = vidioc_enum_fmt_vid_overlay,
.vidioc_g_fmt_vid_overlay = vidioc_g_fmt_vid_overlay,
.vidioc_try_fmt_vid_overlay = vidioc_try_fmt_vid_overlay,
.vidioc_s_fmt_vid_overlay = vidioc_s_fmt_vid_overlay,
.vidioc_g_fmt_vid_out_overlay = vidioc_g_fmt_vid_out_overlay,
.vidioc_try_fmt_vid_out_overlay = vidioc_try_fmt_vid_out_overlay,
.vidioc_s_fmt_vid_out_overlay = vidioc_s_fmt_vid_out_overlay,
.vidioc_g_fbuf = vidioc_g_fbuf,
.vidioc_s_fbuf = vidioc_s_fbuf,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_expbuf = vb2_ioctl_expbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_enumaudio = vidioc_enumaudio,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_modulator = vidioc_s_modulator,
.vidioc_g_modulator = vidioc_g_modulator,
.vidioc_s_hw_freq_seek = vidioc_s_hw_freq_seek,
.vidioc_enum_freq_bands = vidioc_enum_freq_bands,
.vidioc_enum_output = vidioc_enum_output,
.vidioc_g_output = vidioc_g_output,
.vidioc_s_output = vidioc_s_output,
.vidioc_s_audout = vidioc_s_audout,
.vidioc_g_audout = vidioc_g_audout,
.vidioc_enumaudout = vidioc_enumaudout,
.vidioc_querystd = vidioc_querystd,
.vidioc_g_std = vidioc_g_std,
.vidioc_s_std = vidioc_s_std,
.vidioc_s_dv_timings = vidioc_s_dv_timings,
.vidioc_g_dv_timings = vidioc_g_dv_timings,
.vidioc_query_dv_timings = vidioc_query_dv_timings,
.vidioc_enum_dv_timings = vidioc_enum_dv_timings,
.vidioc_dv_timings_cap = vidioc_dv_timings_cap,
.vidioc_g_edid = vidioc_g_edid,
.vidioc_s_edid = vidioc_s_edid,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = vidioc_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
/* -----------------------------------------------------------------
Initialization and module stuff
------------------------------------------------------------------*/
static int __init vivid_create_instance(int inst)
{
static const struct v4l2_dv_timings def_dv_timings =
V4L2_DV_BT_CEA_1280X720P60;
unsigned in_type_counter[4] = { 0, 0, 0, 0 };
unsigned out_type_counter[4] = { 0, 0, 0, 0 };
int ccs_cap = ccs_cap_mode[inst];
int ccs_out = ccs_out_mode[inst];
bool has_tuner;
bool has_modulator;
struct vivid_dev *dev;
struct video_device *vfd;
struct vb2_queue *q;
unsigned node_type = node_types[inst];
v4l2_std_id tvnorms_cap = 0, tvnorms_out = 0;
int ret;
int i;
/* allocate main vivid state structure */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->inst = inst;
/* register v4l2_device */
snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name),
"%s-%03d", VIVID_MODULE_NAME, inst);
ret = v4l2_device_register(NULL, &dev->v4l2_dev);
if (ret)
goto free_dev;
/* start detecting feature set */
/* do we use single- or multi-planar? */
dev->multiplanar = multiplanar[inst] > 1;
v4l2_info(&dev->v4l2_dev, "using %splanar format API\n",
dev->multiplanar ? "multi" : "single ");
/* how many inputs do we have and of what type? */
dev->num_inputs = num_inputs[inst];
if (dev->num_inputs < 1)
dev->num_inputs = 1;
if (dev->num_inputs >= MAX_INPUTS)
dev->num_inputs = MAX_INPUTS;
for (i = 0; i < dev->num_inputs; i++) {
dev->input_type[i] = (input_types[inst] >> (i * 2)) & 0x3;
dev->input_name_counter[i] = in_type_counter[dev->input_type[i]]++;
}
dev->has_audio_inputs = in_type_counter[TV] && in_type_counter[SVID];
/* how many outputs do we have and of what type? */
dev->num_outputs = num_outputs[inst];
if (dev->num_outputs < 1)
dev->num_outputs = 1;
if (dev->num_outputs >= MAX_OUTPUTS)
dev->num_outputs = MAX_OUTPUTS;
for (i = 0; i < dev->num_outputs; i++) {
dev->output_type[i] = ((output_types[inst] >> i) & 1) ? HDMI : SVID;
dev->output_name_counter[i] = out_type_counter[dev->output_type[i]]++;
}
dev->has_audio_outputs = out_type_counter[SVID];
/* do we create a video capture device? */
dev->has_vid_cap = node_type & 0x0001;
/* do we create a vbi capture device? */
if (in_type_counter[TV] || in_type_counter[SVID]) {
dev->has_raw_vbi_cap = node_type & 0x0004;
dev->has_sliced_vbi_cap = node_type & 0x0008;
dev->has_vbi_cap = dev->has_raw_vbi_cap | dev->has_sliced_vbi_cap;
}
/* do we create a video output device? */
dev->has_vid_out = node_type & 0x0100;
/* do we create a vbi output device? */
if (out_type_counter[SVID]) {
dev->has_raw_vbi_out = node_type & 0x0400;
dev->has_sliced_vbi_out = node_type & 0x0800;
dev->has_vbi_out = dev->has_raw_vbi_out | dev->has_sliced_vbi_out;
}
/* do we create a radio receiver device? */
dev->has_radio_rx = node_type & 0x0010;
/* do we create a radio transmitter device? */
dev->has_radio_tx = node_type & 0x1000;
/* do we create a software defined radio capture device? */
dev->has_sdr_cap = node_type & 0x0020;
/* do we have a tuner? */
has_tuner = ((dev->has_vid_cap || dev->has_vbi_cap) && in_type_counter[TV]) ||
dev->has_radio_rx || dev->has_sdr_cap;
/* do we have a modulator? */
has_modulator = dev->has_radio_tx;
if (dev->has_vid_cap)
/* do we have a framebuffer for overlay testing? */
dev->has_fb = node_type & 0x10000;
/* can we do crop/compose/scaling while capturing? */
if (no_error_inj && ccs_cap == -1)
ccs_cap = 7;
/* if ccs_cap == -1, then the use can select it using controls */
if (ccs_cap != -1) {
dev->has_crop_cap = ccs_cap & 1;
dev->has_compose_cap = ccs_cap & 2;
dev->has_scaler_cap = ccs_cap & 4;
v4l2_info(&dev->v4l2_dev, "Capture Crop: %c Compose: %c Scaler: %c\n",
dev->has_crop_cap ? 'Y' : 'N',
dev->has_compose_cap ? 'Y' : 'N',
dev->has_scaler_cap ? 'Y' : 'N');
}
/* can we do crop/compose/scaling with video output? */
if (no_error_inj && ccs_out == -1)
ccs_out = 7;
/* if ccs_out == -1, then the use can select it using controls */
if (ccs_out != -1) {
dev->has_crop_out = ccs_out & 1;
dev->has_compose_out = ccs_out & 2;
dev->has_scaler_out = ccs_out & 4;
v4l2_info(&dev->v4l2_dev, "Output Crop: %c Compose: %c Scaler: %c\n",
dev->has_crop_out ? 'Y' : 'N',
dev->has_compose_out ? 'Y' : 'N',
dev->has_scaler_out ? 'Y' : 'N');
}
/* end detecting feature set */
if (dev->has_vid_cap) {
/* set up the capabilities of the video capture device */
dev->vid_cap_caps = dev->multiplanar ?
V4L2_CAP_VIDEO_CAPTURE_MPLANE :
V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OVERLAY;
dev->vid_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
if (dev->has_audio_inputs)
dev->vid_cap_caps |= V4L2_CAP_AUDIO;
if (in_type_counter[TV])
dev->vid_cap_caps |= V4L2_CAP_TUNER;
}
if (dev->has_vid_out) {
/* set up the capabilities of the video output device */
dev->vid_out_caps = dev->multiplanar ?
V4L2_CAP_VIDEO_OUTPUT_MPLANE :
V4L2_CAP_VIDEO_OUTPUT;
if (dev->has_fb)
dev->vid_out_caps |= V4L2_CAP_VIDEO_OUTPUT_OVERLAY;
dev->vid_out_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
if (dev->has_audio_outputs)
dev->vid_out_caps |= V4L2_CAP_AUDIO;
}
if (dev->has_vbi_cap) {
/* set up the capabilities of the vbi capture device */
dev->vbi_cap_caps = (dev->has_raw_vbi_cap ? V4L2_CAP_VBI_CAPTURE : 0) |
(dev->has_sliced_vbi_cap ? V4L2_CAP_SLICED_VBI_CAPTURE : 0);
dev->vbi_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
if (dev->has_audio_inputs)
dev->vbi_cap_caps |= V4L2_CAP_AUDIO;
if (in_type_counter[TV])
dev->vbi_cap_caps |= V4L2_CAP_TUNER;
}
if (dev->has_vbi_out) {
/* set up the capabilities of the vbi output device */
dev->vbi_out_caps = (dev->has_raw_vbi_out ? V4L2_CAP_VBI_OUTPUT : 0) |
(dev->has_sliced_vbi_out ? V4L2_CAP_SLICED_VBI_OUTPUT : 0);
dev->vbi_out_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
if (dev->has_audio_outputs)
dev->vbi_out_caps |= V4L2_CAP_AUDIO;
}
if (dev->has_sdr_cap) {
/* set up the capabilities of the sdr capture device */
dev->sdr_cap_caps = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER;
dev->sdr_cap_caps |= V4L2_CAP_STREAMING | V4L2_CAP_READWRITE;
}
/* set up the capabilities of the radio receiver device */
if (dev->has_radio_rx)
dev->radio_rx_caps = V4L2_CAP_RADIO | V4L2_CAP_RDS_CAPTURE |
V4L2_CAP_HW_FREQ_SEEK | V4L2_CAP_TUNER |
V4L2_CAP_READWRITE;
/* set up the capabilities of the radio transmitter device */
if (dev->has_radio_tx)
dev->radio_tx_caps = V4L2_CAP_RDS_OUTPUT | V4L2_CAP_MODULATOR |
V4L2_CAP_READWRITE;
/* initialize the test pattern generator */
tpg_init(&dev->tpg, 640, 360);
if (tpg_alloc(&dev->tpg, MAX_ZOOM * MAX_WIDTH))
goto free_dev;
dev->scaled_line = vzalloc(MAX_ZOOM * MAX_WIDTH);
if (!dev->scaled_line)
goto free_dev;
dev->blended_line = vzalloc(MAX_ZOOM * MAX_WIDTH);
if (!dev->blended_line)
goto free_dev;
/* load the edid */
dev->edid = vmalloc(256 * 128);
if (!dev->edid)
goto free_dev;
/* create a string array containing the names of all the preset timings */
while (v4l2_dv_timings_presets[dev->query_dv_timings_size].bt.width)
dev->query_dv_timings_size++;
dev->query_dv_timings_qmenu = kmalloc(dev->query_dv_timings_size *
(sizeof(void *) + 32), GFP_KERNEL);
if (dev->query_dv_timings_qmenu == NULL)
goto free_dev;
for (i = 0; i < dev->query_dv_timings_size; i++) {
const struct v4l2_bt_timings *bt = &v4l2_dv_timings_presets[i].bt;
char *p = (char *)&dev->query_dv_timings_qmenu[dev->query_dv_timings_size];
u32 htot, vtot;
p += i * 32;
dev->query_dv_timings_qmenu[i] = p;
htot = V4L2_DV_BT_FRAME_WIDTH(bt);
vtot = V4L2_DV_BT_FRAME_HEIGHT(bt);
snprintf(p, 32, "%ux%u%s%u",
bt->width, bt->height, bt->interlaced ? "i" : "p",
(u32)bt->pixelclock / (htot * vtot));
}
/* disable invalid ioctls based on the feature set */
if (!dev->has_audio_inputs) {
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_AUDIO);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_AUDIO);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUMAUDIO);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_AUDIO);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_AUDIO);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_ENUMAUDIO);
}
if (!dev->has_audio_outputs) {
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_AUDOUT);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_AUDOUT);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUMAUDOUT);
v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_S_AUDOUT);
v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_G_AUDOUT);
v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_ENUMAUDOUT);
}
if (!in_type_counter[TV] && !in_type_counter[SVID]) {
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_STD);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_STD);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUMSTD);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_QUERYSTD);
}
if (!out_type_counter[SVID]) {
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_STD);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_STD);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUMSTD);
}
if (!has_tuner && !has_modulator) {
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_FREQUENCY);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_FREQUENCY);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_FREQUENCY);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_FREQUENCY);
}
if (!has_tuner) {
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_TUNER);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_TUNER);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_TUNER);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_G_TUNER);
}
if (in_type_counter[HDMI] == 0) {
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_EDID);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_EDID);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_DV_TIMINGS_CAP);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_G_DV_TIMINGS);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_DV_TIMINGS);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_ENUM_DV_TIMINGS);
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_QUERY_DV_TIMINGS);
}
if (out_type_counter[HDMI] == 0) {
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_EDID);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_DV_TIMINGS_CAP);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_DV_TIMINGS);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_DV_TIMINGS);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_DV_TIMINGS);
}
if (!dev->has_fb) {
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_FBUF);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_FBUF);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_OVERLAY);
}
v4l2_disable_ioctl(&dev->vid_cap_dev, VIDIOC_S_HW_FREQ_SEEK);
v4l2_disable_ioctl(&dev->vbi_cap_dev, VIDIOC_S_HW_FREQ_SEEK);
v4l2_disable_ioctl(&dev->sdr_cap_dev, VIDIOC_S_HW_FREQ_SEEK);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_S_FREQUENCY);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_G_FREQUENCY);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_FRAMESIZES);
v4l2_disable_ioctl(&dev->vid_out_dev, VIDIOC_ENUM_FRAMEINTERVALS);
v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_S_FREQUENCY);
v4l2_disable_ioctl(&dev->vbi_out_dev, VIDIOC_G_FREQUENCY);
/* configure internal data */
dev->fmt_cap = &vivid_formats[0];
dev->fmt_out = &vivid_formats[0];
if (!dev->multiplanar)
vivid_formats[0].data_offset[0] = 0;
dev->webcam_size_idx = 1;
dev->webcam_ival_idx = 3;
tpg_s_fourcc(&dev->tpg, dev->fmt_cap->fourcc);
dev->std_cap = V4L2_STD_PAL;
dev->std_out = V4L2_STD_PAL;
if (dev->input_type[0] == TV || dev->input_type[0] == SVID)
tvnorms_cap = V4L2_STD_ALL;
if (dev->output_type[0] == SVID)
tvnorms_out = V4L2_STD_ALL;
dev->dv_timings_cap = def_dv_timings;
dev->dv_timings_out = def_dv_timings;
dev->tv_freq = 2804 /* 175.25 * 16 */;
dev->tv_audmode = V4L2_TUNER_MODE_STEREO;
dev->tv_field_cap = V4L2_FIELD_INTERLACED;
dev->tv_field_out = V4L2_FIELD_INTERLACED;
dev->radio_rx_freq = 95000 * 16;
dev->radio_rx_audmode = V4L2_TUNER_MODE_STEREO;
if (dev->has_radio_tx) {
dev->radio_tx_freq = 95500 * 16;
dev->radio_rds_loop = false;
}
dev->radio_tx_subchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_RDS;
dev->sdr_adc_freq = 300000;
dev->sdr_fm_freq = 50000000;
dev->edid_max_blocks = dev->edid_blocks = 2;
memcpy(dev->edid, vivid_hdmi_edid, sizeof(vivid_hdmi_edid));
ktime_get_ts(&dev->radio_rds_init_ts);
/* create all controls */
ret = vivid_create_controls(dev, ccs_cap == -1, ccs_out == -1, no_error_inj,
in_type_counter[TV] || in_type_counter[SVID] ||
out_type_counter[SVID],
in_type_counter[HDMI] || out_type_counter[HDMI]);
if (ret)
goto unreg_dev;
/*
* update the capture and output formats to do a proper initial
* configuration.
*/
vivid_update_format_cap(dev, false);
vivid_update_format_out(dev);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vid_cap);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vid_out);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vbi_cap);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_vbi_out);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_radio_rx);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_radio_tx);
v4l2_ctrl_handler_setup(&dev->ctrl_hdl_sdr_cap);
/* initialize overlay */
dev->fb_cap.fmt.width = dev->src_rect.width;
dev->fb_cap.fmt.height = dev->src_rect.height;
dev->fb_cap.fmt.pixelformat = dev->fmt_cap->fourcc;
dev->fb_cap.fmt.bytesperline = dev->src_rect.width * tpg_g_twopixelsize(&dev->tpg, 0) / 2;
dev->fb_cap.fmt.sizeimage = dev->src_rect.height * dev->fb_cap.fmt.bytesperline;
/* initialize locks */
spin_lock_init(&dev->slock);
mutex_init(&dev->mutex);
/* init dma queues */
INIT_LIST_HEAD(&dev->vid_cap_active);
INIT_LIST_HEAD(&dev->vid_out_active);
INIT_LIST_HEAD(&dev->vbi_cap_active);
INIT_LIST_HEAD(&dev->vbi_out_active);
INIT_LIST_HEAD(&dev->sdr_cap_active);
/* start creating the vb2 queues */
if (dev->has_vid_cap) {
/* initialize vid_cap queue */
q = &dev->vb_vid_cap_q;
q->type = dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :
V4L2_BUF_TYPE_VIDEO_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct vivid_buffer);
q->ops = &vivid_vid_cap_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 2;
q->lock = &dev->mutex;
ret = vb2_queue_init(q);
if (ret)
goto unreg_dev;
}
if (dev->has_vid_out) {
/* initialize vid_out queue */
q = &dev->vb_vid_out_q;
q->type = dev->multiplanar ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE :
V4L2_BUF_TYPE_VIDEO_OUTPUT;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_WRITE;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct vivid_buffer);
q->ops = &vivid_vid_out_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 2;
q->lock = &dev->mutex;
ret = vb2_queue_init(q);
if (ret)
goto unreg_dev;
}
if (dev->has_vbi_cap) {
/* initialize vbi_cap queue */
q = &dev->vb_vbi_cap_q;
q->type = dev->has_raw_vbi_cap ? V4L2_BUF_TYPE_VBI_CAPTURE :
V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct vivid_buffer);
q->ops = &vivid_vbi_cap_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 2;
q->lock = &dev->mutex;
ret = vb2_queue_init(q);
if (ret)
goto unreg_dev;
}
if (dev->has_vbi_out) {
/* initialize vbi_out queue */
q = &dev->vb_vbi_out_q;
q->type = dev->has_raw_vbi_out ? V4L2_BUF_TYPE_VBI_OUTPUT :
V4L2_BUF_TYPE_SLICED_VBI_OUTPUT;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_WRITE;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct vivid_buffer);
q->ops = &vivid_vbi_out_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 2;
q->lock = &dev->mutex;
ret = vb2_queue_init(q);
if (ret)
goto unreg_dev;
}
if (dev->has_sdr_cap) {
/* initialize sdr_cap queue */
q = &dev->vb_sdr_cap_q;
q->type = V4L2_BUF_TYPE_SDR_CAPTURE;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
q->drv_priv = dev;
q->buf_struct_size = sizeof(struct vivid_buffer);
q->ops = &vivid_sdr_cap_qops;
q->mem_ops = &vb2_vmalloc_memops;
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 8;
q->lock = &dev->mutex;
ret = vb2_queue_init(q);
if (ret)
goto unreg_dev;
}
if (dev->has_fb) {
/* Create framebuffer for testing capture/output overlay */
ret = vivid_fb_init(dev);
if (ret)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "Framebuffer device registered as fb%d\n",
dev->fb_info.node);
}
/* finally start creating the device nodes */
if (dev->has_vid_cap) {
vfd = &dev->vid_cap_dev;
strlcpy(vfd->name, "vivid-vid-cap", sizeof(vfd->name));
vfd->fops = &vivid_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->queue = &dev->vb_vid_cap_q;
vfd->tvnorms = tvnorms_cap;
/*
* Provide a mutex to v4l2 core. It will be used to protect
* all fops and v4l2 ioctls.
*/
vfd->lock = &dev->mutex;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_GRABBER, vid_cap_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s\n",
video_device_node_name(vfd));
}
if (dev->has_vid_out) {
vfd = &dev->vid_out_dev;
strlcpy(vfd->name, "vivid-vid-out", sizeof(vfd->name));
vfd->vfl_dir = VFL_DIR_TX;
vfd->fops = &vivid_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->queue = &dev->vb_vid_out_q;
vfd->tvnorms = tvnorms_out;
/*
* Provide a mutex to v4l2 core. It will be used to protect
* all fops and v4l2 ioctls.
*/
vfd->lock = &dev->mutex;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_GRABBER, vid_out_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 output device registered as %s\n",
video_device_node_name(vfd));
}
if (dev->has_vbi_cap) {
vfd = &dev->vbi_cap_dev;
strlcpy(vfd->name, "vivid-vbi-cap", sizeof(vfd->name));
vfd->fops = &vivid_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->queue = &dev->vb_vbi_cap_q;
vfd->lock = &dev->mutex;
vfd->tvnorms = tvnorms_cap;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_VBI, vbi_cap_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s, supports %s VBI\n",
video_device_node_name(vfd),
(dev->has_raw_vbi_cap && dev->has_sliced_vbi_cap) ?
"raw and sliced" :
(dev->has_raw_vbi_cap ? "raw" : "sliced"));
}
if (dev->has_vbi_out) {
vfd = &dev->vbi_out_dev;
strlcpy(vfd->name, "vivid-vbi-out", sizeof(vfd->name));
vfd->vfl_dir = VFL_DIR_TX;
vfd->fops = &vivid_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->queue = &dev->vb_vbi_out_q;
vfd->lock = &dev->mutex;
vfd->tvnorms = tvnorms_out;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_VBI, vbi_out_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 output device registered as %s, supports %s VBI\n",
video_device_node_name(vfd),
(dev->has_raw_vbi_out && dev->has_sliced_vbi_out) ?
"raw and sliced" :
(dev->has_raw_vbi_out ? "raw" : "sliced"));
}
if (dev->has_sdr_cap) {
vfd = &dev->sdr_cap_dev;
strlcpy(vfd->name, "vivid-sdr-cap", sizeof(vfd->name));
vfd->fops = &vivid_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->queue = &dev->vb_sdr_cap_q;
vfd->lock = &dev->mutex;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_SDR, sdr_cap_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 capture device registered as %s\n",
video_device_node_name(vfd));
}
if (dev->has_radio_rx) {
vfd = &dev->radio_rx_dev;
strlcpy(vfd->name, "vivid-rad-rx", sizeof(vfd->name));
vfd->fops = &vivid_radio_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->lock = &dev->mutex;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_RADIO, radio_rx_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 receiver device registered as %s\n",
video_device_node_name(vfd));
}
if (dev->has_radio_tx) {
vfd = &dev->radio_tx_dev;
strlcpy(vfd->name, "vivid-rad-tx", sizeof(vfd->name));
vfd->vfl_dir = VFL_DIR_TX;
vfd->fops = &vivid_radio_fops;
vfd->ioctl_ops = &vivid_ioctl_ops;
vfd->release = video_device_release_empty;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->lock = &dev->mutex;
video_set_drvdata(vfd, dev);
ret = video_register_device(vfd, VFL_TYPE_RADIO, radio_tx_nr[inst]);
if (ret < 0)
goto unreg_dev;
v4l2_info(&dev->v4l2_dev, "V4L2 transmitter device registered as %s\n",
video_device_node_name(vfd));
}
/* Now that everything is fine, let's add it to device list */
vivid_devs[inst] = dev;
return 0;
unreg_dev:
video_unregister_device(&dev->radio_tx_dev);
video_unregister_device(&dev->radio_rx_dev);
video_unregister_device(&dev->sdr_cap_dev);
video_unregister_device(&dev->vbi_out_dev);
video_unregister_device(&dev->vbi_cap_dev);
video_unregister_device(&dev->vid_out_dev);
video_unregister_device(&dev->vid_cap_dev);
vivid_free_controls(dev);
v4l2_device_unregister(&dev->v4l2_dev);
free_dev:
vfree(dev->scaled_line);
vfree(dev->blended_line);
vfree(dev->edid);
tpg_free(&dev->tpg);
kfree(dev->query_dv_timings_qmenu);
kfree(dev);
return ret;
}
/* This routine allocates from 1 to n_devs virtual drivers.
The real maximum number of virtual drivers will depend on how many drivers
will succeed. This is limited to the maximum number of devices that
videodev supports, which is equal to VIDEO_NUM_DEVICES.
*/
static int __init vivid_init(void)
{
const struct font_desc *font = find_font("VGA8x16");
int ret = 0, i;
if (font == NULL) {
pr_err("vivid: could not find font\n");
return -ENODEV;
}
tpg_set_font(font->data);
n_devs = clamp_t(unsigned, n_devs, 1, VIVID_MAX_DEVS);
for (i = 0; i < n_devs; i++) {
ret = vivid_create_instance(i);
if (ret) {
/* If some instantiations succeeded, keep driver */
if (i)
ret = 0;
break;
}
}
if (ret < 0) {
pr_err("vivid: error %d while loading driver\n", ret);
return ret;
}
/* n_devs will reflect the actual number of allocated devices */
n_devs = i;
return ret;
}
static void __exit vivid_exit(void)
{
struct vivid_dev *dev;
unsigned i;
for (i = 0; vivid_devs[i]; i++) {
dev = vivid_devs[i];
if (dev->has_vid_cap) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->vid_cap_dev));
video_unregister_device(&dev->vid_cap_dev);
}
if (dev->has_vid_out) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->vid_out_dev));
video_unregister_device(&dev->vid_out_dev);
}
if (dev->has_vbi_cap) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->vbi_cap_dev));
video_unregister_device(&dev->vbi_cap_dev);
}
if (dev->has_vbi_out) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->vbi_out_dev));
video_unregister_device(&dev->vbi_out_dev);
}
if (dev->has_sdr_cap) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->sdr_cap_dev));
video_unregister_device(&dev->sdr_cap_dev);
}
if (dev->has_radio_rx) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->radio_rx_dev));
video_unregister_device(&dev->radio_rx_dev);
}
if (dev->has_radio_tx) {
v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
video_device_node_name(&dev->radio_tx_dev));
video_unregister_device(&dev->radio_tx_dev);
}
if (dev->has_fb) {
v4l2_info(&dev->v4l2_dev, "unregistering fb%d\n",
dev->fb_info.node);
unregister_framebuffer(&dev->fb_info);
vivid_fb_release_buffers(dev);
}
v4l2_device_unregister(&dev->v4l2_dev);
vivid_free_controls(dev);
vfree(dev->scaled_line);
vfree(dev->blended_line);
vfree(dev->edid);
vfree(dev->bitmap_cap);
vfree(dev->bitmap_out);
tpg_free(&dev->tpg);
kfree(dev->query_dv_timings_qmenu);
kfree(dev);
vivid_devs[i] = NULL;
}
}
module_init(vivid_init);
module_exit(vivid_exit);
|
systemdaemon/systemd
|
src/linux/drivers/media/platform/vivid/vivid-core.c
|
C
|
gpl-2.0
| 47,731
|
/*
* linux/drivers/mmc/core/sd_ops.h
*
* Copyright 2006-2007 Pierre Ossman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include "core.h"
#include "sd_ops.h"
int mmc_app_cmd(struct mmc_host *host, struct mmc_card *card)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!host);
BUG_ON(card && (card->host != host));
cmd.opcode = MMC_APP_CMD;
if (card) {
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
} else {
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_BCR;
}
err = mmc_wait_for_cmd(host, &cmd, 0);
if (err)
return err;
/* Check that card supported application commands */
if (!mmc_host_is_spi(host) && !(cmd.resp[0] & R1_APP_CMD))
return -EOPNOTSUPP;
return 0;
}
EXPORT_SYMBOL_GPL(mmc_app_cmd);
/**
* mmc_wait_for_app_cmd - start an application command and wait for
completion
* @host: MMC host to start command
* @card: Card to send MMC_APP_CMD to
* @cmd: MMC command to start
* @retries: maximum number of retries
*
* Sends a MMC_APP_CMD, checks the card response, sends the command
* in the parameter and waits for it to complete. Return any error
* that occurred while the command was executing. Do not attempt to
* parse the response.
*/
int mmc_wait_for_app_cmd(struct mmc_host *host, struct mmc_card *card,
struct mmc_command *cmd, int retries)
{
struct mmc_request mrq = {0};
int i, err;
BUG_ON(!cmd);
BUG_ON(retries < 0);
err = -EIO;
/*
* We have to resend MMC_APP_CMD for each attempt so
* we cannot use the retries field in mmc_command.
*/
for (i = 0;i <= retries;i++) {
err = mmc_app_cmd(host, card);
if (err) {
/* no point in retrying; no APP commands allowed */
if (mmc_host_is_spi(host)) {
if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
break;
}
continue;
}
memset(&mrq, 0, sizeof(struct mmc_request));
memset(cmd->resp, 0, sizeof(cmd->resp));
cmd->retries = 0;
mrq.cmd = cmd;
cmd->data = NULL;
mmc_wait_for_req(host, &mrq);
err = cmd->error;
if (!cmd->error)
break;
/* no point in retrying illegal APP commands */
if (mmc_host_is_spi(host)) {
if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND)
break;
}
}
return err;
}
EXPORT_SYMBOL(mmc_wait_for_app_cmd);
int mmc_app_set_bus_width(struct mmc_card *card, int width)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!card);
BUG_ON(!card->host);
cmd.opcode = SD_APP_SET_BUS_WIDTH;
cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
switch (width) {
case MMC_BUS_WIDTH_1:
cmd.arg = SD_BUS_WIDTH_1;
break;
case MMC_BUS_WIDTH_4:
cmd.arg = SD_BUS_WIDTH_4;
break;
default:
return -EINVAL;
}
err = mmc_wait_for_app_cmd(card->host, card, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
return 0;
}
int mmc_send_app_op_cond(struct mmc_host *host, u32 ocr, u32 *rocr)
{
struct mmc_command cmd = {0};
int i, err = 0;
BUG_ON(!host);
cmd.opcode = SD_APP_OP_COND;
if (mmc_host_is_spi(host))
cmd.arg = ocr & (1 << 30); /* SPI only defines one bit */
else
cmd.arg = ocr;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R3 | MMC_CMD_BCR;
for (i = 100; i; i--) {
err = mmc_wait_for_app_cmd(host, NULL, &cmd, MMC_CMD_RETRIES);
if (err)
break;
/* if we're just probing, do a single pass */
if (ocr == 0)
break;
/* otherwise wait until reset completes */
if (mmc_host_is_spi(host)) {
if (!(cmd.resp[0] & R1_SPI_IDLE))
break;
} else {
if (cmd.resp[0] & MMC_CARD_BUSY)
break;
}
err = -ETIMEDOUT;
mmc_delay(10);
}
if (rocr && !mmc_host_is_spi(host))
*rocr = cmd.resp[0];
return err;
}
int mmc_send_if_cond(struct mmc_host *host, u32 ocr)
{
struct mmc_command cmd = {0};
int err;
static const u8 test_pattern = 0xAA;
u8 result_pattern;
/*
* To support SD 2.0 cards, we must always invoke SD_SEND_IF_COND
* before SD_APP_OP_COND. This command will harmlessly fail for
* SD 1.0 cards.
*/
cmd.opcode = SD_SEND_IF_COND;
cmd.arg = ((ocr & 0xFF8000) != 0) << 8 | test_pattern;
cmd.flags = MMC_RSP_SPI_R7 | MMC_RSP_R7 | MMC_CMD_BCR;
err = mmc_wait_for_cmd(host, &cmd, 0);
if (err)
return err;
if (mmc_host_is_spi(host))
result_pattern = cmd.resp[1] & 0xFF;
else
result_pattern = cmd.resp[0] & 0xFF;
if (result_pattern != test_pattern)
return -EIO;
return 0;
}
int mmc_send_relative_addr(struct mmc_host *host, unsigned int *rca)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!host);
BUG_ON(!rca);
cmd.opcode = SD_SEND_RELATIVE_ADDR;
cmd.arg = 0;
cmd.flags = MMC_RSP_R6 | MMC_CMD_BCR;
err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
*rca = cmd.resp[0] >> 16;
return 0;
}
int mmc_app_send_scr(struct mmc_card *card, u32 *scr)
{
int err;
struct mmc_request mrq = {0};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
void *data_buf;
BUG_ON(!card);
BUG_ON(!card->host);
BUG_ON(!scr);
/* NOTE: caller guarantees scr is heap-allocated */
err = mmc_app_cmd(card->host, card);
if (err)
return err;
/* dma onto stack is unsafe/nonportable, but callers to this
* routine normally provide temporary on-stack buffers ...
*/
data_buf = kmalloc(sizeof(card->raw_scr), GFP_KERNEL);
if (data_buf == NULL)
return -ENOMEM;
mrq.cmd = &cmd;
mrq.data = &data;
cmd.opcode = SD_APP_SEND_SCR;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 8;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, data_buf, 8);
mmc_set_data_timeout(&data, card);
mmc_wait_for_req(card->host, &mrq);
memcpy(scr, data_buf, sizeof(card->raw_scr));
kfree(data_buf);
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
scr[0] = be32_to_cpu(scr[0]);
scr[1] = be32_to_cpu(scr[1]);
return 0;
}
int mmc_sd_switch(struct mmc_card *card, int mode, int group,
u8 value, u8 *resp)
{
struct mmc_request mrq = {0};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
BUG_ON(!card);
BUG_ON(!card->host);
/* NOTE: caller guarantees resp is heap-allocated */
mode = !!mode;
value &= 0xF;
mrq.cmd = &cmd;
mrq.data = &data;
cmd.opcode = SD_SWITCH;
cmd.arg = mode << 31 | 0x00FFFFFF;
cmd.arg &= ~(0xF << (group * 4));
cmd.arg |= value << (group * 4);
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 64;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, resp, 64);
mmc_set_data_timeout(&data, card);
mmc_wait_for_req(card->host, &mrq);
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
return 0;
}
int mmc_app_sd_status(struct mmc_card *card, void *ssr)
{
int err;
struct mmc_request mrq = {0};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
BUG_ON(!card);
BUG_ON(!card->host);
BUG_ON(!ssr);
/* NOTE: caller guarantees ssr is heap-allocated */
err = mmc_app_cmd(card->host, card);
if (err)
return err;
mrq.cmd = &cmd;
mrq.data = &data;
cmd.opcode = SD_APP_SD_STATUS;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 64;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, ssr, 64);
mmc_set_data_timeout(&data, card);
mmc_wait_for_req(card->host, &mrq);
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
return 0;
}
|
JijonHyuni/HyperKernel-JB
|
virt/drivers/mmc/core/sd_ops.c
|
C
|
gpl-2.0
| 7,846
|
/* Copyright (c) 2011-2015, The Linux Foundation. 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 MSM_CAMERA_CCI_I2C_H
#define MSM_CAMERA_CCI_I2C_H
#include <linux/delay.h>
#include <media/v4l2-subdev.h>
#include <media/msm_cam_sensor.h>
struct msm_camera_i2c_client {
struct msm_camera_i2c_fn_t *i2c_func_tbl;
struct i2c_client *client;
struct msm_camera_cci_client *cci_client;
struct msm_camera_spi_client *spi_client;
enum msm_camera_i2c_reg_addr_type addr_type;
enum msm_camera_qup_i2c_write_batch_size_t batch_size;
};
struct msm_camera_i2c_fn_t {
int (*i2c_read) (struct msm_camera_i2c_client *, uint32_t, uint16_t *,
enum msm_camera_i2c_data_type);
int32_t (*i2c_read_seq)(struct msm_camera_i2c_client *, uint32_t,
uint8_t *, uint32_t);
int (*i2c_write) (struct msm_camera_i2c_client *, uint32_t, uint16_t,
enum msm_camera_i2c_data_type);
int (*i2c_write_seq) (struct msm_camera_i2c_client *, uint32_t ,
uint8_t *, uint32_t);
int32_t (*i2c_write_table)(struct msm_camera_i2c_client *,
struct msm_camera_i2c_reg_setting *);
int32_t (*i2c_write_seq_table)(struct msm_camera_i2c_client *,
struct msm_camera_i2c_seq_reg_setting *);
int32_t (*i2c_write_table_w_microdelay)
(struct msm_camera_i2c_client *,
struct msm_camera_i2c_reg_setting *);
int32_t (*i2c_util)(struct msm_camera_i2c_client *, uint16_t);
int32_t (*i2c_write_conf_tbl)(struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_conf *reg_conf_tbl, uint16_t size,
enum msm_camera_i2c_data_type data_type);
int32_t (*i2c_poll)(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t data,
enum msm_camera_i2c_data_type data_type);
int32_t (*i2c_read_burst)(struct msm_camera_i2c_client *client,
uint32_t read_byte, uint8_t *buffer, uint32_t addr,
enum msm_camera_i2c_data_type data_type);
int32_t (*i2c_write_burst)(struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_array *reg_setting, uint32_t reg_size,
uint32_t buf_len, uint32_t addr,
enum msm_camera_i2c_data_type data_type);
};
int32_t msm_camera_cci_i2c_read(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t *data,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_cci_i2c_read_seq(struct msm_camera_i2c_client *client,
uint32_t addr, uint8_t *data, uint32_t num_byte);
int32_t msm_camera_cci_i2c_write(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t data,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_cci_i2c_write_seq(struct msm_camera_i2c_client *client,
uint32_t addr, uint8_t *data, uint32_t num_byte);
int32_t msm_camera_cci_i2c_write_table(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_setting *write_setting);
int32_t msm_camera_cci_i2c_write_seq_table(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_seq_reg_setting *write_setting);
int32_t msm_camera_cci_i2c_write_table_w_microdelay(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_setting *write_setting);
int32_t msm_camera_cci_i2c_write_conf_tbl(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_conf *reg_conf_tbl, uint16_t size,
enum msm_camera_i2c_data_type data_type);
int32_t msm_sensor_cci_i2c_util(struct msm_camera_i2c_client *client,
uint16_t cci_cmd);
int32_t msm_camera_cci_i2c_poll(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t data,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_qup_i2c_read(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t *data,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_qup_i2c_read_seq(struct msm_camera_i2c_client *client,
uint32_t addr, uint8_t *data, uint32_t num_byte);
int32_t msm_camera_qup_i2c_write(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t data,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_qup_i2c_write_seq(struct msm_camera_i2c_client *client,
uint32_t addr, uint8_t *data, uint32_t num_byte);
int32_t msm_camera_qup_i2c_write_table(struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_setting *write_setting);
int32_t msm_camera_qup_i2c_write_seq_table(struct msm_camera_i2c_client *client,
struct msm_camera_i2c_seq_reg_setting *write_setting);
int32_t msm_camera_qup_i2c_write_table_w_microdelay(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_setting *write_setting);
int32_t msm_camera_qup_i2c_write_conf_tbl(
struct msm_camera_i2c_client *client,
struct msm_camera_i2c_reg_conf *reg_conf_tbl, uint16_t size,
enum msm_camera_i2c_data_type data_type);
int32_t msm_camera_qup_i2c_poll(struct msm_camera_i2c_client *client,
uint32_t addr, uint16_t data,
enum msm_camera_i2c_data_type data_type);
#endif
|
shakalaca/ASUS_ZenFone_ZE601KL
|
kernel/drivers/media/platform/msm/camera_v2/sensor/io/msm_camera_i2c.h
|
C
|
gpl-2.0
| 5,162
|
/******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License 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 Street, Fifth Floor, Boston, MA 02110, USA
*
*
******************************************************************************/
#ifndef __RTW_LED_H_
#define __RTW_LED_H_
#include <drv_conf.h>
#include <osdep_service.h>
#include <drv_types.h>
#define MSECS(t) (HZ * ((t) / 1000) + (HZ * ((t) % 1000)) / 1000)
typedef enum _LED_CTL_MODE{
LED_CTL_POWER_ON = 1,
LED_CTL_LINK = 2,
LED_CTL_NO_LINK = 3,
LED_CTL_TX = 4,
LED_CTL_RX = 5,
LED_CTL_SITE_SURVEY = 6,
LED_CTL_POWER_OFF = 7,
LED_CTL_START_TO_LINK = 8,
LED_CTL_START_WPS = 9,
LED_CTL_STOP_WPS = 10,
LED_CTL_START_WPS_BOTTON = 11, //added for runtop
LED_CTL_STOP_WPS_FAIL = 12, //added for ALPHA
LED_CTL_STOP_WPS_FAIL_OVERLAP = 13, //added for BELKIN
}LED_CTL_MODE;
#if defined(CONFIG_USB_HCI) || defined(CONFIG_SDIO_HCI)
//================================================================================
// LED object.
//================================================================================
typedef enum _LED_STATE_871x{
LED_UNKNOWN = 0,
RTW_LED_ON = 1,
RTW_LED_OFF = 2,
LED_BLINK_NORMAL = 3,
LED_BLINK_SLOWLY = 4,
LED_POWER_ON_BLINK = 5,
LED_SCAN_BLINK = 6, // LED is blinking during scanning period, the # of times to blink is depend on time for scanning.
LED_NO_LINK_BLINK = 7, // LED is blinking during no link state.
LED_BLINK_StartToBlink = 8,// Customzied for Sercomm Printer Server case
LED_BLINK_WPS = 9, // LED is blinkg during WPS communication
LED_TXRX_BLINK = 10,
LED_BLINK_WPS_STOP = 11, //for ALPHA
LED_BLINK_WPS_STOP_OVERLAP = 12, //for BELKIN
}LED_STATE_871x;
#define IS_LED_WPS_BLINKING(_LED_871x) (((PLED_871x)_LED_871x)->CurrLedState==LED_BLINK_WPS \
|| ((PLED_871x)_LED_871x)->CurrLedState==LED_BLINK_WPS_STOP \
|| ((PLED_871x)_LED_871x)->bLedWPSBlinkInProgress)
#define IS_LED_BLINKING(_LED_871x) (((PLED_871x)_LED_871x)->bLedWPSBlinkInProgress \
||((PLED_871x)_LED_871x)->bLedScanBlinkInProgress)
typedef enum _LED_PIN_871x{
LED_PIN_GPIO0,
LED_PIN_LED0,
LED_PIN_LED1
}LED_PIN_871x;
typedef struct _LED_871x{
_adapter *padapter;
LED_PIN_871x LedPin; // Identify how to implement this SW led.
LED_STATE_871x CurrLedState; // Current LED state.
u8 bLedOn; // true if LED is ON, false if LED is OFF.
u8 bSWLedCtrl;
u8 bLedBlinkInProgress; // true if it is blinking, false o.w..
// ALPHA, added by chiyoko, 20090106
u8 bLedNoLinkBlinkInProgress;
u8 bLedLinkBlinkInProgress;
u8 bLedStartToLinkBlinkInProgress;
u8 bLedScanBlinkInProgress;
u8 bLedWPSBlinkInProgress;
u32 BlinkTimes; // Number of times to toggle led state for blinking.
LED_STATE_871x BlinkingLedState; // Next state for blinking, either RTW_LED_ON or RTW_LED_OFF are.
_timer BlinkTimer; // Timer object for led blinking.
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0)|| defined PLATFORM_FREEBSD
_workitem BlinkWorkItem; // Workitem used by BlinkTimer to manipulate H/W to blink LED.
#endif
} LED_871x, *PLED_871x;
//================================================================================
// LED customization.
//================================================================================
typedef enum _LED_STRATEGY_871x{
SW_LED_MODE0, // SW control 1 LED via GPIO0. It is default option.
SW_LED_MODE1, // 2 LEDs, through LED0 and LED1. For ALPHA.
SW_LED_MODE2, // SW control 1 LED via GPIO0, customized for AzWave 8187 minicard.
SW_LED_MODE3, // SW control 1 LED via GPIO0, customized for Sercomm Printer Server case.
SW_LED_MODE4, //for Edimax / Belkin
SW_LED_MODE5, //for Sercomm / Belkin
SW_LED_MODE6, //for 88CU minicard, porting from ce SW_LED_MODE7
HW_LED, // HW control 2 LEDs, LED0 and LED1 (there are 4 different control modes, see MAC.CONFIG1 for details.)
}LED_STRATEGY_871x, *PLED_STRATEGY_871x;
#endif //CONFIG_USB_HCI
#ifdef CONFIG_PCI_HCI
//================================================================================
// LED object.
//================================================================================
typedef enum _LED_STATE_871x{
LED_UNKNOWN = 0,
RTW_LED_ON = 1,
RTW_LED_OFF = 2,
LED_BLINK_NORMAL = 3,
LED_BLINK_SLOWLY = 4,
LED_POWER_ON_BLINK = 5,
LED_SCAN_BLINK = 6, // LED is blinking during scanning period, the # of times to blink is depend on time for scanning.
LED_NO_LINK_BLINK = 7, // LED is blinking during no link state.
LED_BLINK_StartToBlink = 8,
LED_BLINK_TXRX = 9,
LED_BLINK_RUNTOP = 10, // Customized for RunTop
LED_BLINK_CAMEO = 11,
}LED_STATE_871x;
typedef enum _LED_PIN_871x{
LED_PIN_GPIO0,
LED_PIN_LED0,
LED_PIN_LED1,
LED_PIN_LED2
}LED_PIN_871x;
typedef struct _LED_871x{
_adapter *padapter;
LED_PIN_871x LedPin; // Identify how to implement this SW led.
LED_STATE_871x CurrLedState; // Current LED state.
u8 bLedOn; // TRUE if LED is ON, FALSE if LED is OFF.
u8 bLedBlinkInProgress; // TRUE if it is blinking, FALSE o.w..
u8 bLedWPSBlinkInProgress; // TRUE if it is blinking, FALSE o.w..
u8 bLedSlowBlinkInProgress;//added by vivi, for led new mode
u32 BlinkTimes; // Number of times to toggle led state for blinking.
LED_STATE_871x BlinkingLedState; // Next state for blinking, either RTW_LED_ON or RTW_LED_OFF are.
_timer BlinkTimer; // Timer object for led blinking.
u8 bLedLinkBlinkInProgress;
u8 bLedNoLinkBlinkInProgress;
u8 bLedScanBlinkInProgress;
} LED_871x, *PLED_871x;
//================================================================================
// LED customization.
//================================================================================
typedef enum _LED_STRATEGY_871x{
SW_LED_MODE0, // SW control 1 LED via GPIO0. It is default option.
SW_LED_MODE1, // SW control for PCI Express
SW_LED_MODE2, // SW control for Cameo.
SW_LED_MODE3, // SW contorl for RunTop.
SW_LED_MODE4, // SW control for Netcore
SW_LED_MODE5, //added by vivi, for led new mode, DLINK
SW_LED_MODE6, //added by vivi, for led new mode, PRONET
SW_LED_MODE7, //added by chiyokolin, for Lenovo, PCI Express Minicard Spec Rev.1.2 spec
SW_LED_MODE8, //added by chiyokolin, for QMI
SW_LED_MODE9, //added by chiyokolin, for BITLAND, PCI Express Minicard Spec Rev.1.1
SW_LED_MODE10, //added by chiyokolin, for Edimax-ASUS
HW_LED, // HW control 2 LEDs, LED0 and LED1 (there are 4 different control modes)
}LED_STRATEGY_871x, *PLED_STRATEGY_871x;
#define LED_CM8_BLINK_INTERVAL 500 //for QMI
#endif //CONFIG_PCI_HCI
struct led_priv{
/* add for led controll */
LED_871x SwLed0;
LED_871x SwLed1;
LED_STRATEGY_871x LedStrategy;
u8 bRegUseLed;
void (*LedControlHandler)(_adapter *padapter, LED_CTL_MODE LedAction);
/* add for led controll */
};
#ifdef CONFIG_SW_LED
#define rtw_led_control(adapter, LedAction) \
do { \
if((adapter)->ledpriv.LedControlHandler) \
(adapter)->ledpriv.LedControlHandler((adapter), (LedAction)); \
} while(0)
#else //CONFIG_SW_LED
#define rtw_led_control(adapter, LedAction)
#endif //CONFIG_SW_LED
extern void BlinkHandler(PLED_871x pLed);
#endif //__RTW_LED_H_
|
21zaber/Utils
|
wifi-fix/include/rtw_led.h
|
C
|
gpl-3.0
| 7,950
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.